pip install flasgger
pip install jsonschema

定義翻譯方法

下面的方法需要兩個參數,其中:language是翻譯目標語言,text是需要翻譯的文本。

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

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

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

# 4. 創建鏈
chain = prompt_template | model | parser

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

return result

定義請求的json數據格式

當前比較流行的做法是客戶端的請求以json格式提交給服務端。  

使用jsonschema可以輕松的對客戶端的輸入參數進行校驗。

# 定義請求數據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}
}
}

關于jsonschema的詳細內容,可參見:https://python-jsonschema.readthedocs.io/en/stable/

定義接口和路由

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

#翻譯API
@app.route("/trans", methods=['POST'])
def trans_api():
# 以下注釋將會被flasgger使用。
"""
翻譯文本。
---
tags:
- 翻譯
description:
將文本翻譯為目標語言。
consumes:
- application/json
produces:
- application/json
parameters:
- name: query
in: body
required: true
description: json格式。例如:{"l":"簡體中文","t":"good morning"}
responses:
code==ok:
description: 成功。msg的值為返回的內容。
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)})

關于flasgger詳細的說明,請參考:

啟動API

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

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

app.run(port=5001)

出現下圖所示,即表示API啟動成功。

驗證API

顯然,上述API的地址為:http://127.0.0.1:5001/trans??梢允褂枚喾N方法驗證API。

1. 使用第三方工具

下圖使用ApiFox來驗證接口。

2. 使用flasgger生成的API

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

下載源代碼

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

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

文章轉自微信公眾號@AI很有趣

上一篇:

FastAPI 快速開發 Web API 項目: 通過 SQLAlchemy 進行數據操作

下一篇:

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

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

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

#AI深度推理大模型API

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

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