python调用阿里通义千问大模型
开通百炼大模型服务,然后创建API-KEY
import os
from openai import OpenAI
try:
client = OpenAI(
#若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
#api_key=os.getenv("DASHSCOPE_API_KEY"),
api_key="sk-5983xxxxxxxxxxxxxxxxxxxff", # 这里换成自己的API-KEY就行了
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-plus", # 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '卷帘大将是干嘛的?掀帘子的吗?'}
]
)
print(completion.choices[0].message.content)
except Exception as e:
print(f"错误信息:{e}")
print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
阿里云使用手册:https://help.aliyun.com/zh/model-studio/developer-reference/deepseek?spm=5176.smartservice_service_robot_chat_new.0.0.cbd643ec4IyfDi