当前位置:   article > 正文

讯飞星火3.5API接入指南_讯飞星火 开放 api

讯飞星火 开放 api

概述

讯飞星火大模型拥有跨领域的知识和语言理解能力,完成问答对话和文学创作等任务。持续从海量文本数据和大规模语法知识中学习进化,实现从提出问题、规划问题到解决问题的全流程闭环。

API调用流程

步骤一.资源包申请

登录讯飞星火平台,完成个人认证后,申请免费资源包。

步骤二.获取AppID、API Key、Secret Key。

进入 讯飞开放平台,获取AppID、API Key、Secret Key。

代码调用示例(python)

SparkApi.py

  1. import _thread as thread
  2. import base64
  3. import datetime
  4. import hashlib
  5. import hmac
  6. import json
  7. from urllib.parse import urlparse
  8. import ssl
  9. from datetime import datetime
  10. from time import mktime
  11. from urllib.parse import urlencode
  12. from wsgiref.handlers import format_date_time
  13. import websocket # 使用websocket_client
  14. answer = ""
  15. class Ws_Param(object):
  16. # 初始化
  17. def __init__(self, APPID, APIKey, APISecret, Spark_url):
  18. self.APPID = APPID
  19. self.APIKey = APIKey
  20. self.APISecret = APISecret
  21. self.host = urlparse(Spark_url).netloc
  22. self.path = urlparse(Spark_url).path
  23. self.Spark_url = Spark_url
  24. # 生成url
  25. def create_url(self):
  26. # 生成RFC1123格式的时间戳
  27. now = datetime.now()
  28. date = format_date_time(mktime(now.timetuple()))
  29. # 拼接字符串
  30. signature_origin = "host: " + self.host + "\n"
  31. signature_origin += "date: " + date + "\n"
  32. signature_origin += "GET " + self.path + " HTTP/1.1"
  33. # 进行hmac-sha256进行加密
  34. signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
  35. digestmod=hashlib.sha256).digest()
  36. signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')
  37. authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'
  38. authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
  39. # 将请求的鉴权参数组合为字典
  40. v = {
  41. "authorization": authorization,
  42. "date": date,
  43. "host": self.host
  44. }
  45. # 拼接鉴权参数,生成url
  46. url = self.Spark_url + '?' + urlencode(v)
  47. # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
  48. return url
  49. # 收到websocket错误的处理
  50. def on_error(ws, error):
  51. print("### error:", error)
  52. # 收到websocket关闭的处理
  53. def on_close(ws,one,two):
  54. print(" ")
  55. # 收到websocket连接建立的处理
  56. def on_open(ws):
  57. thread.start_new_thread(run, (ws,))
  58. def run(ws, *args):
  59. data = json.dumps(gen_params(appid=ws.appid, domain= ws.domain,question=ws.question))
  60. ws.send(data)
  61. # 收到websocket消息的处理
  62. def on_message(ws, message):
  63. # print(message)
  64. data = json.loads(message)
  65. code = data['header']['code']
  66. if code != 0:
  67. print(f'请求错误: {code}, {data}')
  68. ws.close()
  69. else:
  70. choices = data["payload"]["choices"]
  71. status = choices["status"]
  72. content = choices["text"][0]["content"]
  73. print(content,end ="")
  74. global answer
  75. answer += content
  76. # print(1)
  77. if status == 2:
  78. ws.close()
  79. def gen_params(appid, domain,question):
  80. """
  81. 通过appid和用户的提问来生成请参数
  82. """
  83. data = {
  84. "header": {
  85. "app_id": appid,
  86. "uid": "1234"
  87. },
  88. "parameter": {
  89. "chat": {
  90. "domain": domain,
  91. "temperature": 0.5,
  92. "max_tokens": 2048
  93. }
  94. },
  95. "payload": {
  96. "message": {
  97. "text": question
  98. }
  99. }
  100. }
  101. return data
  102. def main(appid, api_key, api_secret, Spark_url,domain, question):
  103. # print("星火:")
  104. wsParam = Ws_Param(appid, api_key, api_secret, Spark_url)
  105. websocket.enableTrace(False)
  106. wsUrl = wsParam.create_url()
  107. ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)
  108. ws.appid = appid
  109. ws.question = question
  110. ws.domain = domain
  111. ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

test.py

  1. import SparkApi
  2. #以下密钥信息从控制台获取
  3. appid = "XXXXXXXX" #填写控制台中获取的 APPID 信息
  4. api_secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" #填写控制台中获取的 APISecret 信息
  5. api_key ="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" #填写控制台中获取的 APIKey 信息
  6. #用于配置大模型版本,默认“general/generalv2”
  7. domain = "general" # v1.5版本
  8. # domain = "generalv2" # v2.0版本
  9. #云端环境的服务地址
  10. Spark_url = "ws://spark-api.xf-yun.com/v1.1/chat" # v1.5环境的地址
  11. # Spark_url = "ws://spark-api.xf-yun.com/v2.1/chat" # v2.0环境的地址
  12. text =[]
  13. # length = 0
  14. def getText(role,content):
  15. jsoncon = {}
  16. jsoncon["role"] = role
  17. jsoncon["content"] = content
  18. text.append(jsoncon)
  19. return text
  20. def getlength(text):
  21. length = 0
  22. for content in text:
  23. temp = content["content"]
  24. leng = len(temp)
  25. length += leng
  26. return length
  27. def checklen(text):
  28. while (getlength(text) > 8000):
  29. del text[0]
  30. return text
  31. if __name__ == '__main__':
  32. text.clear
  33. while(1):
  34. Input = input("\n" +"我:")
  35. question = checklen(getText("user", Input))
  36. SparkApi.answer =""
  37. print("星火:",end = "")
  38. SparkApi.main(appid,api_key,api_secret,Spark_url,domain,question)
  39. getText("assistant",SparkApi.answer)
  40. # print(str(text))

接口详细介绍、参数说明、错误码等信息请参考 官方接口文档

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/454903
推荐阅读
相关标签
  

闽ICP备14008679号