訊飛星火大模型最新4.0Ultra版本api呼叫教程python程式碼(超詳細教程,1分鐘學會)

定州刺猬發表於2024-06-27

1.首先進入訊飛星火大模型官網

2.點選左下角“api接入”,點選“線上除錯”,隨後註冊賬號,領取免費的token

實名認證後就可以直接領取

3.進入後找到最新的spark4.0Ultra

4.記錄右上伺服器APPID APISecret APIKey的值,將值新增到下面的程式碼中

# coding: utf-8
import _thread as thread
import os
import time
import base64

import base64
import datetime
import hashlib
import hmac
import json
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time

import websocket
import openpyxl
from concurrent.futures import ThreadPoolExecutor, as_completed
import os


class Ws_Param(object):
    # 初始化
    def __init__(self, APPID, APIKey, APISecret, gpt_url):
        self.APPID = APPID
        self.APIKey = APIKey
        self.APISecret = APISecret
        self.host = urlparse(gpt_url).netloc
        self.path = urlparse(gpt_url).path
        self.gpt_url = gpt_url

    # 生成url
    def create_url(self):
        # 生成RFC1123格式的時間戳
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        # 拼接字串
        signature_origin = "host: " + self.host + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + self.path + " HTTP/1.1"

        # 進行hmac-sha256進行加密
        signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()

        signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')

        authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'

        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')

        # 將請求的鑑權引數組合為字典
        v = {
            "authorization": authorization,
            "date": date,
            "host": self.host
        }
        # 拼接鑑權引數,生成url
        url = self.gpt_url + '?' + urlencode(v)
        # 此處列印出建立連線時候的url,參考本demo的時候可取消上方列印的註釋,比對相同引數時生成的url與自己程式碼生成的url是否一致
        return url


# 收到websocket錯誤的處理
def on_error(ws, error):
    print("### error:", error)


# 收到websocket關閉的處理
def on_close(ws):
    print("### closed ###")


# 收到websocket連線建立的處理
def on_open(ws):
    thread.start_new_thread(run, (ws,))


def run(ws, *args):
    data = json.dumps(gen_params(appid=ws.appid, query=ws.query, domain=ws.domain))
    ws.send(data)


# 收到websocket訊息的處理
def on_message(ws, message):
    # print(message)
    data = json.loads(message)
    code = data['header']['code']
    if code != 0:
        print(f'請求錯誤: {code}, {data}')
        ws.close()
    else:
        choices = data["payload"]["choices"]
        status = choices["status"]
        content = choices["text"][0]["content"]
        print(content,end='')
        if status == 2:
            print("#### 關閉會話")
            ws.close()


def gen_params(appid, query, domain):
    """
    透過appid和使用者的提問來生成請引數
    """

    data = {
        "header": {
            "app_id": appid,
            "uid": "1234",           
            # "patch_id": []    #接入微調模型,對應服務釋出後的resourceid          
        },
        "parameter": {
            "chat": {
                "domain": domain,
                "temperature": 0.5,
                "max_tokens": 4096,
                "auditing": "default",
            }
        },
        "payload": {
            "message": {
                "text": [{"role": "user", "content": query}]
            }
        }
    }
    return data


def main(appid, api_secret, api_key, gpt_url, domain, query):
    wsParam = Ws_Param(appid, api_key, api_secret, gpt_url)
    websocket.enableTrace(False)
    wsUrl = wsParam.create_url()

    ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)
    ws.appid = appid
    ws.query = query
    ws.domain = domain
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})


if __name__ == "__main__":
    main(
        appid="",
        api_secret="",
        api_key="",
        #appid、api_secret、api_key三個服務認證資訊請前往開放平臺控制檯檢視(https://console.xfyun.cn/services/bm35)
        gpt_url="wss://spark-api.xf-yun.com/v4.0/chat",
        # Spark_url = "ws://spark-api.xf-yun.com/v3.1/chat"  # v3.0環境的地址
        # Spark_url = "ws://spark-api.xf-yun.com/v2.1/chat"  # v2.0環境的地址
        # Spark_url = "ws://spark-api.xf-yun.com/v1.1/chat"  # v1.5環境的地址
        domain="4.0Ultra",
        # domain = "generalv3"    # v3.0版本
        # domain = "generalv2"    # v2.0版本
        # domain = "general"    # v2.0版本
        query="你和3.5版本有什麼區別"
    )

5.執行程式碼時,可能會報錯,注意把未新增的庫新增好,如果都新增好了還報錯,可以嘗試以下除錯程式碼

pip install --upgrade websocket-client

6.祝大家都能用上順手的大模型~

相關文章