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 小时前
LangChain python 版本 第一集
开发语言·python·langchain
星幻元宇VR6 小时前
公共安全实训展厅设备【人防知识学习系统】
科技·学习·安全
YIAN7 小时前
LangChain JS 工具调用实战:基于 DeepSeek-V4-Flash 实现本地文件读取 AI 代码助手(完整可运行源码)
javascript·langchain·前端框架
齐 飞8 小时前
LangGraph快速入门-02状态
人工智能·langchain
心中有国也有家9 小时前
AtomGit Flutter 鸿蒙客户端:情绪日记的时间线实现
学习·flutter·华为·harmonyos
椰椰椰耶10 小时前
【LangChain系列十二】RAG全流程下:从零搭建知识问答系统
langchain
Darling噜啦啦10 小时前
手写 mini-cursor 完整版:从 Promise 子进程到 ReAct 循环,30 轮迭代完成 TodoList 全流程
langchain·agent
百里香酚兰10 小时前
【python学习笔记】pyttsx3库疑似只播报一次语音
笔记·python·学习
飞猪~11 小时前
Langchain python版本 LLM 重要函数invoke,ainvoke,stream,astream,batch,abatch
python·langchain·batch
恣逍信点11 小时前
《凌微经》助读:本体论根基——“无之自悖”与“形性一体”
人工智能·科技·学习·程序人生·生活·交友·哲学