
node.js + express + docker + mysql + jwt 實現用戶管理restful api
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格式提交給服務端。
使用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詳細的說明,請參考:
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的地址為:http://127.0.0.1:5001/trans
??梢允褂枚喾N方法驗證API。
下圖使用ApiFox
來驗證接口。
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很有趣
node.js + express + docker + mysql + jwt 實現用戶管理restful api
nodejs + mongodb 編寫 restful 風格博客 api
表格插件wpDataTables-將 WordPress 表與 Google Sheets API 連接
手把手教你用Python和Flask創建REST API
使用 Django 和 Django REST 框架構建 RESTful API:實現 CRUD 操作
ASP.NET Web API快速入門介紹
2024年在線市場平臺的11大最佳支付解決方案
完整指南:如何在應用程序中集成和使用ChatGPT API
選擇AI API的指南:ChatGPT、Gemini或Claude,哪一個最適合你?