昨天我們進行PromptTemplate的解說,以及兩人對話劇本產生器的應用示範,我們今天會進行LnagServe的使用,並且嘗試把兩人對話劇本產生器部屬至LangServe。
首先安裝LangServe
pip install "langserve[all]"
接著安裝FastAPI
pip install fastapi
具體使用方式
首先建立Chain之前的程式碼皆保留
import os
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
# 1. Create model
os.environ["OPENAI_API_KEY"] = "你的OpenAI key"
model = ChatOpenAI(model="gpt-4o")
# 2. Create prompt template
system_template = "創建一個對話場景包含 {character1} 和 {character2}."
prompt_template = ChatPromptTemplate.from_messages(
[("system", system_template), ("user", "{dialogue_start}")]
)
# 3. Create parser
parser = StrOutputParser()
# 4. Create chain
chain = prompt_template | model | parser
我們多import這幾項
from langserve import add_routes
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
接著定義一個FastAPI的app,並且利用LangServe的add_routes,將FastAPI連接chain,以及為這個任務流程定義一個路徑
# 5. App definition
app = FastAPI(
title="LangChain Server",
version="1.0",
description="A simple API server using LangChain's Runnable interfaces",
)
# 6. Adding chain route
add_routes(
app,
chain,
path="/chain",
)
最後去執行這個應用程式
先安裝
pip install uvicorn
再加入
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)
此時訪問http://localhost:8000/chain/playground/
可以看到一個完整的介面
其實我們可以直接使用Redirect的方式,訪問http://localhost:8000 即可看見這個畫面
@app.get("/")
async def read_root():
return RedirectResponse(url="/chain/playground")
最後完整程式碼
import os
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langserve import add_routes
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
# 1. Create model
os.environ["OPENAI_API_KEY"] = "你的OpenAI key"
model = ChatOpenAI(model="gpt-4o")
# 2. Create prompt template
system_template = "創建一個對話場景包含 {character1} 和 {character2}."
prompt_template = ChatPromptTemplate.from_messages(
[("system", system_template), ("user", "{dialogue_start}")]
)
# 3. Create parser
parser = StrOutputParser()
# 4. Create chain
chain = prompt_template | model | parser
# 5. App definition
app = FastAPI(
title="LangChain Server",
version="1.0",
description="A simple API server using LangChain's Runnable interfaces",
)
# 6. Adding chain route
add_routes(
app,
chain,
path="/chain",
)
@app.get("/")
async def read_root():
return RedirectResponse(url="/chain/playground")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)