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 分钟前
基于学习的人工智能(7)机器学习基本框架
人工智能·学习
Ccjf酷儿6 分钟前
操作系统 蒋炎岩 3.硬件视角的操作系统
笔记
千里念行客24030 分钟前
昂瑞微正式启动科创板IPO发行
人工智能·科技·信息与通信·射频工程
习习.y34 分钟前
python笔记梳理以及一些题目整理
开发语言·笔记·python
撸码猿41 分钟前
《Python AI入门》第10章 拥抱AIGC——OpenAI API调用与Prompt工程实战
人工智能·python·aigc
Z***G4791 小时前
网络爬虫学习:借助DeepSeek完善爬虫软件,实现模拟鼠标右键点击,将链接另存为本地文件
爬虫·学习·计算机外设
在逃热干面1 小时前
(笔记)自定义 systemd 服务
笔记
双翌视觉1 小时前
双翌全自动影像测量仪:以微米精度打造智能化制造
人工智能·机器学习·制造
编程小白_正在努力中2 小时前
神经网络深度解析:从神经元到深度学习的进化之路
人工智能·深度学习·神经网络·机器学习
无风听海2 小时前
神经网络之经验风险最小化
人工智能·深度学习·神经网络