langchain 学习 制作一个简单的 llm 对话程序
- SystemMessage 和 HumanMessage 是 LangChain 中的消息类型。
- ChatOllama 是用于连接本地 Ollama 服务的接口。
- StrOutputParser 用于将模型输出转换为字符串。
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_ollama import ChatOllama
from langchain_core.output_parsers import StrOutputParser
model = ChatOllama(
base_url= "http://127.0.0.1:11434",
model="qwen2.5:32b-instruct-q5_K_S",
temperature=0.7)
messages = [
SystemMessage(content="你是世界级技术专家"),
HumanMessage(content="帮我写一篇关于ai 的文章, 100个字"),
]
## 调用模型
result = model.invoke(messages)
print(result.content)
## 格式化输出
parser = StrOutputParser()
print(parser.invoke(result))
## 链
chain = model | parser
print(chain.invoke(messages))
使用了 langchain 的模块来构建一个翻译任务的链式处理流程。你定义了一个提示模板(ChatPromptTemplate),连接了一个本地部署的大模型(ChatOllama),并最终通过字符串输出解析器(StrOutputParser)将结果转换为字符串。
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_ollama import ChatOllama
from langchain_core.output_parsers import StrOutputParser
system_template = "Translate the following into {language}:"
prompt_template = ChatPromptTemplate.from_messages(
[("system", system_template), ("user", "{text}")]
)
result = prompt_template.invoke({"language": "italian", "text": "hi"})
print(result.to_messages())
## 自我封装
## [SystemMessage(content='Translate the following into italian:', additional_kwargs={}, response_metadata={}), HumanMessage(content='hi', additional_kwargs={}, response_metadata={})]
model = ChatOllama(
base_url= "http://127.0.0.1:11434",
model="qwen2.5:32b-instruct-q5_K_S",
temperature=0.7)
parser = StrOutputParser()
chain = prompt_template | model | parser
result = chain.invoke({"language": "italian", "text": "hi"})
print(result)
定义系统模板和用户输入模板:
system_template = "Translate the following into {language}:"
prompt_template = ChatPromptTemplate.from_messages(
[("system", system_template), ("user", "{text}")]
)
这里,你首先定义了一个系统级别的提示(system_template),它包含一个占位符 {language},用于指定目标语言。然后,你创建了一个 ChatPromptTemplate,它接受系统提示和用户提示(同样含有一个占位符 {text})。 构造消息: 当你调用 prompt_template.invoke({"language": "italian", "text": "hi"}) 时,ChatPromptTemplate 会根据传入的字典替换掉模板中的占位符,生成最终的消息。在这个例子中,生成的消息将会是:
- 系统消息:Translate the following into italian:
- 用户消息:hi
链式调用与输出解析:
chain = prompt_template | model | parser
result = chain.invoke({"language": "italian", "text": "hi"})
最后,你构建了一个处理链,它从构造消息开始,经过模型推理,最后通过 StrOutputParser 解析模型的输出为字符串格式。
langserve使用
使用 LangChain 和 FastAPI 构建的简单服务端程序,它通过 langserve 提供了一个 REST API 接口来运行一个翻译链(chain)。整体结构非常清晰、规范。
主要用途
- 简化集成:自动为你的 LangChain Runnable 创建 HTTP 接口,极大地减少了设置和配置的工作量。
- 快速部署:使你能够迅速将自然语言处理模型或其它复杂流程暴露为服务端点,方便在生产环境中使用。
- 标准化接口:提供了一套标准化的输入输出格式,便于客户端与服务端交互。
langserve.add_routes() 是 LangServe 库中的一个实用函数,用于将 LangChain 的 Runnable 对象快速集成到 FastAPI 应用中,并自动为其生成相应的 HTTP 路由。这使得开发者能够轻松地通过 REST API 来调用 LangChain 流程(如文本处理、翻译、问答等),而无需手动编写路由逻辑。
add_routes(app, chain, path="/chain") 实际上做了以下几件事情:
- 在 FastAPI 应用 app 上添加了一个新的路径 /chain。
- 这个路径会接收 POST 请求,请求体应包含 JSON 格式的输入数据(例如,{"input": {"language": "italian", "text": "hi"}})。
- 当收到请求时,它会将输入传递给之前定义的 chain,执行整个过程(即根据提示构造消息、调用模型、解析结果)。
- 最后,返回处理后的结果作为 HTTP 响应。
from fastapi import FastAPI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_ollama import ChatOllama
from langserve import add_routes
# 1. Create prompt template
system_template = "Translate the following into {language}:"
prompt_template = ChatPromptTemplate.from_messages([
('system', system_template),
('user', '{text}')
])
# 2. Create model
model = ChatOllama(
base_url= "http://192.168.5.240:11434",
model="qwen2.5:32b-instruct-q5_K_S",
temperature=0.7)
# 3. Create parser
parser = StrOutputParser()
# 4. Create chain
chain = prompt_template | model | parser
# 4. App definition
app = FastAPI(
title="LangChain Server",
version="1.0",
description="A simple API server using LangChain's Runnable interfaces",
)
# 5. Adding chain route
add_routes(
app,
chain,
path="/chain",
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)