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)
相关推荐
葫芦和十三19 小时前
渐进发现|代码库不是文档库
langchain·agent·ai编程
柒和远方1 天前
LangGraph 深度解析:从增强型 LLM 到生产级 Agent
langchain·llm·agent
通信小呆呆2 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
H__Rick2 天前
自动对焦学习-3
人工智能·学习·计算机视觉
Daisy Lee2 天前
量化学习-第1章-什么是量化金融
学习·金融·datawhale
Alsn862 天前
等待学习-学习目录:Docker 容器安全攻防
学习·安全·docker
YM52e2 天前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统
小雨下雨的雨2 天前
HarmonyOS ArkUI训练营入门-组件掌握系列-Animation 动画效果实现-PC版本
学习·华为·harmonyos·鸿蒙
cqbzcsq2 天前
CellFlow虚拟细胞论文阅读
论文阅读·人工智能·笔记·学习·生物信息
YangYang9YangYan2 天前
2026初入职场学习数据分析的价值
学习·数据挖掘·数据分析