(1)设置 LangSmith 环境变量,用于追踪模型执行
importos# 1. 设置 LangSmith 环境变量 (用于追踪)os.environ["LANGSMITH_TRACING"]="true"os.environ["LANGSMITH_API_KEY"]="api_key"# 请替换为真实的 Keyos.environ["LANGSMITH_ENDPOINT"]="https://api.smith.langchain.com"# 建议检查 endpointos.environ["LANGSMITH_PROJECT"]="llm_server"# 替换为真实项目名称(2)创建模型实例
fromlangchain_ollama.chat_modelsimportChatOllama# 创建模型实例model=ChatOllama(model="qwen3.5:latest",base_url="http://IP:11434")(3)创建输出解析器实例
fromlangchain_core.output_parsersimportStrOutputParser# 创建输出解析器实例parser=StrOutputParser()(4)创建提示词模板
fromlangchain_core.promptsimportChatPromptTemplate# 创建提示模板实例system_template="你是一个翻译大师,请把以下文本翻译成{language}"prompt_template=ChatPromptTemplate.from_messages([("system",system_template),("human","{text}"),])(5)创建 Chain
# 使用LCEL链接组件chain=prompt_template|model|parser(6)使用 LangServe 部署应用,提供 API 接口
LangServe 的核心优势在于它能自动将 LangChain 的 Runnable 对象转换为标准的 REST API 端点,并自动生成 Playground 界面。
自动生成接口为:
流式应答接口:/xxx/stream
一次响应接口:/xxx/invoke
安装langserve
pip install langserve开发fastapi服务
fromfastapiimportFastAPIfromlangserveimportadd_routesfromfastapi.middleware.corsimportCORSMiddleware# 1、创建appapp=FastAPI(title="LangChain Server",description="翻译小工具",version="0.0.1",)# 2、添加路由add_routes(app,chain,path="/chain")# 3、跨域支持app.add_middleware(CORSMiddleware,allow_origins=["*"],# 生产环境请指定具体域名allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)if__name__=="__main__":importuvicorn uvicorn.run(app,host="0.0.0.0",port=8000)(7)API 测试方法
- 启动服务
python server.py
如图显示则表示服务启动成功
访问 Playground:打开浏览器访问http://localhost:8000/chat/playground,如图所示。
使用接口测试工具访问
使用 python 客户端访问
fromlangserveimportRemoteRunnable remote_chain=RemoteRunnable("http://localhost:8000/chain/")remote_chain.invoke({"language":"italian","text":"hi"})(8)完整代码
fromlangchain_ollama.chat_modelsimportChatOllamafromlangchain_core.output_parsersimportStrOutputParserfromlangchain_core.promptsimportChatPromptTemplateimportos# 1. 设置 LangSmith 环境变量 (用于追踪)os.environ["LANGSMITH_TRACING"]="true"os.environ["LANGSMITH_API_KEY"]="API_Key"# 请替换为真实的 Keyos.environ["LANGSMITH_ENDPOINT"]="https://api.smith.langchain.com"# 建议检查 endpointos.environ["LANGSMITH_PROJECT"]="llm_server"# 创建模型实例model=ChatOllama(model="qwen3.5:latest",base_url="http://IP:11434")# 创建输出解析器实例parser=StrOutputParser()# 创建提示模板实例system_template="把以下文本翻译成{language}"prompt_template=ChatPromptTemplate.from_messages([("system",system_template),("human","{text}"),])# 使用LCEL链接组件chain=prompt_template|model|parserfromfastapiimportFastAPIfromlangserveimportadd_routesfromllm_serverimportchain# 1、创建appapp=FastAPI(title="LangChain Server",description="翻译小工具",version="0.0.1",)# 2、添加路由add_routes(app,chain,path="/chain")# 3、跨域支持app.add_middleware(CORSMiddleware,allow_origins=["*"],# 生产环境请指定具体域名allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)if__name__=="__main__":importuvicorn uvicorn.run(app,host="0.0.0.0",port=8000)