react + 图灵api 实现模拟客服

1.代码

chatbot/index.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
 * 客服
*/
import React, { useState, useRef } from 'react';
import { Button, Toast, InputItem } from 'antd-mobile';
import { RobotUrl, ApiKeys } from 'utils/constants';
import askImg from 'Images/user_center/ask.jpg';
import answerImg from 'Images/user_center/answer.jpg';
import './index.less';
 
interface IProps { }
 
function ChatBot(props: IProps) {
  const [apiKey, setApiKey] = useState<string>(ApiKeys[0]);
  const [message, setMessage] = useState<string>('');
  const [askList, setAskList] = useState<string[]>([]);
  const [answerList, setAnswerList] = useState<string[]>([]);
  const listRef: any = useRef(null);
 
  function sendMessage() {
    if (!message) {
      Toast.info('不能发送空白消息哦');
      return;
    }
 
    setAskList([...askList, message]);
    // 请求图灵接口
    fetch(`${RobotUrl}?key=${apiKey}&info=${message}`, {
      method: 'POST',
      // type: 'cors'
    }).then(function (response: any) {
      return response.json()
    }).then(function (detail: any) {
      setAnswerList([...answerList, detail.text]);
      listRef.current.scrollTop = listRef.current.scrollHeight;
      if (+detail.code !== 100000) setApiKey(ApiKeys[1]);
    }).finally(() => setMessage(''))
  }
 
  return (
    <div className="chatbot_content">
      <div className="message_list" ref={listRef}>
        {askList.map((elem, index) => (
          <div className="container" key={index}>
            <div className="ask_content">
              <p className="message">{elem}</p>
              <img src={askImg} className="avatar" />
            </div>
            <div className="answer_content">
              <img src={answerImg} className="avatar" />
              <p className="message">{answerList[index]}</p>
            </div>
          </div>
        ))}
      </div>
      <div className="send_message">
        <InputItem
          className="send_txt"
          placeholder="请输入"
          value={message}
          onChange={(msg: string) => setMessage(msg)}
        />
        <Button
          type="primary"
          size="small"
          inline
          onClick={sendMessage}
          className="send_btn"
        >发送</Button>
      </div>
    </div>
  );
}
 
export default ChatBot;

2.效果图

posted @   每天都要进步一点点  阅读(480)  评论(1编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
历史上的今天:
2019-04-05 Web Storage与Cookie相比存在的优势:
2018-04-05 vux-uploader 图片上传组件
2017-04-05 proxy [ˈprɒksi] 代理
点击右上角即可分享
微信分享提示