无脑利用API实现文心一言AI对话功能?(附代码)

前言:在当今数字化的时代,人工智能(AI)技术正在不断演进,为开发者提供了丰富的工具和资源。其中,API(应用程序接口)成为构建强大AI应用的关键组成部分之一。本文将介绍如何利用API来打造一个AI对话网站,使用户能够与智能系统进行交互。

以下内容不作太多解释,不懂就无脑套用就行,这里的api接口以文心一言示例,先在LuckyCola注册账号然后在个人中心申请appKey
在这里插入图片描述
在这里插入图片描述

1.请求方式

请求方式: POST

https://luckycola.com.cn/ai/openwxyy

建议使用https协议,当https协议无法使用时再尝试使用http协议

2.请求参数

序号 参数 是否必须 说明
1 ques 提交问题
2 appKey 唯一验证AppKey
3 uid 唯一标识
4 isLongChat 是否支持上下文(值为1或者0)

3.请求参数示例

{
    
    
   "ques": "hello",
   "appKey": "*****************",
   "uid": "***************",
	 // 是否支持上下文 值1表示支持,0表示不支持
   "isLongChat": 0
}

3.接口 返回示例

{
    
    
	// 	成功状态码
	"code": 0,
	// 	成功提示
	"msg": "AI接口返回成功",
	"data": {
    
    
		// 	AI回答结果
		"result": "您好,如果您需要帮助或有任何问题,请随时告诉我,我将竭诚为您服务。",
		"countMsg": "无穷",
		// 当前是否是上下文对话模式,1表示是上下文模式,0为非上下文模式
		"longChat": 0
	}
}

建立前端页面,创建一个用户友好的前端页面,可以使用HTML、CSS和JavaScript等技术来实现交互式的用户界面。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI对话网站</title>
  <style>
    /* 在这里添加你的样式 */
  </style>
</head>
<body>
  <div id="chat-container">
    <div id="chat-display"></div>
    <input type="text" id="user-input" placeholder="请输入你的问题...">
    <button onclick="sendUserMessage()">发送</button>
  </div>
  <script>
    // 在这里添加用户交互的JavaScript代码
  </script>
</body>
</html>

然后我这里简单写了一段,完成简单对话页面UI,替换自己的uid和appkey即可,供参考

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
      
      
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            overflow: hidden;
        }

        #chat-container {
      
      
            width: 90%; 
            max-width: 400px; 
            border: 1px solid #ccc;
            border-radius: 10px;
            overflow: hidden;
            height: 100%; 
            display: flex;
            flex-direction: column;
        }

        #chat-messages {
      
      
            flex: 1; /* 让消息容器占据剩余空间 */
            padding: 10px;
            overflow-y: auto;
            background-color: #fff;
        }

        .message {
      
      
            clear: both;
            padding: 8px;
            margin-bottom: 8px;
            border-radius: 5px;
            max-width: 70%;
            word-wrap: break-word;
        }

        .message.sent {
      
      
            float: right;
            background-color: #4caf50;
            color: #fff;
        }

        .message.received {
      
      
            float: left;
            background-color: #e0e0e0;
        }

        #chat-input {
      
      
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px;
            background-color: #fff;
            border-top: 1px solid #ccc;
        }

        #chat-input input {
      
      
            flex: 1;
            padding: 8px;
            margin-right: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        #chat-input button {
      
      
            padding: 8px;
            border: none;
            border-radius: 5px;
            background-color: #4caf50;
            color: #fff;
            cursor: pointer;
        }

        #chat-input button:disabled {
      
      
            background-color: #ccc;
            cursor: not-allowed;
        }
    </style>
</head>
<body>

<div id="chat-container">
    <div id="chat-messages">
        <div class="message received">这里是NDIR博客,内容是如何利用API搭建文心一言AI,你有任何问题吗?</div>
    </div>
    <div id="chat-input">
        <input type="text" id="user-input" placeholder="Type your message...">
        <button onclick="sendMessage()" id="sendButton">Send</button>
    </div>
</div>

<script>
    async function sendMessage() {
      
      
        var inputElement = document.querySelector('#user-input');
        var messageText = inputElement.value.trim();
        var sendButton = document.getElementById('sendButton');

        if (messageText !== "") {
      
      
            var messagesContainer = document.querySelector('#chat-messages');
            
            // Display user's message
            var userMessage = document.createElement('div');
            userMessage.className = 'message sent';
            userMessage.textContent = messageText;
            messagesContainer.appendChild(userMessage);

            // Disable send button until AI response
            sendButton.disabled = true;

            // Call AI API
            try {
      
      
                var aiResponse = await getAiResponse(messageText);
                
                // Display AI's response with formatted code blocks
                var aiMessage = document.createElement('div');
                aiMessage.className = 'message received';
                aiMessage.innerHTML = formatCodeBlocks(aiResponse.data.result);
                messagesContainer.appendChild(aiMessage);

                // Scroll to the bottom
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            } catch (error) {
      
      
                console.error("Error fetching AI response:", error);
            }

            // Clear input and enable send button
            inputElement.value = '';
            sendButton.disabled = false;
        }
    }

    async function getAiResponse(userInput) {
      
      
        var apiUrl = 'https://luckycola.com.cn/ai/openwxyy';

        var requestBody = {
      
      
            ques: userInput,
            //替换你的标识
            appKey: "*********************",
            uid: "************************",
            isLongChat: 0
        };

        var response = await fetch(apiUrl, {
      
      
            method: 'POST',
            headers: {
      
      
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(requestBody),
        });

        if (response.ok) {
      
      
            return response.json();
        } else {
      
      
            throw new Error('Failed to fetch AI response');
        }
    }

    function formatCodeBlocks(text) {
      
      
        // Match code blocks enclosed in triple backticks (```code ```)
        return text.replace(/```([\s\S]*?)```/g, '<pre>$1</pre>');
    }
</script>

</body>
</html>
运行效果

在这里插入图片描述

下面是用低代码设计的界面
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_73589720/article/details/135016157