fastapi小案例:实现星火API调用和中文转英文fastapi+sparkAI+en2zh
本帖最后由 vicmay 于 2024-8-7 11:53 编辑from fastapi import FastAPI
import uvicorn
import requests
app = FastAPI()
# sparkai调用
from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler
from sparkai.core.messages import ChatMessage
#星火认知大模型Spark Max的URL值,其他版本大模型URL值请前往文档(https://www.xfyun.cn/doc/spark/Web.html)查看
SPARKAI_URL = 'wss://spark-api.xf-yun.com/v1.1/chat'
#星火认知大模型调用秘钥信息,请前往讯飞开放平台控制台(https://console.xfyun.cn/services/bm35)查看
SPARKAI_APP_ID = '替换自己的ID'
SPARKAI_API_SECRET = '替换自己的SECRET'
SPARKAI_API_KEY = '替换自己的API_KEY'
#星火认知大模型Spark Max的domain值,其他版本大模型domain值请前往文档(https://www.xfyun.cn/doc/spark/Web.html)查看
SPARKAI_DOMAIN = 'general'
def search_sparkai(keyword):
spark = ChatSparkLLM(
spark_api_url=SPARKAI_URL,
spark_app_id=SPARKAI_APP_ID,
spark_api_key=SPARKAI_API_KEY,
spark_api_secret=SPARKAI_API_SECRET,
spark_llm_domain=SPARKAI_DOMAIN,
streaming=False,
)
messages =
handler = ChunkPrintHandler()
generations = spark.generate(, callbacks=)
data = str(generations)
return data
def get_text(t):
m=t.split("text='")
if len(m) >1:
m=m.split("', message")
else:
return t
return m
@app.get("/sparkai")
def sparkai_answer(keyword:str|None=None):
t=search_sparkai(keyword)
return get_text(t)
def zhongying(keywords):
zh = 'zh'
en = 'en'
for c in keywords:
if ('\u4e00' <= c <= '\u9fa5'):# 判断是否为中文
zh = 'en'
en = 'zh'
try:
url = "https://fy.httpcn.com/bdaify/?s1=%s&t1=%s&q=%s" % (en, zh, keywords)
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
}
fanhui = requests.get(url, headers=headers, timeout=30)
jieguo = fanhui.json()
jie2 = jieguo['result']['trans_result']['dst']
return jie2
except:
return '无数据'
@app.get("/zhongying")
def zhongying_answer(keyword:str|None=None):
return zhongying(keyword)
# 启动uvicorn服务器
# 示例使用
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8099)
#使用前安装fastapi、requests、uvicorn即可一键启动;然后浏览器访问http://127.0.0.1:8099/docs即可调用相应API from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler这个调用有问题 xixicoco 发表于 2024-8-7 11:47
from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler这个调用有问题
具体什么问题呢?麻烦截图反馈 xixicoco 发表于 2024-8-7 11:47
from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler这个调用有问题
哦,忘了,还要安装sparkai库,pip install sparkai 支持,!一直想学 默默学习,给一个大大的赞
页:
[1]