longchain使用通义千问
1.安装第三方库
确保你的python版本大于3.8.1
不然会有以下报错
ERROR: Ignored the following versions that require a different python version: 0.0.1 Requires-Python >=3.8.1,<4.0; 0.0.10 Requires-Python >=3.8.1,<4.0; 0.0.11 Requires-Python >=3.8.1,<4.0; 0.0.12 Requires-Python >=3.8.1,<4.0; 0.0.13 Requires-Python >=3.8.1,<4.0; 0.0.14 Requires-Python >=3.8.1,<4.0; 0.0.15 Requires-Python >=3.8.1,<4.0;
ERROR: Could not find a version that satisfies the requirement langchain_community (from versions: none)
ERROR: No matching distribution found for langchain_community
我使用了3.10版本的python,按照第三方库:
python -m pip install longchain langchain-community dashscope openai==1.7.0 -i https://mirrors.aliyun.com/pypi/simple
2.直接调用通义千问
from openai import OpenAIclient = OpenAI(api_key="", # 如何获取API Key:https://help.aliyun.com/zh/model-studio/developer-reference/get-api-keybase_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/modelsmessages=[{'role': 'system', 'content': 'You are a helpful assistant.'},{'role': 'user', 'content': '你是谁?'}]
)
print(completion.choices[0].message.content)
3.使用langchain调用通义千问
from openai import OpenAI
from langchain_community.llms.tongyi import Tongyi
from langchain.prompts.prompt import PromptTemplate
# 设置 API Key(推荐使用环境变量或文件)
import os
os.environ['DASHSCOPE_API_KEY'] = ''def translate():model = Tongyi(model_name='qwen-max',model_kwargs={'temperature': 0.01})prompt_template = PromptTemplate.from_template('你是英语翻译官,对用户的输入翻译成英文,不要解释。\n\n{input}')user_input = input('请输入要翻译的中文:')print('1.用户输入的内容是:', user_input)prompt = prompt_template.format(input=user_input)print(f'2.生成翻译英文的prompts:{prompt}')print(f'3.调用大模型')res = model.invoke(prompt)print(f"4.输出翻译后的英文内容:", res)
translate()