LangChain LangServe 学习笔记

LangChain LangServe 学习笔记

  • [0. 引言](#0. 引言)
  • [1. LangServe 概述](#1. LangServe 概述)
  • [2. 特性](#2. 特性)
  • [3. 限制](#3. 限制)
  • [4. 安装](#4. 安装)
  • [5. 示例应用程序](#5. 示例应用程序)
  • [6. OpenAPI文档](#6. OpenAPI文档)
  • [7. Python SDK 客户端](#7. Python SDK 客户端)
  • [8. Playground](#8. Playground)
  • [9. 聊天可运行页面](#9. 聊天可运行页面)

0. 引言

使用 LangServe 可以立即将您的LLM应用程序变成 API 服务器。

LangServe 使用 FastAPI 构建,为您的 LangChain 应用程序提供 API、文档和 Playground,进入生产变得更加容易。

1. LangServe 概述

LangServe 帮助开发人员将 LangChain 可运行对象(runnables)和链部署为 REST API。

该库与 FastAPI 集成,并使用 pydantic 进行数据验证。

此外,它还提供了一个客户端,可用于调用服务器上部署的可运行对象。JavaScript 客户端在 LangChain.js 中可用。

2. 特性

  • LangChain对象自动推断的输入和输出模式,并在每次API调用中强制执行,提供丰富的错误消息
  • 具有JSONSchema和Swagger的API文档页面
  • 高效的/invoke/、/batch/和/stream/端点,支持单个服务器上的许多并发请求
  • /stream_log/端点,用于从您的链/代理流式传输所有(或部分)中间步骤
  • 新的0.0.40版本支持astream_events,使流式传输更加轻松,无需解析stream_log的输出
  • 在/playground/上的Playground页面,具有流式输出和中间步骤
  • 所有内容都是使用经过实战检验的开源Python库构建的,例如FastAPI、Pydantic、uvloop和asyncio。
  • 使用客户端SDK调用LangServe服务器,就像在本地运行的Runnable一样(或直接调用HTTP API)

3. 限制

  • 客户端回调尚不支持在服务器上发起的事件
  • 在使用Pydantic V2时不会生成OpenAPI文档。FastAPI不支持混合使用pydantic v1和v2命名空间。

4. 安装

对于客户端和服务器都是:

pip install "langserve[all]"

或者对于客户端代码,使用pip install "langserve[client]",对于服务器代码使用pip install "langserve[server]"

5. 示例应用程序

以下是一个部署OpenAI聊天模型、Anthropic聊天模型以及使用Anthropic模型讲述关于某个主题笑话的链的服务器。

# server.py
import os

from dotenv import load_dotenv, find_dotenv
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from langchain.prompts import ChatPromptTemplate
from langchain_anthropic import ChatAnthropic
from langchain_openai import ChatOpenAI
from langserve import add_routes

_ = load_dotenv(find_dotenv())

app = FastAPI(
    title="LangChain Server",
    version="1.0",
    description="A simple api server using Langchain's Runnable interfaces",
)

# Set all CORS enabled origins
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["*"],
)

add_routes(
    app,
    ChatOpenAI(model_name="gpt-4", base_url=os.environ['OPENAI_BASE_URL']),
    path="/openai",
)

add_routes(
    app,
    ChatAnthropic(model_name="claude-3-opus-20240229"),
    path="/anthropic",
)

model = ChatAnthropic(model_name="claude-3-sonnet-20240229")
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
add_routes(
    app,
    prompt | model,
    path="/joke",
)

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="localhost", port=8000)

6. OpenAPI文档

如果您已部署了上述服务器,您可以使用以下命令查看生成的OpenAPI文档:

如果使用pydantic v2,则不会为invoke、batch、stream、stream_log生成文档。

使用浏览器打开 http://localhost:8000/docs

7. Python SDK 客户端

# client.py
import asyncio
import time

from langchain.schema.runnable import RunnableMap
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.prompts import ChatPromptTemplate
from langserve import RemoteRunnable

openai = RemoteRunnable("http://localhost:8000/openai/")
anthropic = RemoteRunnable("http://localhost:8000/anthropic/")
joke_chain = RemoteRunnable("http://localhost:8000/joke/")

# Method-1
joke_response = joke_chain.invoke({"topic": "parrots"})
print(f"{joke_response.content=}")


# or async
# Method-2
async def joke_chain_async():
    try:
        response = await joke_chain.ainvoke({"topic": "parrots"})
        print(response.content, end="", flush=True)
    finally:
        # 在 finally 块中确保无论如何都尝试关闭连接
        await joke_chain.async_client.aclose()


# Method-3
prompt = [
    SystemMessage(content='Act like either a cat or a parrot.'),
    HumanMessage(content='Hello!')
]


# Supports astream
async def astream_anthropic():
    async for msg in anthropic.astream(prompt):
        print(msg.content, end="", flush=True)


# Method-4
prompt2 = ChatPromptTemplate.from_messages(
    [("system", "Tell me a long story about {topic}")]
)

# Can define custom chains
chain = prompt2 | RunnableMap({
    "openai": openai,
    # "anthropic": anthropic,
})

for response in chain.batch([{"topic": "parrots"}, {"topic": "cats"}]):
    if "openai" in response:
        print(response["openai"].content, end="", flush=True)
    if "anthropic" in response:
        print(response, end="", flush=True)

if __name__ == "__main__":
    asyncio.run(joke_chain_async())
    asyncio.run(astream_anthropic())

8. Playground

您可以在/my_runnable/playground/找到可运行的页面。这提供了一个简单的用户界面,用于配置和调用您的可运行代码,并具有流式输出和中间步骤。

例如,使用浏览器打开 http://localhost:8000/openai/playground

9. 聊天可运行页面

LangServe还支持一个聊天重点的可运行页面,可选择并在/my_runnable/playground/下使用。与一般可运行页面不同,仅支持某些类型的可运行代码-可运行代码的输入模式必须是一个dict,其中包含:

  • 一个键,该键的值必须是一个聊天消息列表。
  • 两个键,一个键的值是消息列表,另一个代表最近的消息。

我们建议您使用第一种格式。

可运行代码还必须返回AIMessage或字符串。

要启用它,必须在添加路由时设置playground_type="chat"。

以下是一个示例:

# Declare a chain
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful, professional assistant named Cob."),
        MessagesPlaceholder(variable_name="messages"),
    ]
)

chain = prompt | ChatAnthropic(model="claude-2")


class InputChat(BaseModel):
    """Input for the chat endpoint."""

    messages: List[Union[HumanMessage, AIMessage, SystemMessage]] = Field(
        ...,
        description="The chat messages representing the current conversation.",
    )


add_routes(
    app,
    chain.with_types(input_type=InputChat),
    enable_feedback_endpoint=True,
    enable_public_trace_link_endpoint=True,
    playground_type="chat",
)

完结!

refer: https://www.langchain.com/langserve

refer: https://python.langchain.com/docs/langserve/

相关推荐
七哥的AI日常3 分钟前
个人随想-gpt-o1大模型中推理链的一个落地实现
人工智能
liangbm38 分钟前
MATLAB系列02:MATLAB基础
开发语言·数据结构·笔记·matlab·教程·工程基础·高级绘图
深蓝海拓2 小时前
迭代器和生成器的学习笔记
笔记·python·学习
createcrystal2 小时前
《算法笔记》例题解析 第3章入门模拟--3图形输出(9题)2021-03-03
c++·笔记·算法
卡戎-caryon2 小时前
【Linux】09.Linux 下的调试器——gdb/cgdb
linux·运维·服务器·开发语言·笔记
985小水博一枚呀3 小时前
【深度学习|可视化】如何以图形化的方式展示神经网络的结构、训练过程、模型的中间状态或模型决策的结果??
人工智能·python·深度学习·神经网络·机器学习·计算机视觉·cnn
LluckyYH4 小时前
代码随想录Day 46|动态规划完结,leetcode题目:647. 回文子串、516.最长回文子序列
数据结构·人工智能·算法·leetcode·动态规划
代码敲不对.5 小时前
江科大笔记—软件安装
笔记·stm32·单片机·嵌入式硬件
古猫先生5 小时前
YMTC Xtacking 4.0(Gen5)技术深度分析
服务器·人工智能·科技·云计算
一水鉴天5 小时前
智能工厂的软件设计 “程序program”表达式,即 接口模型的代理模式表达式
开发语言·人工智能·中间件·代理模式