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/

相关推荐
لا معنى له2 小时前
目标检测的内涵、发展和经典模型--学习笔记
人工智能·笔记·深度学习·学习·目标检测·机器学习
AKAMAI3 小时前
Akamai Cloud客户案例 | CloudMinister借助Akamai实现多云转型
人工智能·云计算
石像鬼₧魂石4 小时前
内网渗透靶场实操清单(基于 Vulhub+Metasploitable 2)
linux·windows·学习·ubuntu
flying robot5 小时前
centos7系统配置
笔记
小a杰.5 小时前
Flutter 与 AI 深度集成指南:从基础实现到高级应用
人工智能·flutter
colorknight5 小时前
数据编织-异构数据存储的自动化治理
数据仓库·人工智能·数据治理·数据湖·数据科学·数据编织·自动化治理
Lun3866buzha5 小时前
篮球场景目标检测与定位_YOLO11-RFPN实现详解
人工智能·目标检测·计算机视觉
janefir5 小时前
LangChain框架下DirectoryLoader使用报错zipfile.BadZipFile
人工智能·langchain
醇氧6 小时前
org.jetbrains.annotations的@Nullable 学习
java·开发语言·学习·intellij-idea
齐齐大魔王6 小时前
COCO 数据集
人工智能·机器学习