鍵.png)
node.js + express + docker + mysql + jwt 實現(xiàn)用戶管理restful api
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
當(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ì)的說明,請參考:
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的地址為:http://127.0.0.1:5001/trans
。可以使用多種方法驗證API。
下圖使用ApiFox
來驗證接口。
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很有趣
node.js + express + docker + mysql + jwt 實現(xiàn)用戶管理restful api
nodejs + mongodb 編寫 restful 風(fēng)格博客 api
表格插件wpDataTables-將 WordPress 表與 Google Sheets API 連接
手把手教你用Python和Flask創(chuàng)建REST API
使用 Django 和 Django REST 框架構(gòu)建 RESTful API:實現(xiàn) CRUD 操作
ASP.NET Web API快速入門介紹
2024年在線市場平臺的11大最佳支付解決方案
完整指南:如何在應(yīng)用程序中集成和使用ChatGPT API
選擇AI API的指南:ChatGPT、Gemini或Claude,哪一個最適合你?