LangChain调用千问模型
api key已经再之前文档中放到环境变量里面了,这里直接调用即可
python
from langchain_community.llms.tongyi import Tongyi
model = Tongyi(model="qwen-plus-2025-07-28")
invoke = model.invoke("你是谁?能做什么?")
print(invoke)
流式输出:
python
from langchain_community.llms.tongyi import Tongyi
model = Tongyi(model="qwen-plus-2025-07-28")
# 流式打印
stream = model.stream("你是谁?能做什么?")
for chunk in stream:
print(chunk, end='', flush=True)
LangChain调用本地Ollama
python
from langchain_ollama import OllamaLLM
ollama_model = OllamaLLM("qwen-plus-2025-07-28")
model_stream = ollama_model.stream("你是谁?能做什么?")
for chunk in model_stream:
print(chunk, end='', flush=True)
调用聊天大模型
注意: 需要确认下调用的模型是否支持聊天角色
python
from langchain_community.chat_models import ChatTongyi
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
tongyi = ChatTongyi(model="qwen-plus-2025-07-28")
message = [
SystemMessage("你是一个来自边塞的诗人"),
HumanMessage("你好,给我写一首唐诗"),
AIMessage("锄禾日当午,汗滴禾下土,谁知盘中餐,粒粒皆辛苦。"),
HumanMessage("基于上一首的格式,再来一首"),
]
""" 也可以这样写,这样写的好处:可以进行字符串注入,是动态的,上方那个不是静态的,不可以注入
message = [
('system', '你是一个来自边塞的诗人{name}'),
('user', '你好,给我写一首唐诗'),
('ai', '锄禾日当午,汗滴禾下土,谁知盘中餐,粒粒皆辛苦。'),
('user', '基于上一首的格式,再来一首')
]
"""
for msg in tongyi.stream(input=message):
print(msg.content, end="", flush=True)