AI学习_05_LangChain使用

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)
相关推荐
春风解人意6 小时前
从零开始学习嵌入式P32----网络基础之TCP
c语言·网络·学习·tcp/ip
传奇开心果编程8 小时前
【Rust入门知识点学与练】第21课:Trait 进阶 Advanced Traits
开发语言·学习·rust
水巷石子8 小时前
备考系统架构设计师第一天
学习·架构·软考·设计·考试
是隼人9 小时前
buuctf-pwn inndy_echo(32位fmt)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
ToTensor9 小时前
DataGen——合成数据生成器:把一句任务描述变成可校验的训练数据
langchain·agent
xian_wwq9 小时前
【学习笔记】深度认知系列-第16讲-提示词工程
人工智能·笔记·学习
洛阳纸贵10 小时前
MATLAB-matlab基础知识
学习·算法·matlab
Vcaker10 小时前
Linux学习25-harbor私有仓库部署
linux·运维·学习
留白_10 小时前
【tableau入门学习】5、筛选器、参考线和集
学习·tableau
youm200310 小时前
认识Redis
redis·笔记·学习