阿里千问Qwen大模型API调用(Python版)
一、API_KEY配置
1、登陆阿里百炼平台,单击创建我的API-KEY。
2、访问业务空间管理界面,找到需要授权的子业务空间后,单击其右侧的模型权限流控设置。
3、选择需要的模型,编辑权限,并保存
二、API调用
1、加载url图片
- 传入图像URL进行图像理解的示例代码(python):
import os
from openai import OpenAIclient = OpenAI(api_key=os.getenv("DASHSCOPE_API_KEY"),base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)completion = client.chat.completions.create(model="qwen-vl-max-latest", # 此处以qwen-vl-max-latest为例,可按需更换模型名称。模型列表:https://help.aliyun.com/model-studio/getting-started/modelsmessages=[{"role": "system","content": [{"type": "text", "text": "You are a helpful assistant."}],},{"role": "user","content": [{"type": "image_url","image_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"},},{"type": "text", "text": "图中描绘的是什么景象?"},],},],
)print(completion.choices[0].message.content)
- 通过curl方式获取结果:
curl --location 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{"model": "qwen-vl-max","messages": [{"role":"system","content":[{"type": "text", "text": "You are a helpful assistant."}]},{"role": "user","content": [{"type": "image_url", "image_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"}},{"type": "text", "text": "图中描绘的是什么景象?"}]}]
}'
2、加载本地图片
- 加载本地图片进行图像理解:需要将本地文件编码为Base64格式后再传入
from openai import OpenAI
import os
import base64# base 64 编码格式
def encode_image(image_path):with open(image_path, "rb") as image_file:return base64.b64encode(image_file.read()).decode("utf-8")# 将xxxx/eagle.png替换为你本地图像的绝对路径
base64_image = encode_image("xxx/eagle.png")client = OpenAI(# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"api_key=os.getenv('DASHSCOPE_API_KEY'),base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(model="qwen-vl-max-latest", # 此处以qwen-vl-max-latest为例,可按需更换模型名称。模型列表:https://help.aliyun.com/model-studio/getting-started/modelmessages=[{"role": "system","content": [{"type":"text","text": "You are a helpful assistant."}]},{"role": "user","content": [{"type": "image_url",# 需要注意,传入Base64,图像格式(即image/{format})需要与支持的图片列表中的Content Type保持一致。"f"是字符串格式化的方法。# PNG图像: f"data:image/png;base64,{base64_image}"# JPEG图像: f"data:image/jpeg;base64,{base64_image}"# WEBP图像: f"data:image/webp;base64,{base64_image}""image_url": {"url": f"data:image/png;base64,{base64_image}"}, },{"type": "text", "text": "图中描绘的是什么景象?"},],}],
)
print(completion.choices[0].message.content)
官方参考链接:https://help.aliyun.com/zh/model-studio/vision?spm=a2c4g.11186623.0.0.349c2562o1Fzsi#da33480805fjh