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/

相关推荐
Best_Me07几秒前
理解AUROC,AP,F1-scroe,PRO
人工智能·机器学习
IT_陈寒3 分钟前
React 性能优化:5个实战技巧让首屏加载提升50%,开发者亲测有效!
前端·人工智能·后端
久未8 分钟前
Pytorch autoload机制自动加载树外扩展(Autoload Device Extension)
人工智能·pytorch·python
Apifox.10 分钟前
如何在 Apifox 中通过 AI 一键生成几十个测试用例?
人工智能·程序人生·ai·测试用例·ai编程
Learn Beyond Limits27 分钟前
TensorFlow Implementation of Content-Based Filtering|基于内容过滤的TensorFlow实现
人工智能·python·深度学习·机器学习·ai·tensorflow·吴恩达
是Yu欸32 分钟前
【AI视频】从单模型,到AI Agent工作流
人工智能·ai·ai作画·aigc·音视频·实时音视频
im_AMBER35 分钟前
CSS 01【基础语法学习】
前端·css·笔记·学习
摇滚侠36 分钟前
Spring Boot 3零基础教程,深度理解 Spring Boot 自动配置原理,笔记11
spring boot·笔记·后端
AI人工智能+42 分钟前
发票识别技术:结合OCR与AI技术,实现纸质票据高效数字化,推动企业智能化转型
人工智能·nlp·ocr·发票识别
用户5191495848451 小时前
Aniyomi扩展开发指南与Google Drive集成方案
人工智能·aigc