rojects/source/server/routes/rojos.ts

86 lines
1.9 KiB
TypeScript

import { Router } from "express";
import { requireAuth } from "../middleware/auth";
import { getAgentStream, updateAgentConversation } from "../rojos/RojosAgent";
import { RJLog } from "../../library-ts/node/log/RJLog";
const router = Router();
router.use( requireAuth );
router.post( "/chat", async ( req, res ) =>
{
const { id, message } = req.body as { id: string; message: string };
// RJLog.log( "Chat", { id, message } );
if ( !id || !message )
{
res.status( 400 ).json( { error: "id and message are required" } );
return;
}
try
{
const agentStream = await getAgentStream( id, message );
res.setHeader( "Content-Type", "text/event-stream" );
res.setHeader( "Cache-Control", "no-cache" );
res.setHeader( "Connection", "keep-alive" );
res.flushHeaders();
const collected: string[] = [];
for await ( const chunk of agentStream )
{
const content = chunk.content;
let text = "";
// RJLog.log( "Chunk", chunk );
if ( typeof content === "string" )
{
text = content;
}
else if ( Array.isArray( content ) )
{
for ( const c of content )
{
if ( typeof c === "string" )
{
text += c;
}
else if ( c && typeof c === "object" && "text" in c )
{
text += ( c as any ).text;
}
}
}
if ( text.length > 0 )
{
collected.push( text );
res.write( JSON.stringify( { type: "CHAT", text } ) + "\n" );
}
else
{
res.write( JSON.stringify( { type: "THINKING" } ) + "\n" );
}
}
updateAgentConversation( id, collected.join( "" ) );
res.write( JSON.stringify( { type: "DONE" } ) + "\n" );
res.end();
}
catch ( err )
{
console.error( err );
if ( !res.headersSent )
{
res.status( 500 ).json( { error: "Failed to get agent response" } );
}
}
} );
export default router;