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/

相关推荐
Juchecar7 分钟前
母语,塑造和构成了我们的思维过程本身
人工智能
苏打水com13 分钟前
0基础学前端:100天拿offer实战课(第3天)—— CSS基础美化:给网页“精装修”的5大核心技巧
人工智能·python·tensorflow
NON-JUDGMENTAL19 分钟前
CyberSecEval 2
人工智能
智驱力人工智能24 分钟前
智能安全管理 基于视觉分析的玩手机检测系统 手机行为AI模型训练 边缘计算手机行为监测设备
人工智能·安全·目标检测·计算机视觉·智能手机·视觉检测·边缘计算
芯盾时代26 分钟前
CIPS系统迎来重大升级
大数据·人工智能·跨境支付·芯盾时代
ManageEngineITSM27 分钟前
重构可见性:IT资产管理的下一次觉醒
大数据·人工智能·重构·自动化·itsm·工单系统
摘星观月40 分钟前
【深度学习5】多层感知机
人工智能·深度学习
欧阳码农42 分钟前
AI提效这么多,为什么不试试自己开发N个产品呢?
前端·人工智能·后端
Blossom.1181 小时前
把AI“贴”进路灯柱:1KB决策树让老旧路灯自己报「灯头松动」
java·人工智能·python·深度学习·算法·决策树·机器学习
IT_陈寒1 小时前
SpringBoot 3.x 中被低估的10个隐藏特性,让你的开发效率提升50%
前端·人工智能·后端