鍵.png)
node.js + express + docker + mysql + jwt 實(shí)現(xiàn)用戶管理restful api
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
從這里就可以看到代碼比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))
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)
顯然,上述API的地址為:http://127.0.0.1:5001/trans
。可以使用多種方法驗(yàn)證API。
下圖使用ApiFox
來驗(yàn)證接口。
flasgger
生成的API使用瀏覽器打開地址:http://127.0.0.1:5001/docs/
,依圖示對接口進(jìn)行測試。
文章轉(zhuǎn)自微信公眾號@AI很有趣
node.js + express + docker + mysql + jwt 實(shí)現(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:實(shí)現(xiàn) CRUD 操作
ASP.NET Web API快速入門介紹
2024年在線市場平臺的11大最佳支付解決方案
完整指南:如何在應(yīng)用程序中集成和使用ChatGPT API
選擇AI API的指南:ChatGPT、Gemini或Claude,哪一個最適合你?