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.

set default model to gpt-5-mini

Forhad Hosaind0ebb505c81e
diff --git a/packages/runtime/src/core/constants.ts b/packages/runtime/src/core/constants.ts
index 5c2fccf3..56b6c0a8 100644
--- a/packages/runtime/src/core/constants.ts
+++ b/packages/runtime/src/core/constants.ts
@@ -1,5 +1,5 @@
export const DEFAULT_AGENT_MODEL_SETTINGS_KEY = "chatGptModel"; // the key in the agent settings object that contains the model name
-export const DEFAULT_AGENT_MODEL = "gpt-5-mini"; // the default model to use if no model is specified in the agent settings
+export const DEFAULT_MODEL = "gpt-5-mini"; // the default model to use if no model is specified in the agent settings
export const PROD_VERSION_VALUES = ["prod", "production", "stable"];
export const TEST_VERSION_VALUES = [
diff --git a/packages/runtime/src/core/default-file-parsing-agent.ts b/packages/runtime/src/core/default-file-parsing-agent.ts
index 85475fda..b3ec2f07 100644
--- a/packages/runtime/src/core/default-file-parsing-agent.ts
+++ b/packages/runtime/src/core/default-file-parsing-agent.ts
@@ -1,125 +1,167 @@
+import { DEFAULT_MODEL } from "@core/constants";
+
export const defaultFileParsingAgent = {
components: [
- {
- id: 'CM6JHAW8TNQB',
- name: 'APIEndpoint',
- outputs: [
- { name: 'headers', color: '#3C89F9', index: 0, default: true },
- { name: 'body', color: '#3C89F9', index: 1, default: true },
- { name: 'query', color: '#3C89F9', index: 2, default: true },
- { name: 'message', color: '#3C89F9', expression: 'body.message', index: 3, default: false },
- { name: 'attachments', color: '#3C89F9', expression: 'body.attachments', index: 4, default: false },
- ],
- inputs: [
- {
- name: 'message',
- type: 'Any',
- friendlyInputType: 'Text',
- coreInputType: 'Any',
- color: '#F35063',
- optional: false,
- description: "User's query.",
- index: 0,
- default: false,
- },
- {
- name: 'attachments',
- type: 'Binary',
- friendlyInputType: 'Text',
- coreInputType: 'Binary',
- color: '#F35063',
- optional: false,
- description: 'Files, images, and attachments to parse and answer questions about.',
- index: 1,
- default: false,
- },
- ],
- data: {
- method: 'POST',
- endpoint: 'process_attachment_fallback',
- description: 'Use this endpoint to process user queries with attachments, if there is no other endpoint to process the attachments.',
- ai_exposed: true,
- summary: '',
- advancedModeEnabled: false,
- },
- top: '72.6576px',
- left: '539.408px',
- width: '',
- height: '',
- displayName: 'APIEndpoint',
- title: 'Agent Skill',
- aiTitle: '',
- description: 'An API Endpoint with input parameters for your AI agent.',
+ {
+ id: "CM6JHAW8TNQB",
+ name: "APIEndpoint",
+ outputs: [
+ { name: "headers", color: "#3C89F9", index: 0, default: true },
+ { name: "body", color: "#3C89F9", index: 1, default: true },
+ { name: "query", color: "#3C89F9", index: 2, default: true },
+ {
+ name: "message",
+ color: "#3C89F9",
+ expression: "body.message",
+ index: 3,
+ default: false,
+ },
+ {
+ name: "attachments",
+ color: "#3C89F9",
+ expression: "body.attachments",
+ index: 4,
+ default: false,
+ },
+ ],
+ inputs: [
+ {
+ name: "message",
+ type: "Any",
+ friendlyInputType: "Text",
+ coreInputType: "Any",
+ color: "#F35063",
+ optional: false,
+ description: "User's query.",
+ index: 0,
+ default: false,
+ },
+ {
+ name: "attachments",
+ type: "Binary",
+ friendlyInputType: "Text",
+ coreInputType: "Binary",
+ color: "#F35063",
+ optional: false,
+ description:
+ "Files, images, and attachments to parse and answer questions about.",
+ index: 1,
+ default: false,
+ },
+ ],
+ data: {
+ method: "POST",
+ endpoint: "process_attachment_fallback",
+ description:
+ "Use this endpoint to process user queries with attachments, if there is no other endpoint to process the attachments.",
+ ai_exposed: true,
+ summary: "",
+ advancedModeEnabled: false,
},
- {
- id: 'CM6JHDY7QJR',
- name: 'APIOutput',
- outputs: [{ name: 'Output', color: '#3C89F9', index: 0, default: true }],
- inputs: [
- {
- name: 'result',
- type: 'Any',
- friendlyInputType: '',
- coreInputType: 'Any',
- color: '#F35063',
- optional: false,
- index: 0,
- default: false,
- },
- ],
- data: { format: 'minimal' },
- top: '131.801px',
- left: '1269.49px',
- width: '',
- height: '',
- displayName: 'APIOutput',
- title: 'APIOutput',
- aiTitle: '',
- description: '',
- },
- {
- id: 'CM6QMI3IGUCK',
- name: 'GenAILLM',
- outputs: [{ name: 'Reply', color: '#3C89F9', index: 0, default: true }],
- inputs: [
- { name: 'Input', type: 'Any', friendlyInputType: '', coreInputType: '', color: '#F35063', optional: false, index: 0, default: false },
- {
- name: 'Attachment',
- type: 'Binary',
- friendlyInputType: '',
- coreInputType: '',
- color: '#F35063',
- optional: true,
- index: 1,
- default: false,
- },
- ],
- data: {
- model: 'legacy/gpt-4o', // Use legacy/gpt-4o to support all plans; tries user's API key, then falls back to ours with limited tokens.
- prompt: "Answer question the user's questions: {{Input}}\nUse the attachments for context if needed.",
- temperature: '1',
- maxTokens: '16384',
- topP: '1',
- topK: '0',
- frequencyPenalty: '0',
- presencePenalty: '0',
- passthrough: false,
- stopSequences: '',
- maxThinkingTokens: '816',
- },
- top: '34.9306px',
- left: '902.845px',
- width: '',
- height: '',
- displayName: 'GenAI LLM',
- title: 'Question Answering System',
- aiTitle: 'Question Answering System',
- description: 'Make a GenAI request to an AI model. Works with many input file types.',
+ top: "72.6576px",
+ left: "539.408px",
+ width: "",
+ height: "",
+ displayName: "APIEndpoint",
+ title: "Agent Skill",
+ aiTitle: "",
+ description: "An API Endpoint with input parameters for your AI agent.",
+ },
+ {
+ id: "CM6JHDY7QJR",
+ name: "APIOutput",
+ outputs: [{ name: "Output", color: "#3C89F9", index: 0, default: true }],
+ inputs: [
+ {
+ name: "result",
+ type: "Any",
+ friendlyInputType: "",
+ coreInputType: "Any",
+ color: "#F35063",
+ optional: false,
+ index: 0,
+ default: false,
+ },
+ ],
+ data: { format: "minimal" },
+ top: "131.801px",
+ left: "1269.49px",
+ width: "",
+ height: "",
+ displayName: "APIOutput",
+ title: "APIOutput",
+ aiTitle: "",
+ description: "",
+ },
+ {
+ id: "CM6QMI3IGUCK",
+ name: "GenAILLM",
+ outputs: [{ name: "Reply", color: "#3C89F9", index: 0, default: true }],
+ inputs: [
+ {
+ name: "Input",
+ type: "Any",
+ friendlyInputType: "",
+ coreInputType: "",
+ color: "#F35063",
+ optional: false,
+ index: 0,
+ default: false,
+ },
+ {
+ name: "Attachment",
+ type: "Binary",
+ friendlyInputType: "",
+ coreInputType: "",
+ color: "#F35063",
+ optional: true,
+ index: 1,
+ default: false,
+ },
+ ],
+ data: {
+ model: DEFAULT_MODEL,
+ prompt:
+ "Answer question the user's questions: {{Input}}\nUse the attachments for context if needed.",
+ temperature: "1",
+ maxTokens: "16384",
+ topP: "1",
+ topK: "0",
+ frequencyPenalty: "0",
+ presencePenalty: "0",
+ passthrough: false,
+ stopSequences: "",
+ maxThinkingTokens: "816",
},
+ top: "34.9306px",
+ left: "902.845px",
+ width: "",
+ height: "",
+ displayName: "GenAI LLM",
+ title: "Question Answering System",
+ aiTitle: "Question Answering System",
+ description:
+ "Make a GenAI request to an AI model. Works with many input file types.",
+ },
],
connections: [
- { sourceId: 'CM6JHAW8TNQB', sourceIndex: 3, targetId: 'CM6QMI3IGUCK', targetIndex: 0 },
- { sourceId: 'CM6JHAW8TNQB', sourceIndex: 4, targetId: 'CM6QMI3IGUCK', targetIndex: 1 },
- { sourceId: 'CM6QMI3IGUCK', sourceIndex: 0, targetId: 'CM6JHDY7QJR', targetIndex: 0 },
+ {
+ sourceId: "CM6JHAW8TNQB",
+ sourceIndex: 3,
+ targetId: "CM6QMI3IGUCK",
+ targetIndex: 0,
+ },
+ {
+ sourceId: "CM6JHAW8TNQB",
+ sourceIndex: 4,
+ targetId: "CM6QMI3IGUCK",
+ targetIndex: 1,
+ },
+ {
+ sourceId: "CM6QMI3IGUCK",
+ sourceIndex: 0,
+ targetId: "CM6JHDY7QJR",
+ targetIndex: 0,
+ },
],
};
diff --git a/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts
index 20c12a53..10ff1886 100644
--- a/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts
@@ -2,8 +2,8 @@ import { Agent } from "@smythos/sre";
import express from "express";
import {
- DEFAULT_AGENT_MODEL,
DEFAULT_AGENT_MODEL_SETTINGS_KEY,
+ DEFAULT_MODEL,
} from "@core/constants";
import agentLoader from "@embodiment/middlewares/agentLoader.mw";
@@ -27,7 +27,7 @@ router.post("/", agentLoader, async (req: any, res) => {
const alexRequest = parseAlexaRequest(req.body);
const model =
agent.agentSettings?.get(DEFAULT_AGENT_MODEL_SETTINGS_KEY) ||
- DEFAULT_AGENT_MODEL;
+ DEFAULT_MODEL;
const response = await handleAlexaRequest(
agent,
diff --git a/packages/runtime/src/modules/embodiment/modules/chatbot/services/ChatDataManager.class.ts b/packages/runtime/src/modules/embodiment/modules/chatbot/services/ChatDataManager.class.ts
deleted file mode 100644
index cf8628f3..00000000
--- a/packages/runtime/src/modules/embodiment/modules/chatbot/services/ChatDataManager.class.ts
+++ /dev/null
@@ -1,288 +0,0 @@
-import {
- IChatMessage,
- IChatStorage,
- IMetadataFile,
-} from "@/modules/embodiment/types/chat.types";
-
-/*
- ChatDataManager takes care of storing the chat data into chunks of 100 messages in a file
- when the file is full, it creates a new file and stores the next 100 messages in that file
- each messages is a json object and each file is a json array of messages.
-*/
-
-type ChunkFile = IChatMessage[];
-
-// all the props that should not be counted in the context window and should not be sent to LLMs
-const nonRequiredMessageProps = ["timestamp"];
-
-export class ChatDataManager {
- teamId: string;
- userId: string;
- agentId: string;
- storage: IChatStorage;
- chunkIndex: number = 0;
- conversationId: string;
- maxChunks: number = 100;
- metaUpdateCallback: (metadata: IMetadataFile) => void = () => {};
- private metaDataFilename = "metadata.json";
-
- constructor({
- storage,
- teamId,
- userId,
- agentId,
- conversationId,
- metaUpdateCallback,
- }: {
- teamId: string;
- userId: string;
- agentId: string;
- storage: IChatStorage;
- conversationId: string;
- metaUpdateCallback?: (metadata: IMetadataFile) => void;
- }) {
- this.storage = storage;
- this.teamId = teamId;
- this.userId = userId;
- this.agentId = agentId;
- this.conversationId = conversationId;
- this.metaUpdateCallback = metaUpdateCallback || this.metaUpdateCallback;
-
- if (!this.teamId || !this.userId || !this.agentId || !this.conversationId) {
- throw new Error(
- "teamId, userId, agentId and conversationId are required"
- );
- }
-
- this.storage.setParams({ teamId, userId, agentId, conversationId });
- }
-
- async initManager() {
- const metaData = await this.getMetaData();
- console.log("initManager", metaData);
-
- if (metaData) {
- this.chunkIndex = metaData.lastChunkId || 0;
- }
- return this; // to allow chaining
- }
-
- getChunkFileName(chunkId?: number): string {
- return `chunk_${chunkId || this.chunkIndex}.json`;
- }
-
- async storeMetaData(metaData: IMetadataFile) {
- await this.storage.write(
- this.metaDataFilename,
- JSON.stringify(metaData),
- {}
- );
- return this.metaUpdateCallback(metaData);
- }
-
- async initConversation(metaData: IMetadataFile) {
- return this.storeMetaData(metaData);
- }
-
- async getMetaData(): Promise<IMetadataFile> {
- const defaultMetaData: IMetadataFile = {
- label: "chat",
- summary: "chat",
- teamId: this.teamId,
- agentId: this.agentId,
- id: this.conversationId,
- chunkSize: this.maxChunks,
- lastChunkId: this.chunkIndex,
- };
-
- if (!(await this.storage.exists(this.metaDataFilename))) {
- return defaultMetaData;
- }
-
- const metaData = await this.storage.read(this.metaDataFilename);
- return metaData ? JSON.parse(metaData) : defaultMetaData;
- }
-
- async getChunkFile(
- chunkIndex: number,
- createIfNeeded?: boolean
- ): Promise<ChunkFile> {
- const chunkFileName = this.getChunkFileName(chunkIndex);
- if (!(await this.storage.exists(chunkFileName))) {
- if (createIfNeeded) {
- this.storage.write(chunkFileName, JSON.stringify([]), {});
- }
- return [];
- }
-
- const chunkFileContents = (await this.storage.read(chunkFileName)) ?? "";
- const chunkFile: ChunkFile = JSON.parse(chunkFileContents);
- return chunkFile;
- }
-
- async getLatestChunkFile(createIfNeeded?: boolean): Promise<ChunkFile> {
- return this.getChunkFile(this.chunkIndex, createIfNeeded);
- }
-
- async getNextChunkFile(current: number): Promise<ChunkFile> {
- const index = current + 1;
- return this.getChunkFile(index);
- }
-
- async getPrevChunkFile(current: number): Promise<ChunkFile> {
- const index = Math.max(current - 1, 0);
- return this.getChunkFile(index);
- }
-
- // It returns at least min messages but not more than max.
- async getLatestMessages(
- min: number = 20,
- max: number = 100
- ): Promise<IChatMessage[]> {
- const metaData = await this.getMetaData();
- const currentChunkIndex = metaData.lastChunkId;
- const messages: IChatMessage[] = [];
- let totalMessages = 0;
- let i = currentChunkIndex;
-
- while (totalMessages < max && i >= 0) {
- const chunk = await this.getChunkFile(i);
- if (chunk.length === 0) {
- break; // Stop reading chunks if we encounter an empty chunk = non-existent chunk file
- }
- const remainingMessages = max - totalMessages;
- const chunkMessages = chunk.slice(-remainingMessages);
- messages.unshift(...chunkMessages);
- totalMessages += chunkMessages.length;
- i--;
- }
-
- return messages.slice(-min);
- }
-
- // #region TODO
- // Reuse getLatestMessages
- async getPaginatedMessages(
- page: number,
- limit: number
- ): Promise<IChatMessage[]> {
- const metaData = await this.getMetaData();
- const currentChunkIndex = metaData.lastChunkId;
- const messages: IChatMessage[] = [];
- let totalMessages = 0;
- let i = currentChunkIndex;
- const messagesNeeded = page * limit;
-
- while (totalMessages < messagesNeeded && i >= 0) {
- const chunk = await this.getChunkFile(i);
- if (!chunk || chunk.length === 0) {
- break; // Stop reading chunks if we encounter an empty or non-existent chunk file
- }
-
- // Prepend messages from the current chunk
- messages.unshift(...chunk);
-
- // Update total messages read
- totalMessages += chunk.length;
-
- // Decrement the chunk index
- i--;
- }
-
- // Ensure that we have enough messages to paginate properly
- const totalPages = Math.ceil(totalMessages / limit);
- const validPage = Math.min(page, totalPages);
-
- // Calculate start index for slicing messages array based on requested page and limit
- const startIndex = (validPage - 1) * limit;
- const endIndex = startIndex + limit;
-
- // Slice the desired page of messages
- const paginatedMessages = messages
- .reverse() // Reverse the order of messages to get the latest messages first
- .slice(startIndex, endIndex) // Slice the messages array to get the desired page
- .reverse(); // Reverse the order of messages again to get the original order
-
- console.log(
- "returning paginated messages",
- paginatedMessages.length,
- paginatedMessages
- );
- return paginatedMessages;
- }
-
- saveChunkFile(chunks: ChunkFile): Promise<void> {
- const chunkFileName = this.getChunkFileName();
- console.log("saveChunkFile", chunkFileName, chunks);
- return this.storage.write(chunkFileName, JSON.stringify(chunks), {});
- }
-
- async pushMessage(
- message: IChatMessage,
- enforceUnique: boolean = false
- ): Promise<void> {
- console.log("pushing message", message);
- const newMessage = { ...message, timestamp: Date.now() };
-
- let chunkFile = await this.getLatestChunkFile(true);
- const metaData = await this.getMetaData();
-
- // Check if the most recent message matches the role and content of the new message
- if (enforceUnique && chunkFile.length > 0) {
- const mostRecentMessage = chunkFile[chunkFile.length - 1];
- if (
- mostRecentMessage.role === newMessage.role &&
- mostRecentMessage.content === newMessage.content
- ) {
- console.log("Message already exists. Skipping...");
- return; // Return early if the message already exists
- }
- }
-
- if (chunkFile.length >= this.maxChunks) {
- this.chunkIndex++;
-
- if (metaData) {
- metaData.lastChunkId = this.chunkIndex;
- this.storeMetaData(metaData);
- }
-
- chunkFile = []; // to only store current message in the new file
- }
-
- chunkFile.push(newMessage);
- return this.saveChunkFile(chunkFile);
- }
-
- private removeOptionalProps(message: IChatMessage): IChatMessage {
- const newMessage = { ...message };
- nonRequiredMessageProps.forEach((prop) => {
- delete newMessage[prop];
- });
- return newMessage;
- }
-
- async getContextMessages(tokenWindow: number): Promise<IChatMessage[]> {
- const maxContentLength = tokenWindow * 1.5; // characters in the window
- const metaData = await this.getMetaData();
- const currentChunkIndex = metaData.lastChunkId;
- const messages: ChunkFile = [];
- let totalContentLength = 0;
- let i = currentChunkIndex;
-
- while (totalContentLength < maxContentLength && i >= 0) {
- const prevChunk = await this.getChunkFile(i);
- if (prevChunk.length === 0) {
- break; // Stop reading chunks if we encounter an empty chunk = non-existent chunk file
- }
- messages.unshift(
- ...prevChunk.map((msg) => this.removeOptionalProps(msg))
- );
- totalContentLength +=
- (JSON.stringify(prevChunk).length - prevChunk.length * 33) / 4; // approximating the token length
- i--;
- }
-
- return messages;
- }
-}
diff --git a/packages/runtime/src/modules/embodiment/modules/chatbot/services/Chatbot.class.ts b/packages/runtime/src/modules/embodiment/modules/chatbot/services/Chatbot.class.ts
deleted file mode 100644
index c8553dfd..00000000
--- a/packages/runtime/src/modules/embodiment/modules/chatbot/services/Chatbot.class.ts
+++ /dev/null
@@ -1,451 +0,0 @@
-import { Agent, AgentLogger, Conversation } from "@smythos/sre";
-import { Request } from "express";
-
-import config from "@core/config";
-import { delay } from "@core/utils/date-time.utils";
-
-import { EMBODIMENT_TYPES } from "@embodiment/constants";
-import { getOpenAPIJSONForAI } from "@embodiment/helpers/openapi-adapter.helper";
-import { ChatConversationsEnv } from "@embodiment/utils/chat.utils";
-
-import { FsChatbotContextStore } from "./FsChatbotContextStore.class";
-import { ConversationStreamYield } from "./FsChatbotContextStore.class/FsChatbotContextExporter.class";
-
-type Headers = {
- "x-conversation-id": string;
- Authorization?: string;
- "x-forwarded-for"?: string;
-};
-
-type ChatbotResponse = {
- content?: string;
- title?: string;
- debug?: string;
- function?: string;
- parameters?: any[];
- function_call?: any;
- isError?: boolean;
- errorType?: string;
-};
-
-function fnv1aHash(str) {
- let hash = 0x811c9dc5; // FNV offset basis
- for (let i = 0; i < str.length; i++) {
- hash ^= str.charCodeAt(i);
- hash = Math.imul(hash, 0x01000193); // FNV prime
- }
- return (hash >>> 0).toString(36).toUpperCase(); // Convert to Base36
-}
-export default class Chatbot {
- public sessionID;
- public conversationID;
- public agentId;
- public domain;
- public embodimentSettings;
-
- private agent: Agent;
- private systemMessage = "";
- private model = "gpt-4o-mini";
- private modelInfo: any;
- private function_call_order = 0;
- private contextWindow = 1024 * 128;
- private maxOutputTokens = 4096;
- private client_ip = "";
- private toolCallId = "";
- private logId = "";
- private teamId = "";
- private passThroughNotifications = {};
- private isAgentChat = false;
-
- constructor(req: Request | any) {
- this.agentId = req._agent.id; //from agentLoader middleware
- this.sessionID = req.sessionID;
- this.conversationID = req.headers["x-conversation-id"] || req.sessionID;
- this.domain = req._agent.domain; //req.hostname;
- this.agent = req._agent;
- this.client_ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
- this.teamId = req._agent.teamId;
- this.isAgentChat = req.headers["x-ai-agent"] === "true";
- }
- public async init() {
- // wait for agent settings and embodiments to be ready
- await this.agent.agentSettings?.ready();
- await this.agent.agentSettings?.embodiments?.ready();
-
- this.systemMessage =
- this.agent.data.behavior ||
- this.agent.data.description ||
- this.agent.data.shortDescription ||
- "";
-
- this.model =
- this.agent.agentSettings?.get("chatGptModel") ||
- this.agent.agentSettings?.embodiments?.get(
- EMBODIMENT_TYPES.ChatBot,
- "chatGptModel"
- ) ||
- this.model;
-
- // ! DEPRECATED: LLMRegistry and CustomLLMRegistry is not available anymore, if we need to set the maxOutputTokens then we need to find out a different way to do it
- // const isStandardLLM = LLMRegistry.isStandardLLM(this.model);
- // const team = AccessCandidate.team(this.teamId);
- // let llmRegistry = isStandardLLM ? LLMRegistry : await CustomLLMRegistry.getInstance(team);
-
- // if (typeof llmRegistry?.getModelInfo !== 'function') {
- // const error = new Error(`The chatbot model '${this.model}' is not supported.`);
- // error['errKey'] = 'MODEL_NOT_SUPPORTED';
- // throw error;
- // }
-
- // this.modelInfo = await llmRegistry.getModelInfo(this.model);
-
- // if (this.modelInfo.tokens == this.modelInfo.completionTokens) {
- // this.contextWindow = Math.round(this.modelInfo.tokens * 0.5);
- // this.maxOutputTokens = Math.round(this.modelInfo.tokens * 0.5);
- // } else if (this.modelInfo.tokens > this.modelInfo.completionTokens) {
- // this.contextWindow = this.modelInfo.tokens - this.modelInfo.completionTokens;
- // this.maxOutputTokens = this.modelInfo.completionTokens;
- // } else {
- // this.contextWindow = this.modelInfo.tokens;
- // this.maxOutputTokens = this.modelInfo.completionTokens;
- // }
-
- // this.maxOutputTokens = Math.min(this.maxOutputTokens, 8192); //limit the max output tokens to 8192
-
- //tokens limits are now handled by SRE
- this.model = this.modelInfo.modelId;
-
- console.log("modelInfo", this.model, this.modelInfo);
- }
-
- /**
- * We use this function to serialize the chatbot object to save it in session
- * @returns {Object} serialized object
- */
- public serialize() {
- return {
- agentId: this.agentId,
- domain: this.domain,
- function_call_order: this.function_call_order,
- agentVersion: this.agent.version,
- //sessionID: this.sessionID,
- //conversationID: this.conversationID,
- embodimentSettings: this.embodimentSettings,
- systemMessage: this.systemMessage,
- model: this.model,
- modelInfo: this.modelInfo,
- contextWindow: this.contextWindow,
- maxOutputTokens: this.maxOutputTokens,
- };
- }
-
- /**
- * We use this function to deserialize the chatbot object from session
- * @param data {Object} serialized object
- */
- public deserialize(data) {
- this.agentId = data.agentId;
- this.domain = data.domain;
- this.function_call_order = data.function_call_order;
- //this.sessionID = data.sessionID;
- //this.conversationID = data.conversationID;
- this.embodimentSettings = data.embodimentSettings;
- this.systemMessage = data.systemMessage;
- this.model = data.model;
- this.modelInfo = data.modelInfo;
- this.contextWindow = data.contextWindow;
- this.maxOutputTokens = data.maxOutputTokens;
- }
-
- /**
- * Helper method to send error messages as normal content with error flags
- * @param error - The error object or message
- * @param errorType - Type of error for categorization
- * @param callback - Callback function to send response
- */
- private sendErrorMessage(
- error: any,
- errorType: string,
- callback: (response: ChatbotResponse) => void
- ) {
- const errorMessage =
- error?.message ||
- error?.code ||
- error ||
- "An error occurred. Please try again later.";
-
- callback({
- content: errorMessage,
- isError: true,
- errorType: errorType,
- });
- }
-
- private async processChatMessage({
- message,
- headers,
- callback,
- abortSignal,
- contextStore,
- isAgentChatRequest,
- }: {
- message: string;
- headers: Record<string, string>;
- callback: (response: ChatbotResponse) => void;
- abortSignal?: AbortSignal;
- contextStore: FsChatbotContextStore;
- isAgentChatRequest?: boolean;
- }) {
- const conversationID = this.conversationID;
-
- this.function_call_order++;
-
- this.logId = AgentLogger.log(this.agent, null, {
- sourceId: "chat",
- componentId: "CHATBOT",
- domain: this.domain,
- input: message,
- inputTimestamp: new Date().toISOString(),
- sessionID: conversationID,
- });
-
- this.toolCallId = Math.round(Math.random() * Math.pow(10, 6))
- .toString(36)
- .toUpperCase();
-
- try {
- const spec = await getOpenAPIJSONForAI(
- this.domain,
- this.agent.usingTestDomain ? "" : "latest",
- isAgentChatRequest
- );
-
- // Adapt the model based on the user's plan, especially to support certain OpenAI models for legacy users with limited tokens without their own API key.
- const conversation = new Conversation(this.model, spec, {
- maxContextSize: this.contextWindow,
- maxOutputTokens: this.maxOutputTokens,
- agentId: this.agentId,
- store: contextStore,
- });
-
- conversation.on("error", (error) => {
- console.error("Error in conversation:", error);
-
- // Send error as normal content with error flag instead of throwing
- this.sendErrorMessage(error, "conversation_error", callback);
- });
-
- conversation.on("toolInfo", (toolInfo) =>
- this.toolsInfoHandler(toolInfo, callback)
- );
-
- conversation.on("beforeToolCall", (toolInfo, llmResponse) =>
- this.beforeToolCallHandler(toolInfo, llmResponse, callback)
- );
-
- conversation.on("afterToolCall", (toolInfo, toolResponse) =>
- this.afterToolCallHandler(toolInfo, toolResponse, callback)
- );
-
- // TODO: We need to stream the "thinking" content correctly. Currently, when using callback({..., debug: thinking}), it prints each chunk on a separate line, which doesn't preserve the original format. We need to fix this to maintain the original flow of the "thinking" content.
- // conversation.on('thinking', (thinking) => {
- // callback({ title: `[${this.toolCallId}] Thought Process`, debug: thinking });
- // });
-
- // Print the thinking content at once
- conversation.on("thoughtProcess", (thinking) => {
- callback({
- title: `[${this.toolCallId}] Thought Process`,
- debug: thinking,
- });
- });
-
- conversation.on("content", (content) => {
- try {
- if (content?.indexOf("}{") >= 0) {
- // workaround to avoid broken json chunks parsing in the frontend
- // since all the json chunks are streamed in the same response, we use "}{" to separate them
- // if a content is equal to '}{' or contains it, we replace it with '} {' to avoid false new chunk
- content = content.replace(/}{/g, "} {");
- }
- callback({ content });
- } catch (e) {
- // Send content processing error as normal message with error flag
- this.sendErrorMessage(e, "content_processing_error", callback);
- }
- });
-
- const isStickyDebug =
- this.agent.debugSessionEnabled || headers["X-MONITOR-ID"];
- const dbgHeaders = isStickyDebug ? { "x-hash-id": this.client_ip } : {};
- const concurrentToolCalls = this.agent.debugSessionEnabled ? 1 : 4;
- const result = await conversation.streamPrompt(
- message,
- { "x-caller-session-id": conversationID, ...headers, ...dbgHeaders },
- concurrentToolCalls,
- abortSignal
- );
-
- if (this.logId)
- AgentLogger.log(this.agent, this.logId, {
- output: result,
- outputTimestamp: new Date().toISOString(),
- });
- } catch (error: any) {
- if (this.logId) {
- AgentLogger.log(this.agent, this.logId, {
- error: typeof error === "object" ? JSON.stringify(error) : error,
- });
- }
-
- // Send error message as normal system message with error flag
- this.sendErrorMessage(error, "system_error", callback);
- } finally {
- this.logId = "";
- this.toolCallId = "";
- }
- }
-
- private async toolsInfoHandler(
- toolsInfo,
- callback: (response: ChatbotResponse) => void
- ) {
- if (this.agent.usingTestDomain || this.isAgentChat) {
- for (const tool of toolsInfo) {
- const toolHash = tool.id ? fnv1aHash(tool.id) : this.toolCallId;
- const dbgJson = {
- title: `[${toolHash}] Function Call : ${tool.name}`,
- debug: `${tool.name} (${
- tool?.arguments && typeof tool?.arguments === "object"
- ? JSON.stringify(tool?.arguments)
- : tool?.arguments
- })`,
- };
- if (this.agent.debugSessionEnabled) {
- //attach to UI debugger
- dbgJson["function"] = "updateStatus";
- dbgJson["parameters"] = ["Debugger: Attaching To Agent ..."];
- }
-
- callback(dbgJson);
- await delay(50);
- callback({
- function_call: { name: tool.name, arguments: tool.arguments },
- });
- }
- }
- }
-
- private async beforeToolCallHandler(
- { tool, args },
- llmResponse,
- callback: (response: ChatbotResponse) => void
- ) {
- if (this.logId)
- AgentLogger.log(this.agent, this.logId, {
- output: llmResponse,
- outputTimestamp: new Date().toISOString(),
- });
- const toolHash = tool.id ? fnv1aHash(tool.id) : this.toolCallId;
- if (this.agent.usingTestDomain || this.isAgentChat) {
- if (this.agent.debugSessionEnabled) {
- await delay(100);
- const dbgFunction = `${tool.name} (${
- args && typeof args === "object" ? JSON.stringify(args) : args
- })`;
-
- let dbgJson = {
- title: `[${toolHash}] Function Call : ${tool.name}`,
- debug: `Debugging ${dbgFunction.substring(0, 50)} ...`,
- };
- dbgJson["function"] = "callParentFunction";
- dbgJson["parameters"] = ["debugLastAction", [], 200];
- callback(dbgJson);
- }
- }
-
- if (this.agent.debugSessionEnabled) {
- await delay(3000); //give some time to the UI debugger to attach - FIXME : find a better way to do this
- }
- }
-
- private async afterToolCallHandler(
- { tool, args },
- toolResponse,
- callback: (response: ChatbotResponse) => void
- ) {
- const toolHash = tool.id ? fnv1aHash(tool.id) : this.toolCallId;
- if (this.agent.usingTestDomain || this.isAgentChat) {
- //workaround to avoid broken debug message in the frontend
- //replace all "}{" with "} {";
- const _toolResponse = toolResponse.replace(/}\{/g, "}_{");
- const chunkSize = 500;
- for (let i = 0, len = _toolResponse.length; i < len; i += chunkSize) {
- const chunk = _toolResponse.substr(i, chunkSize);
-
- if (!this.passThroughNotifications[this.toolCallId]) {
- callback({
- title: `[${toolHash}] Call Response : ${tool.name}`,
- debug: chunk,
- });
- }
-
- await delay(20);
- }
- }
- }
-
- public async getChatStreaming({
- message,
- callback,
- headers,
- abortSignal,
- isAgentChatRequest,
- }: {
- message: string;
- callback: (response: ChatbotResponse) => void;
- headers: Headers;
- abortSignal?: AbortSignal;
- isAgentChatRequest?: boolean;
- }) {
- const contextStore = new FsChatbotContextStore({
- agentId: this.agentId,
- conversationID: this.conversationID,
- dataPath: config.env.DATA_PATH,
- });
-
- return this.processChatMessage({
- message,
- headers,
- callback,
- abortSignal,
- contextStore,
- isAgentChatRequest,
- });
- }
-
- /* public async getAgentChatStreaming(message: string, callback: Function = () => {}, headers = {}, abortSignal?: AbortSignal) {
- return this.processChatMessage({ message, headers, callback, abortSignal });
- } */
-
- public async *exportAllConversations({
- dateRange,
- env,
- }: {
- dateRange?: string;
- env?: string;
- }): AsyncGenerator<ConversationStreamYield> {
- const contextStore = new FsChatbotContextStore({
- agentId: this.agentId,
- conversationID: this.conversationID,
- dataPath: config.env.DATA_PATH,
- });
- // return contextStore.exporter.streamConversations({ dateRange, env: env as ChatConversationsEnv });
- for await (const stream of contextStore.exporter.streamConversations({
- dateRange,
- env: env as ChatConversationsEnv,
- })) {
- yield stream;
- }
- }
-}
diff --git a/packages/runtime/src/modules/embodiment/modules/chatbot/services/FsChatbotContextStore.class/FsChatbotContextExporter.class.ts b/packages/runtime/src/modules/embodiment/modules/chatbot/services/FsChatbotContextStore.class/FsChatbotContextExporter.class.ts
deleted file mode 100644
index 86a9d340..00000000
--- a/packages/runtime/src/modules/embodiment/modules/chatbot/services/FsChatbotContextStore.class/FsChatbotContextExporter.class.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { fsExists } from "@core/utils/general.utils";
-import * as chatUtils from "@embodiment/utils/chat.utils";
-import * as fs from "fs";
-import path from "path";
-export type ConversationStreamYield = {
- stream: fs.ReadStream;
- convId: string;
-};
-
-export class FsChatbotContextExporter {
- private sessionsPath: string;
- private agentId: string;
-
- constructor({
- sessionsPath,
- agentId,
- }: {
- sessionsPath: string;
- agentId: string;
- }) {
- this.sessionsPath = sessionsPath;
- this.agentId = agentId;
- }
-
- /**
- * Export all conversations as a JSON stream
- * @param param0
- * @returns
- */
- public async *streamConversations({
- dateRange,
- env,
- }: {
- dateRange?: string;
- env?: chatUtils.ChatConversationsEnv;
- }): AsyncGenerator<ConversationStreamYield> {
- // TODO covert to stream-based export. will implement it NOW
- const folderPath = path.join(this.sessionsPath, this.agentId);
- const testConvprefix = chatUtils.CHAT_PREFIXES["test"];
- const prodConvprefix = chatUtils.CHAT_PREFIXES["prod"];
-
- // check if the folder exists
- if (!(await fsExists(folderPath))) return;
-
- const conversations = await fs.promises.readdir(folderPath);
- const filteredConversations = conversations.filter((conversation) => {
- // first, filter out by prefix env
- if (
- env === "test"
- ? !conversation.startsWith(testConvprefix)
- : conversation.startsWith(testConvprefix) ||
- !conversation.startsWith(prodConvprefix)
- )
- return false;
- if (!conversation.endsWith(".json")) return false;
-
- // then, filter out by date range
- if (dateRange && chatUtils.isValidDateRange(dateRange)) {
- const conversationDate = chatUtils
- .parseDateFromConvId(conversation)
- .getTime();
- const { start, end } = chatUtils.parseDateRange(dateRange);
- if (conversationDate < start || conversationDate > end) return false;
- }
-
- return true;
- });
-
- for (const file of filteredConversations) {
- const fullPath = path.join(this.sessionsPath, this.agentId, file);
- yield {
- stream: fs.createReadStream(fullPath, { encoding: "utf8" }),
- convId: file.replace(".json", ""),
- };
- }
- }
-}
diff --git a/packages/runtime/src/modules/embodiment/modules/chatbot/services/FsChatbotContextStore.class/index.ts b/packages/runtime/src/modules/embodiment/modules/chatbot/services/FsChatbotContextStore.class/index.ts
deleted file mode 100644
index 310fb946..00000000
--- a/packages/runtime/src/modules/embodiment/modules/chatbot/services/FsChatbotContextStore.class/index.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import fs from "fs";
-import path from "path";
-
-import type { ILLMContextStore } from "@smythos/sre";
-
-import { fsExists } from "@core/utils/general.utils";
-
-import { EStorageTypes } from "@/modules/embodiment/types/fileStorage.types";
-import { FsChatbotContextExporter } from "./FsChatbotContextExporter.class";
-
-export class FsChatbotContextStore implements ILLMContextStore {
- private agentId: string;
- private conversationID: string;
- private dataFolder: string;
- // TODO: "exporter" should be declared in the ILLMContextStore interface and exporter should also implement a known interface
- public exporter: FsChatbotContextExporter;
- storageType = EStorageTypes.Local;
- private sessionsPath: string;
-
- constructor({
- agentId,
- conversationID,
- dataPath,
- }: {
- agentId: string;
- conversationID: string;
- dataPath?: string;
- }) {
- if (!dataPath) {
- throw new Error("dataPath is required.");
- }
-
- if (!fs.existsSync(dataPath)) {
- throw new Error(`The data folder at ${dataPath} does not exist.`);
- }
-
- this.dataFolder = dataPath;
- this.agentId = agentId;
- this.conversationID = conversationID;
- this.sessionsPath = path.join(dataPath, "chat_sessions");
- this.exporter = new FsChatbotContextExporter({
- sessionsPath: this.sessionsPath,
- agentId,
- });
- }
-
- public async save(messages: any[]): Promise<void> {
- try {
- const filePath = this.getConversationFilePath(
- this.agentId,
- this.conversationID
- );
- await this.ensureDirectoryExistence(filePath);
- await fs.promises.writeFile(
- filePath,
- JSON.stringify(messages, null, 2),
- "utf-8"
- );
- } catch (error) {
- // Saving is not critical, so we can simply log the error and continue without interrupting the process.
- console.warn("Error saving Conversation: ", error);
- }
- }
- public async load(count?: number): Promise<any[]> {
- const conversations = await this.getConversationById(
- this.agentId,
- this.conversationID
- );
-
- if (count === undefined) return conversations;
-
- if (typeof count === "number" && count > 0) {
- return conversations.slice(-count);
- }
- }
-
- public async getMessage(message_id: string): Promise<any> {
- return [];
- }
-
- private async getConversationById(
- agentId: string,
- conversationId: string
- ): Promise<Record<string, any>[]> {
- const folderPath = path.join(this.sessionsPath, agentId);
-
- if (!(await fsExists(folderPath))) {
- return [];
- }
-
- const filePath = path.join(folderPath, conversationId + ".json");
-
- if (!(await fsExists(filePath))) {
- return [];
- }
-
- try {
- const fileContent = await fs.promises.readFile(filePath, {
- encoding: "utf8",
- });
- return JSON.parse(fileContent);
- } catch (error) {
- return [];
- }
- }
-
- private getConversationFilePath(
- agentId: string,
- conversationID: string
- ): string {
- return path.join(this.sessionsPath, agentId, `${conversationID}.json`);
- }
-
- private async ensureDirectoryExistence(filePath: string): Promise<void> {
- const dir = path.dirname(filePath);
- if (await fsExists(dir)) {
- return;
- }
- await fs.promises.mkdir(dir, { recursive: true });
- }
-}
diff --git a/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts b/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts
index b525abbc..6552e255 100644
--- a/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts
+++ b/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts
@@ -3,14 +3,15 @@ import { Request } from "express";
import { Agent, AgentLogger, Conversation } from "@smythos/sre";
import config from "@core/config";
+import { DEFAULT_MODEL } from "@core/constants";
import { EMBODIMENT_TYPES } from "@embodiment/constants";
import { getOpenAPIJSONForAI } from "../helpers/openapi-adapter.helper";
-import { FsChatbotContextStore } from "./FsChatbotContextStore.class";
-import { ConversationStreamYield } from "./FsChatbotContextStore.class/FsChatbotContextExporter.class";
import { ChatConversationsEnv } from "../utils/chat.utils";
import { delay } from "../utils/date-time.utils";
+import { FsChatbotContextStore } from "./FsChatbotContextStore.class";
+import { ConversationStreamYield } from "./FsChatbotContextStore.class/FsChatbotContextExporter.class";
type Headers = {
"x-conversation-id": string;
@@ -46,7 +47,7 @@ export default class Chatbot {
private agent: Agent;
private systemMessage = "";
- private model = "gpt-4o-mini";
+ private model = DEFAULT_MODEL;
private modelInfo: any;
private function_call_order = 0;
private contextWindow = 1024 * 128;