pip install flasgger
pip install jsonschema

定義翻譯方法

下面的方法需要兩個參數(shù),其中:language是翻譯目標(biāo)語言,text是需要翻譯的文本。

# 翻譯方法
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

定義請求的json數(shù)據(jù)格式

當(dāng)前比較流行的做法是客戶端的請求以json格式提交給服務(wù)端。  

使用jsonschema可以輕松的對客戶端的輸入?yún)?shù)進(jìn)行校驗。

# 定義請求數(shù)據(jù)json的格式。l:language;t:text
schema={
"type": "object",
'required': ['l','t'],
'properties': {
'l': {'type': 'string',"minLength": 2,"maxLength": 100},
't': {'type': 'string',"minLength": 2,"maxLength": 1000}
}
}

關(guān)于jsonschema的詳細(xì)內(nèi)容,可參見:https://python-jsonschema.readthedocs.io/en/stable/

定義接口和路由

使用@app.route可以指定接口路由,接口方法內(nèi)部的注釋可以被flasgger渲染生成playground。

#翻譯API
@app.route("/trans", methods=['POST'])
def trans_api():
# 以下注釋將會被flasgger使用。
"""
翻譯文本。
---
tags:
- 翻譯
description:
將文本翻譯為目標(biāo)語言。
consumes:
- application/json
produces:
- application/json
parameters:
- name: query
in: body
required: true
description: json格式。例如:{"l":"簡體中文","t":"good morning"}
responses:
code==ok:
description: 成功。msg的值為返回的內(nèi)容。
code==err:
description: 失敗。例如:{"code":"err","msg":"抱歉,我不知道。"} 。
"""

try:
j = request.get_json()
validate(instance=j, schema=schema)
r = translate(j["l"].strip(),j["t"].strip())
return jsonify({"code":"ok","msg":r})
except Exception as e:
return jsonify({"code":"err","msg":str(e)})

關(guān)于flasgger詳細(xì)的說明,請參考:

啟動API

if __name__ == '__main__':
#r = translate("簡體中文","good morning")
#print(r)

# 設(shè)置API 文檔。API文檔訪問地址:http://127.0.0.1:5001/apidocs/
swagger = Swagger(app=app)

app.run(port=5001)

出現(xiàn)下圖所示,即表示API啟動成功。

驗證API

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

1. 使用第三方工具

下圖使用ApiFox來驗證接口。

2. 使用flasgger生成的API

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

下載源代碼

– [gitee](https://gitee.com/liupras/langchain-llama3-Chroma-RAG-demo)

– [github](https://github.com/liupras/langchain-llama3-Chroma-RAG-demo)

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

上一篇:

FastAPI 快速開發(fā) Web API 項目: 通過 SQLAlchemy 進(jìn)行數(shù)據(jù)操作

下一篇:

使用FastAPI和langchain做本地大模型的API
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊

多API并行試用

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

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

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

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

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

10個渠道
一鍵對比試用API 限時免費