python调用千问大模型
一、安装openai
pip3 install openai==1.60.0
验证环境
openai -V
由于某种原因直接安装可能会失败,可以使用国内的镜像,在用户目录下创建.pip文件夹,添加pip.ini文件,填入一下内容:
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple/
二、百炼申请api-key
https://bailian.console.aliyun.com/model-market?tab=model#/model-market
三、代码调用
import os
from openai import OpenAIdef qwen():print('Hello World @@@')client = OpenAI(#填写控制台申请的api-keyapi_key="sk-*******", base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",)completion = client.chat.completions.create(# 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/modelsmodel="qwen-plus", messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},{'role': 'user', 'content': '请介绍金庸小说<<飞狐外传>>的故事梗概'}])ret=completion.choices[0].message.contentprint(ret)def main():qwen()while True:print("press enter exit ...")input()if __name__ == '__main__':main()
模型返回结果