python通过openai接口与配置文件.env使用通义千问API
·
首先,参考https://help.aliyun.com/zh/model-studio/get-api-key文章获取通义千问的API,一般是"sk-xxxxxx"
文章目录
接下来在代码中配置:
示例程序
1. 新建.env文件
在目录中新建一个.env文件,写入下面的内容:
DASHSCOPE_API_KEY="sk-xxxx"
2. 调用AI的文件
from dotenv import load_dotenv
import os
load_dotenv() # 加载 .env 文件到环境变量
db_host = os.getenv("DASHSCOPE_API_KEY") # 这里测试一下环境变量有没有加载进来
print(db_host)
def qwe_ai_model():
import os
from openai import OpenAI
try:
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(
# 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
model="qwen-plus",
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")
if __name__ == '__main__':
qwe_ai_model()
即可得到结果!
更多推荐

所有评论(0)