The project is connected to the Xinghuo Cognitive Model! ! !

The project is connected to the spark cognition model demo

Introduction

With the continuous rise of large language models in China, iFLYTEK’s Xinghuo model, Ali’s Tongyi Qianwen, Baidu’s Wenxin Yiyan, etc.

These large models provide me with great convenience

At the same time, the Xinghuo large model provides open api function so that we can connect the large model to our own projects.

This allows the project to generate

Project Introduction

I successfully connected the large model to my webpage through the open api provided by the spark large model

gif is loading! ! !

Project address

zou-hong-run/xinghuo: Xunfei Xinghuo Cognitive Model access web page (github.com)

Demo Video URL

Xunfei Xunhuo Cognitive Model Access Webpage Demo Demonstration (Project Access Large Model Function)_哔哩哔哩_bilibili

Run the project

  • download the item

  • Go to the Xunfei development platform to register an account, so that you can add applications

    • Xunfei Open Platform – AI open platform with voice interaction as the core (xfyun.cn)
  • Add an application to the Xunfei console, so that APPID, APISecret, APIKey, etc. can be obtained

    • Console-Xunfei Open Platform (xfyun.cn)
  • open our project

    • Modify the code in xinghuodemo/main.js, fill in your own APPID, APISecret, APIKey

       let requestObj = {
      APPID: '',
      APISecret: '',
      APIKey: '',
      Uid:"Random username",
      sparkResult: ''
      }
      
  • Then execute the following command

    cd xinghuodemo
    pnpm i
    pnpm run dev
    
  • Then visit the address and start using it

    • http://localhost:5173/

show code

page layout code

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <link rel="icon" type="image/svg + xml" href="/vite.svg" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Xunfei Spark Cognitive Model was successfully connected to the webpage</title>
  <style>
    * {<!-- -->
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    h1{<!-- -->
      text-align: center;
      color: #5165EA;
    }
    html, body{<!-- -->
      width: 100%;
      height: 100%;
      background-color: #F3F8F9;
    }
    body{<!-- -->
      padding: 10%;
    }
    #results{<!-- -->
      width: 100%;
      height: 80%;
      background-color: #E2EEFF;
    }
    #results #result{<!-- -->
      width: 100%;
      height: 100%;
      padding: 10%;
      
      background-color: #E2EEFF;
      white-space: pre-line;
    }
    #sendVal{<!-- -->
      display: flex;
      width: 100%;
      height: 20%;
    }
    #sendVal #question{<!-- -->
      width: 70%;
      height: 100%;
      padding: 5%;
      border: 2px dotted blue;
    }
    #sendVal #btn{<!-- -->
      width: 30%;
      height: 100%;
      background-color: #5D7CFF;
    }
    
    
    
  </style>
</head>

<body>
  <h1>Xunfei Xunhuo Cognitive Big Model successfully connected to the webpage</h1>
  <div id="results">
    <textarea id="result"></textarea>
  </div>
  <div id="sendVal">
    <input id="question" type="text">
    <button id="btn">Send message</button>
  </div>
  <script type="module" src="main.js"></script>
</body>

</html>

Function implementation code main.js

import * as base64 from 'base-64'
import CryptoJs from 'crypto-js'

let questionInput = document. querySelector("#question");
let sendMsgBtn = document. querySelector("#btn");
let result = document. querySelector("#result");

let requestObj = {
    APPID: '',
    APISecret: '',
    APIKey: '',
    Uid:"red run",
    sparkResult: ''
}
// Click the send message button
sendMsgBtn.addEventListener('click', (e) => {
    sendMsg()
})
// After entering the information, click enter to send the information
questionInput. addEventListener('keydown', function (event) {
    if (event.key === 'Enter') { sendMsg(); }
});
// Send a message
const sendMsg = async () => {
    // get request address
    let myUrl = await getWebsocketUrl();
    // Get the content of the input box
    let inputVal = questionInput. value;
    // Every time a question is sent, it is a new websocketqingqiu
    let socket = new WebSocket(myUrl);

    // Listen to the events of each stage of websocket and deal with them accordingly
    socket.addEventListener('open', (event) => {
        console.log('Open connection!!', event);
        // Send a message
        let params = {
            "header": {
                "app_id": requestObj.APPID,
                "uid": "redrun"
            },
            "parameter": {
                "chat": {
                    "domain": "general",
                    "temperature": 0.5,
                    "max_tokens": 1024,
                }
            },
            "payload": {
                "message": {
                    // If you want to get an answer combined with the context, the developer needs to send the historical question and answer information to the server each time, as shown in the following example
                    // Note: the total tokens of all the contents in the text must be controlled within 8192. If the developer has a long dialogue requirement, the historical information needs to be appropriately cut
                    "text": [
                        { "role": "user", "content": "Who are you" }, //# User history questions
                        { "role": "assistant", "content": "I am an AI assistant" }, //# AI's historical answer results
                        // ....... omitted history dialog
                        { "role": "user", "content": inputVal }, //# The latest question, if no context is needed, just upload the latest question
                    ]
                }
            }
        };
        console.log("Send message");
        socket.send(JSON.stringify(params))
    })
    socket.addEventListener('message', (event) => {
        let data = JSON. parse(event. data)
        // console.log('received message!!', data);
        requestObj.sparkResult + = data.payload.choices.text[0].content
        if (data. header. code !== 0) {
            console.log("Error", data.header.code, ":", data.header.message);
            // Error "manually closed connection"
            socket. close()
        }
        if (data. header. code === 0) {
            // the conversation is complete
            if (data.payload.choices.text & amp; & amp; data.header.status === 2) {
                requestObj.sparkResult + = data.payload.choices.text[0].content;
                setTimeout(() => {
                    // "Conversation complete, close connection manually"
                    socket. close()
                }, 1000)
            }
        }
        addMsgToTextarea(requestObj.sparkResult);
    })
    socket.addEventListener('close', (event) => {
        console.log('Connection closed!!', event);
        // After the conversation is completed, the socket will be closed, and the chat record will be wrapped
        requestObj.sparkResult = requestObj.sparkResult + " & amp;#10;"
        addMsgToTextarea(requestObj.sparkResult);
        // clear the input box
        questionInput. value = ''
    })
    socket.addEventListener('error', (event) => {
        console.log('Connection sending error!!', event);
    })
}
// authentication url address
const getWebsocketUrl = () => {
    return new Promise((resovle, reject) => {
        let url = "wss://spark-api.xf-yun.com/v1.1/chat";
        let host = "spark-api.xf-yun.com";
        let apiKeyName = "api_key";
        let date = new Date().toGMTString();
        let algorithm = "hmac-sha256"
        let headers = "host date request-line";
        let signatureOrigin = `host: ${host}\\
date: ${date}\\
GET /v1.1/chat HTTP/1.1`;
        let signatureSha = CryptoJs.HmacSHA256(signatureOrigin, requestObj.APISecret);
        let signature = CryptoJs.enc.Base64.stringify(signatureSha);

        let authorizationOrigin = `${apiKeyName}="${requestObj.APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature} "`;

        let authorization = base64. encode(authorizationOrigin);

        // encode spaces
        url = `${url}?authorization=${authorization} &date=${encodeURI(date)} &host=${host}`;

        resovle(url)
    })
}
/** Add information to textare
    HTML tags are not supported in textarea.
    Out of service
    Tabs are wrapped.
    Escape characters like \r\\
 cannot be used either.

    To wrap the content in the Textarea, you can use & amp; #13; or & amp; #10; to wrap the line.
     & amp;#13; means carriage return; & amp;#10; means line break;
*/
const addMsgToTextarea = (text) => {
    result.innerHTML = text;
}


End

A long time ago, I started to study how to access various large-scale models, but they haven’t released the API yet, and the Xinghuo large-scale model was the first to come out, which is great! !
If you feel good, please support it three times! ! ! bxin

4C720CEC.png