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)
相关推荐
inferno7 小时前
SVN学习笔记(二)
笔记·学习·svn
传奇开心果编程7 小时前
【ArkUI进阶练中学】第12课:应用架构演进与遗留系统迁移
学习·ui·华为·harmonyos
我想我不够好。7 小时前
装一个纯净的系统
学习
小黄蚁8 小时前
使用LVGL模拟示波器创建正弦函数波形
单片机·学习
打工仔折腾 AI8 小时前
把 AI Agent 托管到家里电脑:UU远程端口映射与CLI实测记录
人工智能·后端·python·langchain·电脑·ai agent 实战
辣知8 小时前
辣知·化智71 四川广汉三星堆的金铜贝
学习
天天进步20158 小时前
90天AI接单学习路线:从LLM应用到AI Agent
人工智能·学习
vx_Biye_Design8 小时前
springboot小学生英语学习APP62773-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·学习·课程设计
@Mike@9 小时前
13-数据库学习笔记(查询执行处理模型)
数据库·笔记·学习
染指11109 小时前
135.Agent-多Agent框架-LangChain多智能体(SubAgents子代理)
数据库·人工智能·设计模式·langchain·agent·agents