LangChainで作ったChainをLangServeでAPI化する手順
LangChainで作ったChainをLangServeでAPI化する手順をまとめておきます。
Chainが出来ていれば、add_routeで追加するだけです。
LangServe
https://python.langchain.com/docs/langserve
Chainを用意する
まずは、LangChainのChainを用意します。
チャットで会話するだけの簡単なChainです。
conversation_sample.py
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.prompts.prompt import PromptTemplate
llm = ChatOpenAI(model_name="gpt-3.5-turbo")
conversation = ConversationChain(llm=llm)
rtn = conversation.run("日本で使える通貨は?")
print(rtn)
実行結果は、次のようになります。
$ export OPENAI_API_KEY=xxxxxxxx
$ python conversation_sample.py
日本では日本円が使われています。
LangServeでAPI化する
LangServeを使ってAPI化します。
server.py
from fastapi import FastAPI
import uvicorn
from langserve import add_routes
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.prompts.prompt import PromptTemplate
app = FastAPI()
llm = ChatOpenAI(model_name="gpt-3.5-turbo")
conversation = ConversationChain(llm=llm)
add_routes(
app,
conversation,
path="/conversation"
)
if __name__ == "__main__":
uvicorn.run(app, host="localhost", port=8000)
サーバプロセスを起動します。
$ export OPENAI_API_KEY=xxxxxxxx
$ python server.py
curlを使ってAPIを呼び出します。
$ curl -X POST -H "Content-Type: application/json;charset=utf-8" \
-d '{"input":{"input": "日本で使える通貨は?"}}' \
http://localhost:8000/conversation/invoke
{"output":{"response":"日本では日本円が使われています。"},"callback_events":[],"metadata":"run_id":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}}
APIの仕様はhttp://localhost:8000/docs
にアクセスするとswaggerで確認できます。
あとは、Frontendアプリケーションからaxiosなどで呼び出せばOKです。
以上。