from langchain_core.output_parsers import StrOutputParser
from langchain_ollama.llms import OllamaLLM

# 翻譯方法
def translate(language,text):
# 1. 創(chuàng)建提示詞模板
system_template = "Translate the following into {language}:"
prompt_template = ChatPromptTemplate.from_messages([
('system', system_template),
('user', '{text}')
])

# 2. 創(chuàng)建本地大模型
model = OllamaLLM(model="llama3.1")

# 3. 創(chuàng)建解析器
parser = StrOutputParser()

# 4. 創(chuàng)建鏈
chain = prompt_template | model | parser

#5. 調(diào)用鏈
result = chain.invoke({"language": language,"text":text})

return result

定義接口輸入和返回數(shù)據(jù)格式

從這里就可以看到代碼比Flask簡潔得多,這才是代碼應(yīng)有的樣子。

# 導(dǎo)入FastAPI和Pydantic
from fastapi import FastAPI
from pydantic import BaseModel, Field

# 定義一個Pydantic模型來校驗(yàn)輸入的JSON數(shù)據(jù)
class query_model(BaseModel):
lang: str = Field(min_length=2, max_length=20, description="語言名稱" )
text: str = Field(min_length=2, max_length=500, description="待翻譯的文本" )

from enum import Enum
# 操作結(jié)果枚舉
class code_enum(str,Enum):
OK = 'ok'
ERR = 'error'

# API返回的消息體
class response_model(BaseModel):
code: code_enum = Field(description="操作結(jié)果" )
desc: str = Field(description="具體內(nèi)容" )

定義接口和路由

使用@app可以指定接口路由、返回的消息體格式,接口方法內(nèi)部的注釋可以被渲染生成playground。

# 創(chuàng)建一個FastAPI實(shí)例
app = FastAPI()

# 創(chuàng)建一個處理POST請求的端點(diǎn)
@app.post("/trans/", response_model=response_model)
async def translate_api(query: query_model):
"""
翻譯文本。

參數(shù):
- Query: 翻譯請求內(nèi)容。

返回:
- Query: 測試
"""

try:
r = translate(query.lang.strip(),query.text.strip())
return response_model(code=code_enum.OK,desc=r)
except Exception as e:
return response_model(code=code_enum.ERR,desc=str(e))

啟動API

import uvicorn

if __name__ == '__main__':
# 交互式API文檔地址:
# http://127.0.0.1:5001/docs/
# http://127.0.0.1:5001/redoc/

uvicorn.run(app, host="0.0.0.0", port=5001)

驗(yàn)證API

顯然,上述API的地址為:http://127.0.0.1:5001/trans。可以使用多種方法驗(yàn)證API。

1. 使用第三方工具

下圖使用ApiFox來驗(yàn)證接口。

2. 使用flasgger生成的API

使用瀏覽器打開地址:http://127.0.0.1:5001/docs/,依圖示對接口進(jìn)行測試。

文章轉(zhuǎn)自微信公眾號@AI很有趣

上一篇:

用Flask做langchain服務(wù)的API接口

下一篇:

用FastAPI實(shí)現(xiàn)簡單的微服務(wù)API網(wǎng)關(guān)
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊

多API并行試用

數(shù)據(jù)驅(qū)動選型,提升決策效率

查看全部API→
??

熱門場景實(shí)測,選對API

#AI文本生成大模型API

對比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個渠道
一鍵對比試用API 限時免費(fèi)

#AI深度推理大模型API

對比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費(fèi)