1- import React , { useState } from 'react' ;
1+ import React , { useState , useEffect , useRef } from 'react' ;
22import {
33 ChatList ,
44 ChatSender ,
55 ChatMessage ,
66 type TdChatSenderParams ,
77 type ChatRequestParams ,
88} from '@tdesign-react/chat' ;
9- import { useChat } from '../index' ;
9+ import { useChat } from '@tdesign-react/chat' ;
10+ import { MessagePlugin } from 'tdesign-react' ;
11+ import { AGUIAdapter } from '@tdesign-react/chat' ;
1012
1113/**
1214 * AG-UI 协议基础示例
@@ -15,20 +17,11 @@ import { useChat } from '../index';
1517 * - 开启 AG-UI 协议支持(protocol: 'agui')
1618 * - 理解 AG-UI 协议的自动解析机制
1719 * - 处理文本消息事件(TEXT_MESSAGE_*)
18- *
19- * AG-UI 协议说明:
20- * AG-UI(Agent-User Interface)是专为 AI Agent 与前端应用交互设计的轻量级协议,
21- * 专注于实时交互、状态流式传输和人机协作。
22- *
23- * 组件会自动解析以下标准事件:
24- * - TEXT_MESSAGE_START/CHUNK/COMPLETE: 文本消息
25- * - THINKING_START/CHUNK/COMPLETE: 思考过程
26- * - TOOL_CALL_START/CHUNK/COMPLETE: 工具调用
27- * - STATE_START/CHUNK/COMPLETE: 状态更新
28- * 等等...
20+ * - 初始化加载历史消息方法 AGUIAdapter.convertHistoryMessages
2921 */
3022export default function AguiBasicExample ( ) {
3123 const [ inputValue , setInputValue ] = useState ( 'AG-UI协议的作用是什么' ) ;
24+ const listRef = useRef < any > ( null ) ;
3225
3326 const { chatEngine, messages, status } = useChat ( {
3427 defaultMessages : [ ] ,
@@ -39,10 +32,6 @@ export default function AguiBasicExample() {
3932 stream : true ,
4033 // 自定义请求参数
4134 onRequest : ( params : ChatRequestParams ) => ( {
42- headers : {
43- 'Content-Type' : 'application/json' ,
44- 'X-Requested-With' : 'XMLHttpRequest' ,
45- } ,
4635 body : JSON . stringify ( {
4736 uid : 'agui-demo' ,
4837 prompt : params . prompt ,
@@ -61,6 +50,26 @@ export default function AguiBasicExample() {
6150 } ,
6251 } ) ;
6352
53+ // 初始化加载历史消息
54+ useEffect ( ( ) => {
55+ const loadHistoryMessages = async ( ) => {
56+ try {
57+ const response = await fetch ( `https://1257786608-9i9j1kpa67.ap-guangzhou.tencentscf.com/api/conversation/history?type=simple` ) ;
58+ const result = await response . json ( ) ;
59+ if ( result . success && result . data ) {
60+ const messages = AGUIAdapter . convertHistoryMessages ( result . data ) ;
61+ chatEngine . setMessages ( messages ) ;
62+ listRef . current ?. scrollList ( { to : 'bottom' } ) ;
63+ }
64+ } catch ( error ) {
65+ console . error ( '加载历史消息出错:' , error ) ;
66+ MessagePlugin . error ( '加载历史消息出错' ) ;
67+ }
68+ } ;
69+
70+ loadHistoryMessages ( ) ;
71+ } , [ ] ) ;
72+
6473 const handleSend = async ( e : CustomEvent < TdChatSenderParams > ) => {
6574 const { value } = e . detail ;
6675 await chatEngine . sendUserMessage ( { prompt : value } ) ;
@@ -69,7 +78,7 @@ export default function AguiBasicExample() {
6978
7079 return (
7180 < div style = { { height : '500px' , display : 'flex' , flexDirection : 'column' } } >
72- < ChatList style = { { flex : 1 } } >
81+ < ChatList ref = { listRef } >
7382 { messages . map ( ( message ) => (
7483 < ChatMessage
7584 key = { message . id }
0 commit comments