以下のエントリでLangServeを動かしたので、
次はAWS Lambdaに対応したLangServeアプリケーションの作成を考えたいと思います。

LangChainで作ったChainをLangServeでAPI化する手順
https://takemikami.com/2023/11/18/LangChainChainLangServerAPI.html

AWS Lambdaのひな形アプリケーションの作成

AWS SAM CLIでAWS Lambdaアプリケーションのひな形を用意します。

sam init --no-interactive --runtime python3.9 --name langserve-demo --dependency-manager pip --app-template hello-world

# AWS SAM CLIについは、以下を参照
# AWS SAM CLI の使用 | docs.aws.amazon.com
# https://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/using-sam-cli.html

ひな形のアプリケーションをビルド・起動します。

cd langserve-demo
sam build --use-container --debug
sam local start-api --debug

curlを使って処理を呼び出します。

$ curl http://localhost:3000/hello
{"message": "hello world"}

以上で、AWS Lambdaのひな形アプリケーションが用意できました。

LangServeのAPIをAWS Lambdaに載せる

作成したひな形にLangServeのアプリケーションを載せていきます。

# LangServeの実体はFastAPIなので、次のサイトの手順でAWS Lambda化できます。
# AWS SAM、FastAPI、Mangum を使って API 開発をやってみる | aws.amazon.com
# https://aws.amazon.com/jp/builders-flash/202304/api-development-sam-fastapi-mangum/

ひな形には、いろいろ(テストコードなど)含まれますが、
今回、手を加えるのは、次のファイルになります。

  • langserve-demo
    • hello_world
      • app.py
      • requirements.txt
    • template.yaml

app.py … FastAPIのappをMangumでラップする

from fastapi import FastAPI
from langserve import add_routes
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.prompts.prompt import PromptTemplate
from mangum import Mangum

app = FastAPI()
llm = ChatOpenAI(model_name="gpt-3.5-turbo")
conversation = ConversationChain(llm=llm)
add_routes(
    app,
    conversation,
    path="/conversation"
)

lambda_handler = Mangum(app)

requirements.txt … langserve関連のパッケージを追加する

requests
fastapi==0.98.0
mangum==0.17.0
sse-starlette==1.6.5
openai==0.27.10
langchain==0.0.334
langserve==0.0.26

template.yaml … Timeoutを伸ばす、環境変数にOpenAIのキーを入れる、Eventのパスを変更する

※途中省略※
Globals:
  Function:
    Timeout: 180
    MemorySize: 128

※途中省略※
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
        - x86_64
      Environment:
        Variables:
          OPENAI_API_KEY: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /conversation/invoke
            Method: post

※途中省略※

横着していろいろとhello_worldのままですが、以上のように修正します。

変更したら、アプリケーションをビルド・起動します。

sam build --use-container --debug
sam local start-api --debug

curlを使って次のように呼び出すと、LangServe上の処理が実行できます。

$ curl -X POST -H "Content-Type: application/json;charset=utf-8" \
    -d '{"input":{"input": "日本で使える通貨は?"}}' \
    http://localhost:3000/conversation/invoke
{"output":{"response":"日本で使われている通貨は日本円です。"},"callback_events":[],"metadata":{"run_id":"d09b923d-9506-459b-b059-598f235a312f"}}

以上。