@@ -2,6 +2,8 @@ import { Router } from 'express';
22import { Request , Response } from 'express' ;
33import { config } from '../../config' ;
44import Agent from '@atoma-agents/sui-agent/src/agents/SuiAgent' ;
5+ import ChatHistory from '../../models/ChatHistory' ;
6+
57const suiAgent = new Agent ( config . atomaSdkBearerAuth ) ;
68const queryRouter : Router = Router ( ) ;
79
@@ -13,15 +15,53 @@ queryRouter.get('/health', (req: Request, res: Response) => {
1315// Query endpoint
1416const handleQuery = async ( req : Request , res : Response ) : Promise < void > => {
1517 try {
16- const { query } = req . body ;
18+ const { query, walletAddress } = req . body ;
19+
1720 if ( ! query ) {
1821 res . status ( 400 ) . json ( {
1922 error : 'Missing query in request body'
2023 } ) ;
2124 return ;
2225 }
2326
27+ // Get agent response first
2428 const result = await suiAgent . SuperVisorAgent ( query ) ;
29+
30+ // Only try to save chat history if walletAddress is provided
31+ if ( walletAddress ) {
32+ try {
33+ // Get or create chat history for this wallet
34+ let chatHistory = await ChatHistory . findOne ( { walletAddress } ) ;
35+ if ( ! chatHistory ) {
36+ chatHistory = new ChatHistory ( { walletAddress, messages : [ ] } ) ;
37+ }
38+
39+ // Add user message to history
40+ chatHistory . messages . push ( {
41+ text : query ,
42+ sender : 'user' ,
43+ timestamp : new Date ( )
44+ } ) ;
45+
46+ // Add agent response to history
47+ chatHistory . messages . push ( {
48+ text :
49+ typeof result [ 0 ] . response === 'string'
50+ ? result [ 0 ] . response
51+ : JSON . stringify ( result [ 0 ] . response ) ,
52+ sender : 'llm' ,
53+ isHTML : true ,
54+ timestamp : new Date ( )
55+ } ) ;
56+
57+ // Save chat history
58+ await chatHistory . save ( ) ;
59+ } catch ( chatError ) {
60+ console . warn ( 'Error saving chat history:' , chatError ) ;
61+ // Continue with the response even if chat history fails
62+ }
63+ }
64+
2565 res . status ( 200 ) . json ( result ) ;
2666 } catch ( error ) {
2767 console . error ( 'Error handling query:' , error ) ;
@@ -31,6 +71,20 @@ const handleQuery = async (req: Request, res: Response): Promise<void> => {
3171 }
3272} ;
3373
74+ // Get chat history endpoint
75+ queryRouter . get ( '/history/:walletAddress' , async ( req : Request , res : Response ) => {
76+ try {
77+ const { walletAddress } = req . params ;
78+ const chatHistory = await ChatHistory . findOne ( { walletAddress } ) ;
79+ res . status ( 200 ) . json ( chatHistory ?. messages || [ ] ) ;
80+ } catch ( error ) {
81+ console . error ( 'Error fetching chat history:' , error ) ;
82+ res . status ( 500 ) . json ( {
83+ error : 'Internal server error'
84+ } ) ;
85+ }
86+ } ) ;
87+
3488// Handle unsupported methods
3589const handleUnsupportedMethod = ( req : Request , res : Response ) : void => {
3690 res . status ( 405 ) . json ( {
0 commit comments