Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

use pretty same upload and stream endpoint of agent chat

Forhad Hosaind7904257308a
diff --git a/packages/app/src/backend/routes/api/page/chat.ts b/packages/app/src/backend/routes/api/page/chat.ts
index 7044f467..48b25f3c 100644
--- a/packages/app/src/backend/routes/api/page/chat.ts
+++ b/packages/app/src/backend/routes/api/page/chat.ts
@@ -2,6 +2,7 @@ import { assetStorage } from '@src/backend/services/storage';
import axios from 'axios';
import { randomUUID } from 'crypto';
import express from 'express';
+import { createProxyMiddleware } from 'http-proxy-middleware';
import config from '../../../config';
import { includeTeamDetails } from '../../../middlewares/auth.mw';
import { authHeaders, includeAxiosAuth, md5Hash, posixPath, smythAPIReq } from '../../../utils';
@@ -59,25 +60,18 @@ const uploadFileMw = assetStorage.createUploadMw({
});
router.post('/stream', async (req, res) => {
- let { message, fileKeys = [] } = req.body;
+ let { message, attachments = [] } = req.body;
const userId = req._user?.id;
const teamId = req._team?.id;
const token = req.user.accessToken;
const agentId = req.headers['x-agent-id'];
const conversationId = req.headers['x-conversation-id'];
const isAgentChat = req.headers['x-ai-agent'] === 'true';
- const filePublicUrls = fileKeys.map((key) => assetStorage.getPublicUrl(key));
-
- if (filePublicUrls.length > 0) {
- message = [message, '###', 'Attachments:', ...filePublicUrls.map((url) => `- ${url}`)].join(
- '\n',
- );
- }
try {
const result = await axios.post(
- getAgentServerURL(agentId as string, isUsingLocalServer) + '/aichat/stream',
- { message },
+ getAgentServerURL(agentId as string, isUsingLocalServer) + '/v1/emb/chat/stream',
+ { message, attachments: req.body.attachments || [] },
{
headers: {
...includeAxiosAuth(token).headers,
@@ -215,28 +209,57 @@ router.get('/messages', async (req, res) => {
}
});
-router.post('/upload', [includeTeamDetails, uploadFileMw.single('file')], async (req, res) => {
- if (!req.file) {
- return res.status(400).json({ message: 'No file uploaded' });
+// Upload endpoint: proxy multipart form-data directly to runtime `/aichat/upload`
+router.post('/upload', [includeTeamDetails], (req: any, res, next) => {
+ const token = req.user?.accessToken;
+ const userId = req._user?.id;
+ const teamId = req._team?.id;
+ const headerAgentId = req.headers['x-agent-id'] as string | undefined;
+ const queryAgentId =
+ (req.query.agentId as string | undefined) || (req.query['agent-id'] as string | undefined);
+
+ // Try to extract agentId from Referer URL if not provided directly
+ let refererAgentId: string | undefined;
+ const referer = req.get('referer') || req.get('referrer');
+ if (!headerAgentId && !queryAgentId && referer) {
+ try {
+ const url = new URL(referer);
+ refererAgentId =
+ (url.searchParams.get('agentId') as string | undefined) ||
+ (url.searchParams.get('aiAgentId') as string | undefined) ||
+ (url.searchParams.get('agent-id') as string | undefined);
+ } catch {}
}
+ const agentId = headerAgentId || queryAgentId || refererAgentId;
- try {
- // @ts-ignore
- const key = req.file.key;
- const publicUrl = assetStorage.getPublicUrl(key);
-
- return res.json({
- success: true,
- file: {
- key: key,
- url: publicUrl,
- name: req.file.originalname,
- type: req.file.mimetype,
- },
- });
- } catch (error) {
- return res.status(500).json({ message: 'Failed to upload file' });
+ if (!agentId) {
+ return res
+ .status(400)
+ .json({ error: 'Missing X-AGENT-ID header or ?agentId query param (or Referer agentId)' });
}
+
+ const target = getAgentServerURL(agentId as string, isUsingLocalServer);
+
+ const proxyMw = createProxyMiddleware({
+ target,
+ changeOrigin: true,
+ pathRewrite: () => '/v1/emb/chat/upload',
+ onProxyReq: (proxyReq) => {
+ if (token) proxyReq.setHeader('Authorization', 'Bearer ' + token);
+ if (userId) proxyReq.setHeader('x-user-id', userId);
+ if (teamId) {
+ proxyReq.setHeader('x-team-id', teamId);
+ proxyReq.setHeader('x-smyth-team-id', teamId);
+ }
+ // Ensure agent id is forwarded for agent resolution by runtime
+ proxyReq.setHeader('X-AGENT-ID', agentId);
+ proxyReq.setHeader('x-agent-id', agentId);
+ // Ensure cookies aren’t forwarded
+ proxyReq.removeHeader('Cookie');
+ },
+ });
+
+ return proxyMw(req, res, next);
});
router.delete('/deleteFile', [includeTeamDetails], async (req, res) => {
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts
index 25463883..dcf38ea9 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts
@@ -112,7 +112,14 @@ export const useChatActions = ({
await chatUtils.generateResponse({
agentId,
query: message,
- fileKeys: attachedFiles?.map((f) => f.metadata.key).filter(Boolean) as string[],
+ attachments: (attachedFiles || [])
+ .map((f) => ({
+ url: f.metadata.publicUrl,
+ name: f.file?.name,
+ type: f.metadata.fileType,
+ size: f.file?.size,
+ }))
+ .filter((a) => !!a.url),
chatId,
signal,
onResponse: (value: string, errorInfo?: { isError?: boolean; errorType?: string }) => {
@@ -272,9 +279,14 @@ export const useChatActions = ({
await chatUtils.generateResponse({
agentId,
query: lastMessage.message,
- fileKeys: lastMessage.attachedFiles
- ?.map((f) => f.metadata.key)
- .filter(Boolean) as string[],
+ attachments: (lastUserMessageRef.current.attachedFiles || [])
+ .map((f) => ({
+ url: f.metadata.publicUrl,
+ name: f.file?.name,
+ type: f.metadata.fileType,
+ size: f.file?.size,
+ }))
+ .filter((a) => !!a.url),
chatId,
signal,
onResponse: (value: string, errorInfo?: { isError?: boolean; errorType?: string }) => {
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts b/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts
index 68e33d90..d850cbba 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts
@@ -32,7 +32,9 @@ const generateUniqueFileId = (file: File): string => {
return `${file.name}-${file.size}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
};
-export const useFileUpload = (): UseFileUploadReturn => {
+export const useFileUpload = (params?: { agentId?: string; chatId?: string }): UseFileUploadReturn => {
+ const agentId = params?.agentId || '';
+ const chatId = params?.chatId;
const [files, setFiles] = useState<FileWithMetadata[]>([]);
const [uploadingFiles, setUploadingFiles] = useState<Set<string>>(new Set());
const [uploadError, setUploadError] = useState<FileUploadError>({ show: false, message: '' });
@@ -110,9 +112,11 @@ export const useFileUpload = (): UseFileUploadReturn => {
// Upload files concurrently
const uploadPromises = filesToUpload.map(async ({ file, id }) => {
try {
- const result = await uploadFile(file);
+ const result = await uploadFile(file, agentId, chatId);
if (result.success) {
+ // Normalize response from runtime (/aichat/upload)
+ const runtimeFile = result.data?.files?.[0];
setFiles((prevFiles) =>
prevFiles.map((f) =>
f.id === id
@@ -120,9 +124,9 @@ export const useFileUpload = (): UseFileUploadReturn => {
...f,
metadata: {
...f.metadata,
- key: result.data.file.key,
- publicUrl: result.data.file.url,
- fileType: result.data.file.type,
+ // Do not set key for runtime uploads (avoid delete attempts)
+ publicUrl: runtimeFile?.url || result.data?.file?.url,
+ fileType: runtimeFile?.mimetype || result.data?.file?.type,
isUploading: false,
},
}
@@ -147,7 +151,7 @@ export const useFileUpload = (): UseFileUploadReturn => {
await Promise.all(uploadPromises);
}
},
- [files.length],
+ [files.length, agentId, chatId],
);
const handleFileChange = useCallback(
diff --git a/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx b/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx
index 7727ef2a..eef3a839 100644
--- a/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx
+++ b/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx
@@ -87,7 +87,10 @@ const AIChat: FC<AIChatProps> = ({
clearError,
isUploadInProgress,
clearFiles,
- } = useFileUpload();
+ } = useFileUpload({
+ agentId: agentId || '',
+ chatId: agentSettingsData?.settings?.lastConversationId,
+ });
const dropzoneRef = useDragAndDrop({ onDrop: handleFileDrop });
diff --git a/packages/app/src/react/features/ai-chat/utils/file.ts b/packages/app/src/react/features/ai-chat/utils/file.ts
index dfdd837c..8004d6a2 100644
--- a/packages/app/src/react/features/ai-chat/utils/file.ts
+++ b/packages/app/src/react/features/ai-chat/utils/file.ts
@@ -114,6 +114,8 @@ export const validateSingleFile = (file: File): string | null => {
*/
export const uploadFile = async (
file: File,
+ agentId: string,
+ chatId?: string,
): Promise<{ success: boolean; data?: any; error?: string }> => {
try {
const formData = new FormData();
@@ -122,6 +124,10 @@ export const uploadFile = async (
const response = await fetch('/api/page/chat/upload', {
method: 'POST',
body: formData,
+ headers: {
+ 'X-AGENT-ID': agentId,
+ ...(chatId ? { 'x-conversation-id': chatId } : {}),
+ },
});
if (!response.ok) {
diff --git a/packages/app/src/react/features/ai-chat/utils/index.ts b/packages/app/src/react/features/ai-chat/utils/index.ts
index cb24418f..28e7c00b 100644
--- a/packages/app/src/react/features/ai-chat/utils/index.ts
+++ b/packages/app/src/react/features/ai-chat/utils/index.ts
@@ -6,7 +6,7 @@ type GenerateResponseInput = {
agentId: string;
chatId: string;
query: string;
- fileKeys?: string[];
+ attachments?: { url: string; name?: string; type?: string; size?: number }[];
signal: AbortSignal;
onResponse: (value: string, errorInfo?: { isError?: boolean; errorType?: string }) => void;
onStart: () => void;
@@ -232,7 +232,10 @@ export const chatUtils = {
'x-conversation-id': input.chatId,
'x-ai-agent': 'true',
},
- body: JSON.stringify({ message: input.query, fileKeys: input.fileKeys }),
+ body: JSON.stringify({
+ message: input.query,
+ attachments: input.attachments,
+ }),
signal: input.signal,
});
diff --git a/packages/runtime/package.json b/packages/runtime/package.json
index 02f1c1f7..1c6c8aa3 100644
--- a/packages/runtime/package.json
+++ b/packages/runtime/package.json
@@ -52,7 +52,7 @@
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.10.1",
- "@smythos/sre": "^1.5.50",
+ "@smythos/sre": "^1.5.64",
"axios": "^1.7.7",
"compression": "^1.8.0",
"cookie-parser": "^1.4.7",
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index fbf55e33..7625ee82 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -35,12 +35,6 @@ const port = config.env.PORT;
registerConnectors();
const sre = SmythRuntime.Instance.init({
- Storage: {
- Connector: 'LocalStorage',
- Settings: {
- folder: `${config.env.DATA_PATH}/tmp`,
- },
- },
Cache: {
Connector: 'RAM',
Settings: {},
diff --git a/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts b/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
index de9457e9..fcafbb9a 100644
--- a/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
+++ b/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
@@ -26,7 +26,8 @@ export default async function agentLoader(req, res, next) {
let agentDomain: any = '';
let isTestDomain = false;
- let { path, version } = extractAgentVerionsAndPath(req.path);
+ const { path, version: extractedVersion } = extractAgentVerionsAndPath(req.path);
+ let version = extractedVersion;
if (!version) version = agentVersion;
if (!agentId) {
const domain = req.hostname;
@@ -75,7 +76,14 @@ export default async function agentLoader(req, res, next) {
agentData = { error: error.message };
}
- if (isAgentChatRequest && (path.startsWith('/stream') || path.startsWith('/chat-stream'))) {
+ // Ensure default components for file parsing are added for all agent chat stream routes
+ if (
+ isAgentChatRequest &&
+ (path.startsWith('/stream') ||
+ path.startsWith('/chat-stream') ||
+ path.includes('/v1/emb/chat/stream') ||
+ req.path.includes('/v1/emb/chat/stream'))
+ ) {
// only add default components and connections for file parsing agent on chat requests
addDefaultComponentsAndConnections(agentData);
}
@@ -121,9 +129,11 @@ export default async function agentLoader(req, res, next) {
function cleanAgentData(agentData) {
if (agentData) {
// remove Note components
+ // eslint-disable-next-line no-param-reassign
agentData.data.components = agentData.data.components.filter(c => c.name != 'Note');
// remove templateInfo
+ // eslint-disable-next-line no-param-reassign
delete agentData.data?.templateInfo;
// TODO : remove UI attributes
diff --git a/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts
index 00d7924d..b726b484 100644
--- a/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts
@@ -13,38 +13,16 @@ import { includeAuth, mwSysAPI } from '@core/services/smythAPIReq';
import agentLoader from '@embodiment/middlewares/agentLoader.mw';
import ChatbotLoader from '@embodiment/middlewares/ChatbotLoader.mw';
-import Chatbot from '@embodiment/services/Chatbot.class';
import { buildConversationId } from '@embodiment/utils/chat.utils';
const console = Logger('[Embodiment] Router: Agent Chat');
-// Import ChatbotResponse type for proper typing
-type ChatbotResponse = {
- content?: string;
- title?: string;
- debug?: string;
- function?: string;
- parameters?: any[];
- function_call?: any;
- isError?: boolean;
- errorType?: string;
-};
-
-// declare the req._chatbot type
-
const router = express.Router();
-const middlewares = [uploadHandler, UserAgentAccessCheck, agentLoader, ChatbotLoader];
+// Note: Intentionally excluding UserAgentAccessCheck to mirror working chatbot routes and avoid SSL certificate issues
+const middlewares = [uploadHandler, agentLoader, ChatbotLoader];
router.use(middlewares);
-const localAgentAuthorizations = {
- // FIXME : this seems like a hardcoded value used by Arslan during implementation, should we remove it ?
- clzi8yw441kcfblqz6zj9bv1h: {
- verifiedKey: 'SomeRandomToken',
- authMethod: 'api-key-bearer',
- },
-};
-
const validations = {
exportConversations: {
body: Joi.object({
@@ -59,90 +37,9 @@ const validations = {
},
};
-router.post('/stream', async (req, res) => {
- let streamStarted = false;
- const isLocalAgent = req.hostname.includes('localagent');
- const agentId = req._agent?.id;
- const agentVersion = req._agent?.version;
- let verifiedKey = null;
-
- if (isLocalAgent) {
- verifiedKey = localAgentAuthorizations?.[agentId]?.verifiedKey;
- } else {
- verifiedKey = req.session.agentAuthorizations?.[agentId]?.verifiedKey;
- }
-
- const abortController = new AbortController();
- try {
- const { message } = req.body;
- if (!req._chatbot) {
- return res.status(404).send({ error: 'Chatbot not found' });
- }
- const chatbot: Chatbot = req._chatbot;
- const userId = req.header('x-user-id') || 'none';
- const teamId = req.header('x-team-id') || 'none';
- const isAgentChatRequest = req.header('x-conversation-id') !== undefined;
- chatbot.conversationID = req.header('x-conversation-id') || req.sessionID;
-
- const headers: any = {};
- if (verifiedKey) {
- headers.Authorization = `Bearer ${verifiedKey}`;
- }
-
- console.log('headers', {
- userId,
- teamId,
- conver: chatbot.conversationID,
- });
-
- const dataPath = config.env.DATA_PATH;
+// Removed legacy /aichat/stream in favor of /v1/emb/chat/stream
- if (!dataPath) {
- return res.status(500).send({ error: 'Data path is not set' });
- }
-
- // set response headers
- res.setHeader('Content-Type', 'text/event-stream');
- res.setHeader('Cache-Control', 'no-cache');
- res.setHeader('Connection', 'keep-alive');
-
- headers['X-AGENT-ID'] = undefined; // because we don't debug with agent chat and this is required to make sre-runtime call the agent via http
- headers['X-AGENT-VERSION'] = agentVersion;
- headers['x-conversation-id'] = chatbot.conversationID;
-
- await chatbot.getChatStreaming({
- message,
- callback: (data: ChatbotResponse) => {
- res.write(JSON.stringify(data));
- streamStarted = true;
- },
- headers,
- abortSignal: abortController.signal,
- isAgentChatRequest,
- });
-
- res.end();
- } catch (error: any) {
- console.error(error);
- if (!streamStarted) {
- res.status(500).send({
- content: error?.message || 'An error occurred. Please try again later.',
- isError: true,
- errorType: 'api_error',
- });
- } else {
- // Stream error message in the same format as normal responses
- res.write(
- JSON.stringify({
- content: "I'm not able to contact the server. Please try again.",
- isError: true,
- errorType: 'connection_error',
- }),
- );
- res.end();
- }
- }
-});
+// New v1 endpoint mirroring chatbot /chat-stream behavior but for Agent Chat
router.post('/new', async (req, res) => {
const { conversation = {} } = req.body;
@@ -184,8 +81,10 @@ router.post('/new', async (req, res) => {
}
});
+// Removed legacy /aichat/upload in favor of unified /v1/emb/chat/upload
+
//* NOTE THAT THIS ROUTE IS PROTECTED BY UserAgentAccessCheck middleware AND IT SHOULD ALWAYS BE PROTECTED
-router.post('/export-conversations', validate(validations.exportConversations), async (req, res) => {
+router.post('/export-conversations', UserAgentAccessCheck, validate(validations.exportConversations), async (req, res) => {
const agentId = req._agent?.id;
if (!agentId) {
return res.status(400).send({ error: 'agentId is required' });
diff --git a/packages/runtime/src/modules/embodiment/modules/chat/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/chat/routes/router.ts
new file mode 100644
index 00000000..cc2c3075
--- /dev/null
+++ b/packages/runtime/src/modules/embodiment/modules/chat/routes/router.ts
@@ -0,0 +1,155 @@
+import express from 'express';
+
+import { AccessCandidate, Agent, BinaryInput, Logger } from '@smythos/sre';
+
+import Chatbot from '@embodiment/services/Chatbot.class';
+
+import { uploadHandler } from '@core/middlewares/uploadHandler.mw';
+
+import agentLoader from '@embodiment/middlewares/agentLoader.mw';
+import ChatbotLoader from '@embodiment/middlewares/ChatbotLoader.mw';
+
+const console = Logger('[Embodiment] Router: Chat (Unified Upload)');
+
+const router = express.Router();
+
+// Reuse the same TTL that was used in chatbot upload
+const MAX_TTL_CHAT_FILE_UPLOAD = 60 * 60 * 24 * 1; // 1 day
+
+// Middlewares: keep this accessible for both chatbot and agent chat
+// Note: Intentionally excluding UserAgentAccessCheck to mirror /chatbot/upload accessibility
+router.use([agentLoader, ChatbotLoader]);
+
+// Exportable handler so other modules (e.g., chatbot) can reuse unified logic
+export async function uploadFile(req: any, res: any) {
+ try {
+ if (!req.files || req.files.length === 0) {
+ return res.status(400).json({ error: 'No files uploaded' });
+ }
+
+ const agent: Agent = req._agent;
+ const uploadedFiles: any[] = [];
+
+ for (const file of req.files) {
+ try {
+ const candidate = AccessCandidate.agent(agent.id);
+ const binaryInput = BinaryInput.from(file.buffer, null, file.mimetype, candidate);
+ await binaryInput.ready();
+ // getJsonData implicitly uploads the file to SmythFS
+ const fileData = await binaryInput.getJsonData(candidate, MAX_TTL_CHAT_FILE_UPLOAD);
+
+ uploadedFiles.push({
+ size: file.size,
+ url: fileData.url,
+ mimetype: file.mimetype,
+ originalName: file.originalname,
+ });
+ } catch (error) {
+ console.error('Error uploading file:', file.originalname, error);
+ }
+ }
+
+ res.json({ success: true, files: uploadedFiles });
+ } catch (error) {
+ console.error('Error handling file upload:', error);
+ res.status(500).json({ success: false, error: 'Failed to process file upload' });
+ }
+}
+
+// Unified upload endpoint for both Chatbot and Agent Chat
+router.post('/upload', uploadHandler, uploadFile);
+
+type ChatbotResponse = {
+ content?: string;
+ title?: string;
+ debug?: string;
+ function?: string;
+ parameters?: any[];
+ function_call?: any;
+ isError?: boolean;
+ errorType?: string;
+};
+
+// POST /v1/emb/chat/stream
+router.post('/chat/stream', async (req: any, res) => {
+ let streamStarted = false;
+ const agentId = req._agent?.id;
+ const agentVersion = req._agent?.version;
+ const isDebugSession = req._agent?.debugSessionEnabled;
+
+ const verifiedKey = req.session.agentAuthorizations?.[agentId]?.verifiedKey || null;
+
+ const abortController = new AbortController();
+
+ try {
+ let { message } = req.body;
+ const { attachments = [] } = req.body;
+ if (Array.isArray(attachments) && attachments.length > 0) {
+ message = [message, '###', 'Attachments:', ...attachments.map((a: any) => `- ${a?.url}`)].join('\n');
+ }
+
+ if (!req._chatbot) {
+ return res.status(404).send({ error: 'Chatbot not found' });
+ }
+ const chatbot: Chatbot = req._chatbot;
+ chatbot.conversationID = (req.header('x-conversation-id') as string) || req.sessionID;
+ const monitorId = req.header('x-monitor-id');
+ const hasAttachments = Array.isArray(attachments) && attachments.length > 0;
+
+ const headers: any = isDebugSession
+ ? {
+ 'X-DEBUG': true,
+ 'X-AGENT-ID': agentId,
+ 'X-AGENT-VERSION': agentVersion,
+ 'X-AGENT-REMOTE-CALL': hasAttachments,
+ 'x-conversation-id': chatbot.conversationID,
+ }
+ : {
+ 'X-AGENT-ID': agentId,
+ 'X-AGENT-VERSION': agentVersion,
+ 'X-AGENT-REMOTE-CALL': hasAttachments,
+ 'x-conversation-id': chatbot.conversationID,
+ };
+ if (monitorId) headers['X-MONITOR-ID'] = monitorId;
+ if (verifiedKey) headers.Authorization = `Bearer ${verifiedKey}`;
+
+ req.on('close', () => abortController.abort());
+
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Connection', 'keep-alive');
+
+ await chatbot.getChatStreaming({
+ message,
+ callback: (data: ChatbotResponse) => {
+ res.write(JSON.stringify(data));
+ streamStarted = true;
+ },
+ headers,
+ abortSignal: abortController.signal,
+ isAgentChatRequest: hasAttachments,
+ });
+
+ res.end();
+ } catch (error: any) {
+ console.error(error);
+ if (!streamStarted) {
+ res.status(500).send({
+ content: error?.message || 'An error occurred. Please try again later.',
+ isError: true,
+ errorType: 'api_error',
+ });
+ } else {
+ res.write(
+ JSON.stringify({
+ content: "I'm not able to contact the server. Please try again.",
+ isError: true,
+ errorType: 'connection_error',
+ }),
+ );
+ res.end();
+ }
+ }
+});
+
+export { router as chatRouter };
diff --git a/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts
index e8945e09..327b59f8 100644
--- a/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts
@@ -1,11 +1,12 @@
import axios from 'axios';
import express from 'express';
-import { AccessCandidate, Agent, BinaryInput, Logger } from '@smythos/sre';
+import { Agent, Logger } from '@smythos/sre';
import config from '@core/config';
import { readAgentOAuthConfig } from '@core/helpers/agent.helper';
import { uploadHandler } from '@core/middlewares/uploadHandler.mw';
+import { uploadFile } from '@embodiment/modules/chat/routes/router';
import { EMBODIMENT_TYPES } from '@embodiment/constants';
import { getChatGPTManifest } from '@embodiment/helpers/chatgpt.helper';
@@ -112,6 +113,7 @@ router.get('/chat-configs', async (req: any, res) => {
res.send(chatbot.pluginManifest);
});
+// * NOTE: This endpoint will be deprecated and replaced by `/v1/emb/chat/stream`.
router.post('/chat-stream', async (req, res) => {
let streamStarted = false;
const isLocalAgent = req.hostname.includes('localagent');
@@ -439,45 +441,8 @@ router.get('/callback', async (req: any, res) => {
sendCloseTabResponse(res);
});
-router.post('/upload', uploadHandler, async (req: any, res) => {
- try {
- if (!req.files || req.files.length === 0) {
- return res.status(400).json({ error: 'No files uploaded' });
- }
-
- const agent = req._agent;
- const uploadedFiles = [];
-
- for (const file of req.files) {
- try {
- const candidate = AccessCandidate.agent(agent.id);
- const binaryInput = BinaryInput.from(file.buffer, null, file.mimetype, candidate);
- await binaryInput.ready();
- // getJsonData implicitly uploads the file to SmythFS
- const fileData = await binaryInput.getJsonData(candidate, MAX_TTL_CHATBOT_FILE_UPLOAD);
-
- uploadedFiles.push({
- size: file.size,
- url: fileData.url,
- mimetype: file.mimetype,
- originalName: file.originalname,
- });
- } catch (error) {
- console.error('Error uploading file:', file.originalname, error);
- }
- }
-
- res.json({
- success: true,
- files: uploadedFiles,
- });
- } catch (error) {
- console.error('Error handling file upload:', error);
- res.status(500).json({
- success: false,
- error: 'Failed to process file upload',
- });
- }
-});
+// Delegate chatbot upload to the unified chat/upload handler
+// * NOTE: This endpoint will be deprecated and replaced by `/v1/emb/chat/upload`.
+router.post('/upload', uploadHandler, uploadFile);
export { router as chatBotRouter };
diff --git a/packages/runtime/src/modules/embodiment/routes/index.ts b/packages/runtime/src/modules/embodiment/routes/index.ts
index 99a39c01..76dced84 100644
--- a/packages/runtime/src/modules/embodiment/routes/index.ts
+++ b/packages/runtime/src/modules/embodiment/routes/index.ts
@@ -6,6 +6,7 @@ import config from '@core/config';
import { agentChatRouter } from '@embodiment/modules/agentChat/routes/router';
import { alexaRouter } from '@embodiment/modules/alexa/routes/router';
import { apiRouter } from '@embodiment/modules/API/routes/router';
+import { chatRouter } from '@embodiment/modules/chat/routes/router';
import { chatBotRouter } from '@embodiment/modules/chatbot/routes/router';
import { chatGPTRouter } from '@embodiment/modules/chatGPT/routes/router';
import { formPreviewRouter } from '@embodiment/modules/formPreview/routes/router';
@@ -56,6 +57,10 @@ const defaultRoutes: Route[] = [
rootPath: ['/chatbot', 'chatBot', '/emb/chatbot'],
route: chatBotRouter,
},
+ {
+ rootPath: ['/v1/emb/chat'],
+ route: chatRouter,
+ },
{
rootPath: ['/aichat', '/emb/aichat'],
route: agentChatRouter,