langchain调用大模型

LangChain

langchain环境地址

https://docs.langchain.com/oss/python/langchain/overview

LangChain环境安装对接阿里云百炼

LangChain本质上上一个Python框架,要部署LangChain环境可以通过pip命令安装对应的包即可。命令如下:

pip install langchain -i https://pypi.tuna.tsinghua.edu.cn/simple

pip install langchain-community -i https://pypi.tuna.tsinghua.edu.cn/simple

pip install dashscope -i https://pypi.tuna.tsinghua.edu.cn/simple

langchain:大模型应用开发核心框架,提供链、记忆、检索等功能

langchain_community:LangChain社区贡献组件,含第三方工具、模型集成

dashscope:阿里云官方的大模型开发Python库,用于调用通义千问(Qwen)等阿里系大模型的API,实现对话、生成、推理等功能。

langchain调用大模型非流式输出

python 复制代码
from langchain_community.llms.tongyi import Tongyi

#qwen-max是大语言模型
model = Tongyi(model="qwen-max")

res = model.invoke(input="你是谁呀能做什么?")

print(res)

langchain调用大模型流式输出

python 复制代码
from langchain_community.llms.tongyi import Tongyi

#qwen-max是大语言模型
model = Tongyi(model="qwen-max")

res = model.stream(input="你是谁呀能做什么?")

for chunk in res:
    print(chunk,end="",flush=True)

langchain聊天模型的调用

python 复制代码
from langchain_community.chat_models.tongyi import ChatTongyi
from langchain_core.messages import HumanMessage,AIMessage,SystemMessage

#得到模型对象,qwen3-max就是聊天模型

model = ChatTongyi(model="qwen3-max")

#准备消息列表
messages = [
    SystemMessage(content="你是一个边塞诗人"),
    HumanMessage(content="写一首唐诗"),
    AIMessage(content="锄禾日当午,汗滴禾下土,谁知盘中餐,粒粒皆辛苦"),
    HumanMessage(content="请按照上一个回复的格式,再写一首唐诗")
]

#调用stream流式执行
res = model.stream(input=messages)

#for 循环迭代打印输出,通过content来获取到内容
for chunk in res:
    print(chunk.content,end="",flush=True)

消息的简写

python 复制代码
from langchain_community.chat_models.tongyi import ChatTongyi

#得到模型对象,qwen3-max就是聊天模型

model = ChatTongyi(model="qwen3-max")

#准备消息列表
messages = [
    ("system","你是一个边塞诗人"),
    ("human","写一首唐诗"),
    ("ai","锄禾日当午,汗滴禾下土,谁知盘中餐,粒粒皆辛苦"),
    ("human","请按照上一个回复的格式,再写一首唐诗")
]

#调用stream流式执行
res = model.stream(input=messages)

#for 循环迭代打印输出,通过content来获取到内容
for chunk in res:
    print(chunk.content,end="",flush=True)

langchain调用嵌入模型

python 复制代码
from langchain_community.embeddings import DashScopeEmbeddings

#创建模型对象 不传model默认用的是 text-embedding-v1
model = DashScopeEmbeddings()

#不用invoke stream
#embed_query、embed_documents
print(model.embed_query("我喜欢你"))
print(model.embed_documents(["我喜欢你","我稀饭你","晚上吃啥"]))
相关推荐
索西引擎14 小时前
【LangChain 1.0】 接入 Ollama:在本地跑通 DeepSeek-R1 的完整指南
langchain
染指111017 小时前
12.LangChain框架4-输出解释器
人工智能·langchain·rag
索西引擎19 小时前
【LangChain 1.0】环境搭建指南:从 conda 到 uv 的现代化 Python 工程实践
python·langchain·conda
云姜.19 小时前
Langchain快速上手编程-Runnable 与 LCEL
java·开发语言·langchain
Coder小相20 小时前
LangChain1.0第四篇 - 统一接口多厂商模型适配
人工智能·langchain·agent
PeterLi21 小时前
LangChain v1.x 最新官方完整教程(六大核心组件全解析+生产级代码示例)
langchain·agent
Irissgwe1 天前
十、LangGraph能力详解(1)LangGraph介绍及核心概念
python·ai·langchain·ai编程·工作流·langgraph
索西引擎1 天前
【LangChain 1.0】接入 DeepSeek API:从 API Key 申请到流式响应的完整实践
android·java·langchain
索西引擎1 天前
【LangChain 1.0】 语义搜索实战:从 PDF 文档到向量知识库的完整 RAG 链路
langchain·pdf