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.

resolve all imports for embodiment

Forhad Hosainb3ab7a28ff3a
diff --git a/.vscode/launch.json b/.vscode/launch.json
index 3b9542be..aea9017f 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -36,6 +36,27 @@
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
+ },
+ {
+ "name": "Launch Runtime Server",
+ "type": "node",
+ "request": "launch",
+ "program": "${workspaceFolder}/packages/runtime/dist/runtime-server.dev.cjs",
+ "preLaunchTask": "runtime: build:dev",
+ "skipFiles": ["<node_internals>/**"],
+ "sourceMaps": true,
+ "outFiles": ["${workspaceFolder}/packages/runtime/dist/**/*.js"],
+ "cwd": "${workspaceFolder}/packages/runtime"
+ },
+ {
+ "name": "Launch Runtime Server (No Build)",
+ "type": "node",
+ "request": "launch",
+ "program": "${workspaceFolder}/packages/runtime/dist/runtime-server.dev.cjs",
+ "skipFiles": ["<node_internals>/**"],
+ "sourceMaps": true,
+ "outFiles": ["${workspaceFolder}/packages/runtime/dist/**/*.js"],
+ "cwd": "${workspaceFolder}/packages/runtime"
}
]
}
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 9c195129..c0769343 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -14,12 +14,11 @@
"typescript.preferences.includePackageJsonAutoImports": "auto",
"typescript.suggest.autoImports": true,
"typescript.preferences.useAliasesForRenames": true,
-
+
// ✅ CORRECT CURRENT SETTINGS: Force alias usage
"typescript.suggest.includeAutomaticOptionalChainCompletions": true,
"typescript.updateImportsOnPaste.enabled": true,
-
+ "cSpell.words": ["logto", "smythos"]
-
// ✅ Additional helpful settings
}
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
new file mode 100644
index 00000000..ffaca8be
--- /dev/null
+++ b/.vscode/tasks.json
@@ -0,0 +1,21 @@
+{
+ "version": "2.0.0",
+ "tasks": [
+ {
+ "label": "runtime: build:dev",
+ "type": "npm",
+ "script": "build:dev",
+ "path": "packages/runtime/",
+ "group": "build",
+ "presentation": {
+ "echo": true,
+ "reveal": "always",
+ "focus": false,
+ "panel": "shared",
+ "showReuseMessage": true,
+ "clear": false
+ },
+ "problemMatcher": []
+ }
+ ]
+}
diff --git a/packages/runtime/CLAUDE.md b/packages/runtime/CLAUDE.md
deleted file mode 100644
index e1aefadb..00000000
--- a/packages/runtime/CLAUDE.md
+++ /dev/null
@@ -1 +0,0 @@
-Please remove any test files you created during this run, as well as the .md file that documents what was done. Do not remove any of my original or important files—only delete files that you generated for testing and explanation purposes.
diff --git a/packages/runtime/CORS_CONFIG.md b/packages/runtime/CORS_CONFIG.md
deleted file mode 100644
index 5c2255b8..00000000
--- a/packages/runtime/CORS_CONFIG.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# Minimal CORS Configuration
-
-Simple CORS setup - allows all origins in development, configurable for production.
-
-## Configuration
-
-**Development**: All origins allowed automatically
-**Production**: Set `CORS_ORIGINS` environment variable
-
-```bash
-# Production only - comma-separated allowed origins
-CORS_ORIGINS=https://yourdomain.com,https://anotherdomain.com
-```
-
-## Behavior
-
-- **Development**: `origin: true` (allows all)
-- **Production**: Uses `CORS_ORIGINS` or blocks all if not set
-- **Credentials**: Always enabled
-- **Methods**: GET, POST, PUT, DELETE, OPTIONS
-- **Headers**: Content-Type, Authorization
\ No newline at end of file
diff --git a/packages/runtime/package.json b/packages/runtime/package.json
index 4e43f9d5..ae2be9c9 100644
--- a/packages/runtime/package.json
+++ b/packages/runtime/package.json
@@ -37,6 +37,7 @@
"dependencies": {
"@aws-sdk/client-s3": "^3.717.0",
"@modelcontextprotocol/sdk": "^1.10.1",
+ "@smythos/sre": "^1.5.50",
"axios": "^1.7.7",
"compression": "^1.8.0",
"cookie-parser": "^1.4.7",
diff --git a/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts b/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts
index ac9fc020..48972569 100644
--- a/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts
+++ b/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts
@@ -1,19 +1,18 @@
+import { getM2MToken } from "@/core/helpers/logto.helper";
+import { SmythConfigs } from "@core/types/general.types";
import {
- Connector,
AccessRequest,
AccountConnector,
+ ACL,
+ ConnectorService,
IAccessCandidate,
+ KeyValueObject,
Logger,
OAuthConfig,
- TAccessRole,
- KeyValueObject,
- ConnectorService,
TAccessLevel,
- ACL,
+ TAccessRole,
} from "@smythos/sre";
import axios, { AxiosInstance } from "axios";
-import { getM2MToken } from "@core/services/logto-helper";
-import { SmythConfigs } from "@core/types/general.types";
const console = Logger("SmythOSSAccount");
export class SmythOSSAccount extends AccountConnector {
diff --git a/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts b/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts
index eecbc978..a1602775 100644
--- a/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts
+++ b/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts
@@ -1,7 +1,7 @@
+import { getM2MToken } from "@/core/helpers/logto.helper";
+import { SmythConfigs } from "@core/types/general.types";
import { AgentDataConnector, OAuthConfig } from "@smythos/sre";
import axios, { AxiosInstance } from "axios";
-import { SmythConfigs } from "@core/types/general.types";
-import { getM2MToken } from "@core/services/logto-helper";
export class SmythOSSAgentDataConnector extends AgentDataConnector {
public name: string = "SmythOSSAgentData";
private oAuthAppId: string;
diff --git a/packages/runtime/src/core/connectors/SmythOSSManagedVault.class.ts b/packages/runtime/src/core/connectors/SmythOSSManagedVault.class.ts
index e1c639e5..d56a862e 100644
--- a/packages/runtime/src/core/connectors/SmythOSSManagedVault.class.ts
+++ b/packages/runtime/src/core/connectors/SmythOSSManagedVault.class.ts
@@ -1,3 +1,5 @@
+import { getM2MToken } from "@/core/helpers/logto.helper";
+import { SmythConfigs } from "@core/types/general.types";
import {
ACL,
AccessRequest,
@@ -11,8 +13,6 @@ import {
TAccessRole,
} from "@smythos/sre";
import axios, { AxiosInstance } from "axios";
-import { SmythConfigs } from "@core/types/general.types";
-import { getM2MToken } from "@core/services/logto-helper";
const console = Logger("SmythOSSManagedVault");
export class SmythOSSManagedVault extends ManagedVaultConnector {
public name: string = "SmythOSSManagedVault";
diff --git a/packages/runtime/src/core/connectors/SmythOSSVault.class.ts b/packages/runtime/src/core/connectors/SmythOSSVault.class.ts
index 4e436fe6..3aeaad64 100644
--- a/packages/runtime/src/core/connectors/SmythOSSVault.class.ts
+++ b/packages/runtime/src/core/connectors/SmythOSSVault.class.ts
@@ -1,17 +1,17 @@
+import { getM2MToken } from "@/core/helpers/logto.helper";
import {
+ AccessRequest,
+ ACL,
ConnectorService,
+ IAccessCandidate,
Logger,
- VaultConnector,
OAuthConfig,
- AccessRequest,
SecureConnector,
- IAccessCandidate,
TAccessLevel,
TAccessRole,
- ACL,
+ VaultConnector,
} from "@smythos/sre";
import axios, { AxiosInstance } from "axios";
-import { getM2MToken } from "@core/services/logto-helper";
export type SmythVaultConfig = {
vaultAPIBaseUrl: string;
diff --git a/packages/runtime/src/core/constants.ts b/packages/runtime/src/core/constants.ts
index 90785cea..073f4279 100644
--- a/packages/runtime/src/core/constants.ts
+++ b/packages/runtime/src/core/constants.ts
@@ -41,3 +41,4 @@ export const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB
export const MAX_FILE_COUNT = 5;
export const AGENT_AUTH_SETTINGS_KEY = "agentAuth";
+export const MOCK_DATA_SETTINGS_KEY = "agent-mock-data";
diff --git a/packages/runtime/src/core/helpers/agent.helper.ts b/packages/runtime/src/core/helpers/agent.helper.ts
new file mode 100644
index 00000000..14b462ba
--- /dev/null
+++ b/packages/runtime/src/core/helpers/agent.helper.ts
@@ -0,0 +1,276 @@
+import axios from "axios";
+import config from "../config";
+
+import { Logger } from "@smythos/sre";
+
+import { includeAuth, mwSysAPI } from "../services/smythAPIReq";
+import { getM2MToken } from "./logto.helper";
+
+import {
+ AGENT_AUTH_SETTINGS_KEY,
+ MOCK_DATA_SETTINGS_KEY,
+ PROD_VERSION_VALUES,
+ TEST_VERSION_VALUES,
+} from "@core/constants";
+import { AccessCandidate, ConnectorService } from "@smythos/sre";
+import { defaultFileParsingAgent } from "../default-file-parsing-agent";
+
+const logger = Logger("(Core) Service: Agent Helper");
+
+export function extractAgentVerionsAndPath(url) {
+ const regex = /^\/v(\d+(\.\d+)?)?(\/api\/.+)/;
+ const match = url.match(regex);
+
+ if (match) {
+ return {
+ path: match[3],
+ version: match[1] || "",
+ };
+ } else {
+ return {
+ path: url,
+ version: "",
+ };
+ }
+}
+
+export async function getAgentDomainById(agentId: string) {
+ const token = (await getM2MToken("https://api.smyth.ai")) as string;
+ const agentDataConnector = ConnectorService.getAgentDataConnector();
+
+ const Authorization = `Bearer ${token}`;
+
+ const result: any = await mwSysAPI
+ .get("/domains?verified=true", { headers: { Authorization } })
+ .catch((error) => ({ error }));
+
+ if (result.error) {
+ throw new Error("Error getting domain info");
+ }
+
+ const domain = result.data.domains.find(
+ (domainEntry: any) => domainEntry?.aiAgent?.id === agentId
+ )?.name;
+
+ if (!domain) {
+ const deployed = await agentDataConnector.isDeployed(agentId);
+ if (deployed) {
+ return `${agentId}.${config.env.PROD_AGENT_DOMAIN}`;
+ } else {
+ return `${agentId}.${config.env.AGENT_DOMAIN}`;
+ }
+ }
+ return domain;
+}
+
+export async function readAgentOAuthConfig(agentData) {
+ const authInfo = await getAgentAuthData(agentData.id);
+ const method = authInfo?.method;
+ const provider = authInfo?.provider[authInfo?.method];
+ if (!provider) {
+ return {};
+ }
+ const authOIDCConfigURL = provider.OIDCConfigURL;
+ const clientID = provider.clientID;
+ const clientSecret = provider.clientSecret;
+ const openid: any = await axios
+ .get(authOIDCConfigURL)
+ .catch((error) => ({ error }));
+
+ const tokenURL = openid?.data?.token_endpoint;
+ const authorizationURL = openid?.data?.authorization_endpoint;
+
+ return {
+ authorizationURL,
+ tokenURL,
+ clientID,
+ clientSecret,
+ method,
+ provider,
+ };
+}
+
+export function getAgentIdAndVersion(model: string) {
+ const [agentId, version] = model.split("@");
+ let agentVersion = version?.trim() || undefined;
+ if (TEST_VERSION_VALUES.includes(agentVersion)) {
+ agentVersion = "";
+ }
+ if (PROD_VERSION_VALUES.includes(agentVersion)) {
+ agentVersion = "latest";
+ }
+
+ return { agentId, agentVersion };
+}
+
+export async function getAgentEmbodiments(agentID) {
+ try {
+ const token = (await getM2MToken("https://api.smyth.ai")) as string;
+ const response = await axios.get(
+ `${config.env.SMYTH_API_BASE_URL}/_sysapi/v1/embodiments?aiAgentId=${agentID}`,
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ }
+ );
+ return response.data.embodiments;
+ } catch (error: any) {
+ logger.error(error.response?.data, error.message);
+ throw new Error(
+ `Error getting embodiments for agentId=${agentID}: ${error?.message}`
+ );
+ }
+}
+
+export async function getAgentIdByDomain(domain = "") {
+ let agentId;
+ //first check if this is the internal wildcard agents domain
+ const isStageWildcardDomain = domain.includes(config.env.AGENT_DOMAIN);
+ const isProdWildcardDomain = domain.includes(config.env.PROD_AGENT_DOMAIN);
+ if (isStageWildcardDomain || isProdWildcardDomain) {
+ agentId = domain.split(".")[0];
+ if (
+ `${agentId}.${config.env.AGENT_DOMAIN}` !== domain &&
+ `${agentId}.${config.env.PROD_AGENT_DOMAIN}` !== domain
+ ) {
+ throw new Error(`Invalid agent domain: ${domain}`);
+ }
+ if (isStageWildcardDomain) return agentId;
+ }
+
+ const token = (await getM2MToken("https://api.smyth.ai")) as string;
+ const Authorization = `Bearer ${token}`;
+ const result: any = await mwSysAPI
+ .get("/domains?verified=true", { headers: { Authorization } })
+ .catch((error) => ({ error }));
+
+ if (result.error) {
+ throw new Error("Error getting domain info");
+ }
+
+ if (agentId) {
+ const hasDomain = result.data.domains.find(
+ (domainEntry: any) => domainEntry?.aiAgent?.id === agentId
+ );
+ if (hasDomain) {
+ throw new Error("Wrong domain");
+ }
+ } else {
+ agentId = result.data.domains.find(
+ (domainEntry: any) => domainEntry.name === domain
+ )?.aiAgent?.id;
+ }
+
+ return agentId;
+}
+
+function migrateAgentData(data) {
+ if (!data.version) {
+ const newData = JSON.parse(JSON.stringify(data));
+ for (let component of newData.components) {
+ component.outputs = component.connectors;
+ component.inputs = component.receptors;
+ component.outputProps = component.connectorProps;
+ component.inputProps = component.receptorProps;
+ delete component.connectors;
+ delete component.receptors;
+ delete component.connectorProps;
+ delete component.receptorProps;
+ }
+ return newData;
+ }
+
+ if (data.version === "1.0.0") {
+ if (data.description && !data.behavior) {
+ data.behavior = data.description;
+ }
+ }
+
+ return data;
+}
+
+export async function getAgentDataById(agentID, version) {
+ try {
+ const token = (await getM2MToken("https://api.smyth.ai")) as string;
+
+ let agentObj;
+
+ const response = await mwSysAPI.get(
+ `/ai-agent/${agentID}?include=team.subscription`,
+ includeAuth(token)
+ );
+ agentObj = response.data.agent;
+ const authData = agentObj.data.auth;
+
+ const tasksResponse = await mwSysAPI.get(
+ `/quota/team/${agentObj.teamId}/tasks/subscription`,
+ includeAuth(token)
+ );
+ agentObj.taskData = tasksResponse.data;
+
+ agentObj.data.debugSessionEnabled =
+ agentObj?.data?.debugSessionEnabled && agentObj?.isLocked;
+
+ if (version) {
+ const deploymentsList = await mwSysAPI.get(
+ `/ai-agent/${agentID}/deployments`,
+ includeAuth(token)
+ );
+ const deployment =
+ version == "latest"
+ ? deploymentsList?.data?.deployments[0]
+ : deploymentsList?.data?.deployments?.find(
+ (deployment) => deployment.version === version
+ );
+ if (deployment) {
+ const deployResponse = await mwSysAPI.get(
+ `/ai-agent/deployments/${deployment.id}`,
+ includeAuth(token)
+ );
+ agentObj.data = deployResponse?.data?.deployment?.aiAgentData;
+ agentObj.data.debugSessionEnabled = false;
+ agentObj.data.agentVersion = deployment.version;
+ } else {
+ throw new Error(`Requested Deploy Version not found: ${version}`);
+ }
+ }
+
+ if (!agentObj?.data?.auth?.method || agentObj?.data?.auth?.method == "none")
+ agentObj.data.auth = authData;
+
+ agentObj.data = migrateAgentData(agentObj.data);
+
+ return agentObj;
+ } catch (error: any) {
+ logger.error(error.response?.data, error.message);
+ throw new Error(
+ `Error getting agent data for agentId=${agentID}: ${error?.message}`
+ );
+ }
+}
+
+export function addDefaultComponentsAndConnections(agentData) {
+ agentData.data.components?.unshift(...defaultFileParsingAgent.components);
+ agentData.data.connections?.unshift(...defaultFileParsingAgent.connections);
+}
+
+async function fetchAgentAuthData(agentId: string) {
+ const accountConnector = ConnectorService.getAccountConnector();
+ return await accountConnector
+ .user(AccessCandidate.agent(agentId))
+ .getAgentSetting(AGENT_AUTH_SETTINGS_KEY);
+}
+
+export async function getAgentAuthData(agentId: string) {
+ const freshSettings = await fetchAgentAuthData(agentId);
+ return JSON.parse(freshSettings || "{}");
+}
+
+export async function getMockData(agentId: string) {
+ const accountConnector = ConnectorService.getAccountConnector();
+ const mockData = await accountConnector
+ .user(AccessCandidate.agent(agentId))
+ .getAgentSetting(MOCK_DATA_SETTINGS_KEY);
+ return JSON.parse(mockData || "{}");
+}
diff --git a/packages/runtime/src/core/services/logto-helper.ts b/packages/runtime/src/core/helpers/logto.helper.ts
similarity index 100%
rename from packages/runtime/src/core/services/logto-helper.ts
rename to packages/runtime/src/core/helpers/logto.helper.ts
diff --git a/packages/runtime/src/core/services/agent-helper.ts b/packages/runtime/src/core/services/agent-helper.ts
deleted file mode 100644
index 4b7bca1d..00000000
--- a/packages/runtime/src/core/services/agent-helper.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import config from "../config";
-import axios from "axios";
-
-import { Logger } from "@smythos/sre";
-
-import { getM2MToken } from "./logto-helper";
-import { mwSysAPI } from "./smythAPIReq";
-
-import { AccessCandidate, ConnectorService } from "@smythos/sre";
-import { defaultFileParsingAgent } from "../default-file-parsing-agent";
-import { AGENT_AUTH_SETTINGS_KEY } from "@core/constants";
-
-const console = Logger("(Core) Service: Agent Helper");
-
-export function extractAgentVerionsAndPath(url) {
- const regex = /^\/v(\d+(\.\d+)?)?(\/api\/.+)/;
- const match = url.match(regex);
-
- if (match) {
- return {
- path: match[3],
- version: match[1] || "",
- };
- } else {
- return {
- path: url,
- version: "",
- };
- }
-}
-
-export async function getAgentDomainById(agentId: string) {
- const token = (await getM2MToken("https://api.smyth.ai")) as string;
- const agentDataConnector = ConnectorService.getAgentDataConnector();
-
- const Authorization = `Bearer ${token}`;
-
- //TODO : OPTIMIZE THIS : use aiAgentId param instead of getting all domains then filtering
- const result: any = await mwSysAPI
- .get("/domains?verified=true", { headers: { Authorization } })
- .catch((error) => ({ error }));
-
- if (result.error) {
- throw new Error("Error getting domain info");
- }
-
- const domain = result.data.domains.find(
- (domainEntry: any) => domainEntry?.aiAgent?.id === agentId
- )?.name;
-
- if (!domain) {
- const deployed = await agentDataConnector.isDeployed(agentId);
- if (deployed) {
- return `${agentId}.${config.env.PROD_AGENT_DOMAIN}`;
- }
- }
- return domain;
-}
-
-export async function readAgentOAuthConfig(agentData) {
- //const authInfo = agentData?.auth;
- const authInfo = await getAgentAuthData(agentData.id);
- const method = authInfo?.method;
- const provider = authInfo?.provider[authInfo?.method];
- if (!provider) {
- return {};
- }
- const authOIDCConfigURL = provider.OIDCConfigURL;
- const clientID = provider.clientID;
- const clientSecret = provider.clientSecret;
- const openid: any = await axios
- .get(authOIDCConfigURL)
- .catch((error) => ({ error }));
-
- const tokenURL = openid?.data?.token_endpoint;
- const authorizationURL = openid?.data?.authorization_endpoint;
-
- return {
- authorizationURL,
- tokenURL,
- clientID,
- clientSecret,
- method,
- provider,
- };
-}
-
-export function addDefaultComponentsAndConnections(agentData) {
- console.log(
- `Adding default components and connections for file parsing agent`
- );
- agentData.data.components?.unshift(...defaultFileParsingAgent.components);
- agentData.data.connections?.unshift(...defaultFileParsingAgent.connections);
-}
-
-// #region Agent Auth Data
-
-/**
- * Fetches agent authentication data from the account connector
- * @param agentId - The ID of the agent
- * @returns Promise containing the agent settings
- */
-async function fetchAgentAuthData(agentId: string) {
- const accountConnector = ConnectorService.getAccountConnector();
- return await accountConnector
- .user(AccessCandidate.agent(agentId))
- .getAgentSetting(AGENT_AUTH_SETTINGS_KEY);
-}
-
-/**
- * Gets agent authentication data
- * @param agentId - The ID of the agent
- * @returns Promise containing the agent auth settings
- */
-export async function getAgentAuthData(agentId: string) {
- const freshSettings = await fetchAgentAuthData(agentId);
-
- return JSON.parse(freshSettings || "{}");
-}
-// #endregion Agent Auth Data
-
-const MOCK_DATA = {
- SETTINGS_KEY: "agent-mock-data",
-} as const;
-
-export async function getMockData(agentId: string) {
- const accountConnector = ConnectorService.getAccountConnector();
- const mockData = await accountConnector
- .user(AccessCandidate.agent(agentId))
- .getAgentSetting(MOCK_DATA.SETTINGS_KEY);
- return JSON.parse(mockData || "{}");
-}
diff --git a/packages/runtime/src/core/types/declarations/smythos.express.d.ts b/packages/runtime/src/core/types/declarations/smythos.express.d.ts
index 905a6c1d..18db9715 100644
--- a/packages/runtime/src/core/types/declarations/smythos.express.d.ts
+++ b/packages/runtime/src/core/types/declarations/smythos.express.d.ts
@@ -1,15 +1,17 @@
-import { Agent } from 'smyth-runtime';
-import multer from 'multer';
+import multer from "multer";
+
+import Chatbot from "@embodiment/modules/chatbot/services/Chatbot.class";
+import { Agent } from "@smythos/sre";
declare global {
- namespace Express {
- interface Request {
- _agent_authinfo: any; // Define your custom property here
- _chatbot: any;
- _agent: Agent;
- session: any;
- files: multer.File[];
- sessionID: string;
- }
+ namespace Express {
+ interface Request {
+ _agent_authinfo: any; // Define your custom property here
+ _chatbot: Chatbot;
+ _agent: Agent;
+ session: any;
+ files: multer.File[];
+ sessionID: string;
}
+ }
}
diff --git a/packages/runtime/src/core/utils/llm.utils.ts b/packages/runtime/src/core/utils/llm.utils.ts
index 0267e7cd..6a63f456 100644
--- a/packages/runtime/src/core/utils/llm.utils.ts
+++ b/packages/runtime/src/core/utils/llm.utils.ts
@@ -1,4 +1,4 @@
-import { MODELS_FOR_LEGACY_USERS } from '@/constants';
+import { MODELS_FOR_LEGACY_USERS } from "@core/constants";
/**
* Adapts a model name based on user plan information and model availability.
@@ -17,24 +17,24 @@ import { MODELS_FOR_LEGACY_USERS } from '@/constants';
* @example
* -- For a free user trying to use a legacy model
* adaptModel('gpt-3.5-turbo', { isDefaultPlan: true }) // Returns 'legacy/gpt-3.5-turbo'
- *
+ *
* @example
* -- For a premium user
* adaptModel('gpt-4', { isDefaultPlan: false, flags: { hasBuiltinModels: true } }) // Returns 'gpt-4'
*/
export function adaptModel(model: string, planInfo: Record<string, any>) {
- try {
- const isFreeUser = planInfo?.isDefaultPlan;
- const hasBuiltInModels = isFreeUser || planInfo?.flags?.hasBuiltinModels;
-
- // If the model is listed in the legacy models array and the user doesn't have access to built-in models, prefix the model with 'legacy/' to allow the model to be used
- if (!hasBuiltInModels && MODELS_FOR_LEGACY_USERS.includes(model)) {
- return `legacy/${model}`;
- }
+ try {
+ const isFreeUser = planInfo?.isDefaultPlan;
+ const hasBuiltInModels = isFreeUser || planInfo?.flags?.hasBuiltinModels;
- return model;
- } catch {
- // Fallback: if any error occurs during processing, return the original model to ensure function never throws
- return model;
+ // If the model is listed in the legacy models array and the user doesn't have access to built-in models, prefix the model with 'legacy/' to allow the model to be used
+ if (!hasBuiltInModels && MODELS_FOR_LEGACY_USERS.includes(model)) {
+ return `legacy/${model}`;
}
+
+ return model;
+ } catch {
+ // Fallback: if any error occurs during processing, return the original model to ensure function never throws
+ return model;
+ }
}
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index a81aa8f4..0f02c977 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -1,32 +1,32 @@
-import url from "url";
-import path from "path";
-import express from "express";
-import { Server } from "http";
-import cookieParser from "cookie-parser";
-import compression from "compression";
-import swaggerUi from "swagger-ui-express";
import {
- SmythRuntime,
- Logger,
- version,
ConnectorService,
- TConnectorService,
JSONModelsProvider,
+ Logger,
+ SmythRuntime,
+ TConnectorService,
+ version,
} from "@smythos/sre";
+import compression from "compression";
+import cookieParser from "cookie-parser";
+import express from "express";
+import { Server } from "http";
+import path from "path";
+import swaggerUi from "swagger-ui-express";
+import url from "url";
// Core imports
-import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
import config from "@core/config";
import { startServers } from "@core/management-router";
-import { errorHandler, notFoundHandler } from "@core/middlewares/error.mw";
import cors from "@core/middlewares/cors.mw";
+import { errorHandler, notFoundHandler } from "@core/middlewares/error.mw";
import RateLimiter from "@core/middlewares/rateLimiter.mw";
+import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
import { requestContext } from "@core/services/request-context";
+import { SmythOSSAccount } from "@core/connectors/SmythOSSAccount.class";
import { SmythOSSAgentDataConnector } from "@core/connectors/SmythOSSAgentDataConnector.class";
-import { SmythOSSVault } from "@core/connectors/SmythOSSVault.class";
import { SmythOSSManagedVault } from "@core/connectors/SmythOSSManagedVault.class";
-import { SmythOSSAccount } from "@core/connectors/SmythOSSAccount.class";
+import { SmythOSSVault } from "@core/connectors/SmythOSSVault.class";
// Debugger Imports
import agentRouter from "@debugger/routes/agent/routes";
@@ -37,11 +37,12 @@ import modelsRouter from "@debugger/routes/models/router";
// import oauthRouter from "@agent-runner/routes/_oauth/router";
// Embodiment imports
-// import { routes as embodimentRoutes } from "@embodiment/routes";
+import { routes as embodimentRoutes } from "@embodiment/routes";
const app = express();
const port = parseInt(process.env.PORT || "5000");
+// TODO [Runtime]: move all connection registration in different place
ConnectorService.register(
TConnectorService.AgentData,
"SmythOSS",
@@ -123,6 +124,7 @@ const sre = SmythRuntime.Instance.init({
ModelsProvider: {
Connector: "SmythModelsProvider",
Settings: {
+ // TODO [Runtime]: Move all the models list in different place to keep the index.ts clean
models: {
"gpt-5": {
label: "GPT 5",
@@ -374,8 +376,8 @@ app.get("/", (req: any, res) => {
app.use("/", agentRouter);
app.use("/models", modelsRouter);
// app.use("/oauth", oauthRouter);
-// app.use("/emb/swagger", swaggerUi.serve);
-// app.use("/", embodimentRoutes);
+app.use("/swagger", swaggerUi.serve);
+app.use("/", embodimentRoutes);
// 404 handler - must come before error handler
app.use(notFoundHandler);
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts b/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts
index b7b06d6b..1a55b52f 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts
@@ -1,9 +1,9 @@
import { NextFunction, Response } from "express";
-import OIDCMWFactory from "./oidc";
import BearerMWFactory from "./bearer";
+import OIDCMWFactory from "./oidc";
+import { getAgentAuthData } from "../../../../core/helpers/agent.helper";
import { createLogger } from "../../../../core/services/logger";
-import { getAgentAuthData } from "../../../../core/services/agent-helper";
const console = createLogger("___FILENAME___");
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts b/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts
index 7af76ca7..f2cace2a 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts
@@ -1,13 +1,13 @@
+import config from "../config";
import {
addDefaultComponentsAndConnections,
extractAgentVerionsAndPath,
getAgentDomainById,
} from "../services/agent-helper";
-import config from "../config";
-import { createLogger } from "../services/logger";
-import { ConnectorService } from "smyth-runtime";
+import { ConnectorService } from "@smythos/sre";
import { DEFAULT_FILE_PARSING_ENDPOINT } from "../constants";
+import { createLogger } from "../services/logger";
import { refreshBillingCache } from "../services/billing-service";
@@ -35,15 +35,17 @@ export default async function agentLoader(req, res, next) {
try {
const result = agentDataConnector?.getAgentIdByDomain?.(domain);
- if (result && typeof result.catch === 'function') {
+ if (result && typeof result.catch === "function") {
agentId = await result.catch((error) => {
console.error(error);
});
} else {
- console.error('getAgentIdByDomain method is not available or does not return a promise');
+ console.error(
+ "getAgentIdByDomain method is not available or does not return a promise"
+ );
}
} catch (error) {
- console.error('Error calling getAgentIdByDomain:', error);
+ console.error("Error calling getAgentIdByDomain:", error);
}
agentDomain = domain;
if (agentId && domain.includes(config.env.AGENT_DOMAIN)) {
@@ -65,17 +67,19 @@ export default async function agentLoader(req, res, next) {
let agentData;
try {
const result = agentDataConnector?.getAgentData?.(agentId, version);
- if (result && typeof result.catch === 'function') {
+ if (result && typeof result.catch === "function") {
agentData = await result.catch((error) => {
console.error(error);
return { error: error.message };
});
} else {
- console.error('getAgentData method is not available or does not return a promise');
- agentData = { error: 'getAgentData method is not available' };
+ console.error(
+ "getAgentData method is not available or does not return a promise"
+ );
+ agentData = { error: "getAgentData method is not available" };
}
} catch (error) {
- console.error('Error calling getAgentData:', error);
+ console.error("Error calling getAgentData:", error);
agentData = { error: error.message };
}
if (agentData?.error) {
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/index.ts b/packages/runtime/src/modules/agent-runner/middlewares/index.ts
index 1121b4a0..7ce9f7a4 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/index.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/index.ts
@@ -1,9 +1,9 @@
import { NextFunction, Response } from "express";
-import OIDCMWFactory from "./oidc";
import BearerMWFactory from "./bearer";
+import OIDCMWFactory from "./oidc";
+import { getAgentAuthData } from "../../../core/helpers/agent.helper";
import { createLogger } from "../../../core/services/logger";
-import { getAgentAuthData } from "../../../core/services/agent-helper";
const console = createLogger("___FILENAME___");
diff --git a/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts b/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts
index 2b142fc9..2af0ef19 100644
--- a/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts
+++ b/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts
@@ -1,10 +1,8 @@
-import express from "express";
+import { readAgentOAuthConfig } from "@/core/helpers/agent.helper";
+import agentLoader from "@core/middlewares/agentLoader.mw";
import axios from "axios";
+import express, { Request, Response } from "express";
import querystring from "querystring";
-import config from "@core/config";
-import agentLoader from "@core/middlewares/agentLoader.mw";
-import { readAgentOAuthConfig } from "@core/services/agent-helper";
-import { Request, Response } from "express";
const router = express.Router();
diff --git a/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts b/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts
index f9bff037..2c581241 100644
--- a/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts
+++ b/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts
@@ -1,10 +1,10 @@
-import { Logger, ConnectorService } from "@smythos/sre";
+import { ConnectorService, Logger } from "@smythos/sre";
import {
addDefaultComponentsAndConnections,
extractAgentVerionsAndPath,
getAgentDomainById,
-} from "@core/services/agent-helper";
+} from "@/core/helpers/agent.helper";
import config from "@core/config";
const console = Logger("[Debugger] Middleware: agentLoader");
diff --git a/packages/runtime/src/modules/debugger/services/agent-request-handler.ts b/packages/runtime/src/modules/debugger/services/agent-request-handler.ts
index 247b870a..eaae7f07 100644
--- a/packages/runtime/src/modules/debugger/services/agent-request-handler.ts
+++ b/packages/runtime/src/modules/debugger/services/agent-request-handler.ts
@@ -1,10 +1,10 @@
-import { Request, Response } from "express";
import axios from "axios";
+import { Request } from "express";
import { Logger } from "@smythos/sre";
+import { getMockData } from "@/core/helpers/agent.helper";
import { AgentProcess } from "@smythos/sre";
-import { getMockData } from "@core/services/agent-helper";
const console = Logger("Service: Agent Request Handler");
diff --git a/packages/runtime/src/modules/embodiment/helpers/agent.helper.ts b/packages/runtime/src/modules/embodiment/helpers/agent.helper.ts
index 3c22b6f6..be8dee02 100644
--- a/packages/runtime/src/modules/embodiment/helpers/agent.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/agent.helper.ts
@@ -1,240 +1,291 @@
-import config from '@embodiment/config';
-import { AccessCandidate, ConnectorService } from 'smyth-runtime';
-import { getM2MToken } from '@embodiment/helpers/logto.helper';
-import { mwSysAPI } from '@core/services/smythAPIReq';
-import { PROD_VERSION_VALUES, TEST_VERSION_VALUES } from '@embodiment/constants';
-import axios from 'axios';
-import { includeAuth } from '@core/services/smythAPIReq';
+import { AccessCandidate, ConnectorService } from "@smythos/sre";
+import axios from "axios";
+
+import config from "@core/config";
+import { PROD_VERSION_VALUES, TEST_VERSION_VALUES } from "@core/constants";
+import { includeAuth, mwSysAPI } from "@core/services/smythAPIReq";
+import { getM2MToken } from "@embodiment/helpers/logto.helper";
export function extractAgentVerionsAndPath(url) {
- const regex = /^\/v(\d+(\.\d+)?)?(\/api\/.+)/;
- const match = url.match(regex);
-
- if (match) {
- return {
- path: match[3],
- version: match[1] || '',
- };
- } else {
- return {
- path: url,
- version: '',
- };
- }
+ const regex = /^\/v(\d+(\.\d+)?)?(\/api\/.+)/;
+ const match = url.match(regex);
+
+ if (match) {
+ return {
+ path: match[3],
+ version: match[1] || "",
+ };
+ } else {
+ return {
+ path: url,
+ version: "",
+ };
+ }
}
export function getAgentIdAndVersion(model: string) {
- const [agentId, version] = model.split('@');
- let agentVersion = version?.trim() || undefined;
- if (TEST_VERSION_VALUES.includes(agentVersion)) {
- agentVersion = '';
- }
- if (PROD_VERSION_VALUES.includes(agentVersion)) {
- agentVersion = 'latest';
- }
-
- return { agentId, agentVersion };
+ const [agentId, version] = model.split("@");
+ let agentVersion = version?.trim() || undefined;
+ if (TEST_VERSION_VALUES.includes(agentVersion)) {
+ agentVersion = "";
+ }
+ if (PROD_VERSION_VALUES.includes(agentVersion)) {
+ agentVersion = "latest";
+ }
+
+ return { agentId, agentVersion };
}
export async function getAgentEmbodiments(agentID) {
- try {
- const token = (await getM2MToken('https://api.smyth.ai')) as string;
- const url = `${config.env.SMYTH_API_BASE_URL}/_sysapi/v1/embodiments?aiAgentId=${agentID}`;
- console.log('calling URL', url);
-
- const response = await axios.get(`${config.env.SMYTH_API_BASE_URL}/_sysapi/v1/embodiments?aiAgentId=${agentID}`, {
- headers: {
- Authorization: `Bearer ${token}`,
- },
- });
- // }
- // const response = await smythAPIReq.get(`/embodiments?aiAgentId=${agentID}`, includeAuth(token));
-
- return response.data.embodiments;
- } catch (error: any) {
- console.error(error.response?.data, error.message);
- console.log(`Error getting embodiments for agentId=${agentID}: ${error?.message}`);
- throw new Error(`Error getting embodiments for agentId=${agentID}: ${error?.message}`);
-
- ///throw error;
- }
+ try {
+ const token = (await getM2MToken("https://api.smyth.ai")) as string;
+ const url = `${config.env.SMYTH_API_BASE_URL}/_sysapi/v1/embodiments?aiAgentId=${agentID}`;
+ console.log("calling URL", url);
+
+ const response = await axios.get(
+ `${config.env.SMYTH_API_BASE_URL}/_sysapi/v1/embodiments?aiAgentId=${agentID}`,
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ }
+ );
+ // }
+ // const response = await smythAPIReq.get(`/embodiments?aiAgentId=${agentID}`, includeAuth(token));
+
+ return response.data.embodiments;
+ } catch (error: any) {
+ console.error(error.response?.data, error.message);
+ console.log(
+ `Error getting embodiments for agentId=${agentID}: ${error?.message}`
+ );
+ throw new Error(
+ `Error getting embodiments for agentId=${agentID}: ${error?.message}`
+ );
+
+ ///throw error;
+ }
}
export async function getAgentDomainById(agentId: string) {
- const token = (await getM2MToken('https://api.smyth.ai')) as string;
- const agentDataConnector = ConnectorService.getAgentDataConnector();
+ const token = (await getM2MToken("https://api.smyth.ai")) as string;
+ const agentDataConnector = ConnectorService.getAgentDataConnector();
- const Authorization = `Bearer ${token}`;
+ const Authorization = `Bearer ${token}`;
- //TODO : OPTIMIZE THIS : use aiAgentId param instead of getting all domains then filtering
- const result: any = await mwSysAPI.get('/domains?verified=true', { headers: { Authorization } }).catch((error) => ({ error }));
+ //TODO : OPTIMIZE THIS : use aiAgentId param instead of getting all domains then filtering
+ const result: any = await mwSysAPI
+ .get("/domains?verified=true", { headers: { Authorization } })
+ .catch((error) => ({ error }));
- if (result.error) {
- throw new Error('Error getting domain info');
- }
+ if (result.error) {
+ throw new Error("Error getting domain info");
+ }
- const domain = result.data.domains.find((domainEntry: any) => domainEntry?.aiAgent?.id === agentId)?.name;
+ const domain = result.data.domains.find(
+ (domainEntry: any) => domainEntry?.aiAgent?.id === agentId
+ )?.name;
- if (!domain) {
- const deployed = await agentDataConnector.isDeployed(agentId);
- if (deployed) {
- return `${agentId}.${config.env.PROD_AGENT_DOMAIN}`;
- } else {
- return `${agentId}.${config.env.AGENT_DOMAIN}`;
- }
+ if (!domain) {
+ const deployed = await agentDataConnector.isDeployed(agentId);
+ if (deployed) {
+ return `${agentId}.${config.env.PROD_AGENT_DOMAIN}`;
+ } else {
+ return `${agentId}.${config.env.AGENT_DOMAIN}`;
}
- return domain;
+ }
+ return domain;
}
export async function readAgentOAuthConfig(agentData) {
- console.log('readAgentOAuthConfig', agentData?.id);
- //const authInfo = agentData?.auth;
- const authInfo = await getAgentAuthData(agentData.id);
- const method = authInfo?.method;
- const provider = authInfo?.provider[authInfo?.method];
- if (!provider) {
- return {};
- }
- const authOIDCConfigURL = provider.OIDCConfigURL;
- const clientID = provider.clientID;
- const clientSecret = provider.clientSecret;
- const openid: any = await axios.get(authOIDCConfigURL).catch((error) => ({ error }));
-
- const tokenURL = openid?.data?.token_endpoint;
- const authorizationURL = openid?.data?.authorization_endpoint;
-
- return { authorizationURL, tokenURL, clientID, clientSecret, method, provider };
+ console.log("readAgentOAuthConfig", agentData?.id);
+ //const authInfo = agentData?.auth;
+ const authInfo = await getAgentAuthData(agentData.id);
+ const method = authInfo?.method;
+ const provider = authInfo?.provider[authInfo?.method];
+ if (!provider) {
+ return {};
+ }
+ const authOIDCConfigURL = provider.OIDCConfigURL;
+ const clientID = provider.clientID;
+ const clientSecret = provider.clientSecret;
+ const openid: any = await axios
+ .get(authOIDCConfigURL)
+ .catch((error) => ({ error }));
+
+ const tokenURL = openid?.data?.token_endpoint;
+ const authorizationURL = openid?.data?.authorization_endpoint;
+
+ return {
+ authorizationURL,
+ tokenURL,
+ clientID,
+ clientSecret,
+ method,
+ provider,
+ };
}
-export async function getAgentIdByDomain(domain = '') {
- let agentId;
- //first check if this is the internal wildcard agents domain
- const isStageWildcardDomain = domain.includes(config.env.AGENT_DOMAIN);
- const isProdWildcardDomain = domain.includes(config.env.PROD_AGENT_DOMAIN);
- if (isStageWildcardDomain || isProdWildcardDomain) {
- //console.log('Internal agent domain detected', domain);
- agentId = domain.split('.')[0];
- //sanity check
- if (`${agentId}.${config.env.AGENT_DOMAIN}` !== domain && `${agentId}.${config.env.PROD_AGENT_DOMAIN}` !== domain) {
- throw new Error(`Invalid agent domain: ${domain}`);
- }
-
- //if this is a stage domain, no more check, return the agentId
- if (isStageWildcardDomain) return agentId;
- }
-
- const token = (await getM2MToken('https://api.smyth.ai')) as string;
- const Authorization = `Bearer ${token}`;
- //FIXME : filter domains by agentId and by domain Id once it's supported in the middleware
- const result: any = await mwSysAPI.get('/domains?verified=true', { headers: { Authorization } }).catch((error) => ({ error }));
-
- if (result.error) {
- throw new Error('Error getting domain info');
+export async function getAgentIdByDomain(domain = "") {
+ let agentId;
+ //first check if this is the internal wildcard agents domain
+ const isStageWildcardDomain = domain.includes(config.env.AGENT_DOMAIN);
+ const isProdWildcardDomain = domain.includes(config.env.PROD_AGENT_DOMAIN);
+ if (isStageWildcardDomain || isProdWildcardDomain) {
+ //console.log('Internal agent domain detected', domain);
+ agentId = domain.split(".")[0];
+ //sanity check
+ if (
+ `${agentId}.${config.env.AGENT_DOMAIN}` !== domain &&
+ `${agentId}.${config.env.PROD_AGENT_DOMAIN}` !== domain
+ ) {
+ throw new Error(`Invalid agent domain: ${domain}`);
}
- //we have an agentId from the wildcard domain, if this domain is already associated with
- if (agentId) {
- const hasDomain = result.data.domains.find((domainEntry: any) => domainEntry?.aiAgent?.id === agentId);
- if (hasDomain) {
- throw new Error('Wrong domain');
- }
- } else {
- agentId = result.data.domains.find((domainEntry: any) => domainEntry.name === domain)?.aiAgent?.id;
+ //if this is a stage domain, no more check, return the agentId
+ if (isStageWildcardDomain) return agentId;
+ }
+
+ const token = (await getM2MToken("https://api.smyth.ai")) as string;
+ const Authorization = `Bearer ${token}`;
+ //FIXME : filter domains by agentId and by domain Id once it's supported in the middleware
+ const result: any = await mwSysAPI
+ .get("/domains?verified=true", { headers: { Authorization } })
+ .catch((error) => ({ error }));
+
+ if (result.error) {
+ throw new Error("Error getting domain info");
+ }
+
+ //we have an agentId from the wildcard domain, if this domain is already associated with
+ if (agentId) {
+ const hasDomain = result.data.domains.find(
+ (domainEntry: any) => domainEntry?.aiAgent?.id === agentId
+ );
+ if (hasDomain) {
+ throw new Error("Wrong domain");
}
+ } else {
+ agentId = result.data.domains.find(
+ (domainEntry: any) => domainEntry.name === domain
+ )?.aiAgent?.id;
+ }
- //if a custom domain is found, use it, otherwise use the agentId from the wildcard domain
+ //if a custom domain is found, use it, otherwise use the agentId from the wildcard domain
- return agentId;
+ return agentId;
}
function migrateAgentData(data) {
- if (!data.version) {
- console.log(`Agent [${data.name}] has an old schema. Migrating to latest version...`);
- // version 0 ===> migrate from receptors/connectors to inputs/outputs
- const newData = JSON.parse(JSON.stringify(data));
- for (let component of newData.components) {
- component.outputs = component.connectors;
- component.inputs = component.receptors;
- component.outputProps = component.connectorProps;
- component.inputProps = component.receptorProps;
- delete component.connectors;
- delete component.receptors;
- delete component.connectorProps;
- delete component.receptorProps;
- }
- return newData;
+ if (!data.version) {
+ console.log(
+ `Agent [${data.name}] has an old schema. Migrating to latest version...`
+ );
+ // version 0 ===> migrate from receptors/connectors to inputs/outputs
+ const newData = JSON.parse(JSON.stringify(data));
+ for (let component of newData.components) {
+ component.outputs = component.connectors;
+ component.inputs = component.receptors;
+ component.outputProps = component.connectorProps;
+ component.inputProps = component.receptorProps;
+ delete component.connectors;
+ delete component.receptors;
+ delete component.connectorProps;
+ delete component.receptorProps;
}
-
- if (data.version === '1.0.0') {
- //migrate .description to .behavior
- if (data.description && !data.behavior) {
- data.behavior = data.description;
- //delete newConfig.description;
- }
+ return newData;
+ }
+
+ if (data.version === "1.0.0") {
+ //migrate .description to .behavior
+ if (data.description && !data.behavior) {
+ data.behavior = data.description;
+ //delete newConfig.description;
}
+ }
- return data;
+ return data;
}
//TODO : cache versioned agent data. when an agent has a version, the data does not change, we can keep it in cache to avoid calling the api every time
export async function getAgentDataById(agentID, version) {
- console.log('getAgentDataById', agentID, version);
- try {
- const token = (await getM2MToken('https://api.smyth.ai')) as string;
-
- let agentObj;
-
- //FIXME : once we have the agent name in deployment api response, we can skip this call
- const response = await mwSysAPI.get(`/ai-agent/${agentID}?include=team.subscription`, includeAuth(token));
- agentObj = response.data.agent;
- const authData = agentObj.data.auth; //use most up to date auth data
-
- const tasksResponse = await mwSysAPI.get(`/quota/team/${agentObj.teamId}/tasks/subscription`, includeAuth(token));
- agentObj.taskData = tasksResponse.data;
-
- agentObj.data.debugSessionEnabled = agentObj?.data?.debugSessionEnabled && agentObj?.isLocked; //disable debug session if agent is not locked (locked agent means that it's open in the Agent builder)
-
- if (version) {
- const deploymentsList = await mwSysAPI.get(`/ai-agent/${agentID}/deployments`, includeAuth(token));
- const deployment =
- version == 'latest'
- ? deploymentsList?.data?.deployments[0]
- : deploymentsList?.data?.deployments?.find((deployment) => deployment.version === version);
- if (deployment) {
- const deployResponse = await mwSysAPI.get(`/ai-agent/deployments/${deployment.id}`, includeAuth(token));
- agentObj.data = deployResponse?.data?.deployment?.aiAgentData;
- agentObj.data.debugSessionEnabled = false; //never enable debug session when using a deployed version
- agentObj.data.agentVersion = deployment.version;
- } else {
- //if (version !== 'latest') {
- throw new Error(`Requested Deploy Version not found: ${version}`);
- //} // if version == 'latest' but no deployment is found we just fallback to the agent live data
- }
- }
-
- //TODO: Also include team and subscription info
-
- //agentObj.data.auth = authData;
- if (!agentObj?.data?.auth?.method || agentObj?.data?.auth?.method == 'none') agentObj.data.auth = authData;
-
- agentObj.data = migrateAgentData(agentObj.data);
-
- return agentObj;
- } catch (error: any) {
- console.error(error.response?.data, error.message);
- console.log(`Error getting agent data for agentId=${agentID}: ${error?.message}`);
- throw new Error(`Error getting agent data for agentId=${agentID}: ${error?.message}`);
+ console.log("getAgentDataById", agentID, version);
+ try {
+ const token = (await getM2MToken("https://api.smyth.ai")) as string;
+
+ let agentObj;
+
+ //FIXME : once we have the agent name in deployment api response, we can skip this call
+ const response = await mwSysAPI.get(
+ `/ai-agent/${agentID}?include=team.subscription`,
+ includeAuth(token)
+ );
+ agentObj = response.data.agent;
+ const authData = agentObj.data.auth; //use most up to date auth data
+
+ const tasksResponse = await mwSysAPI.get(
+ `/quota/team/${agentObj.teamId}/tasks/subscription`,
+ includeAuth(token)
+ );
+ agentObj.taskData = tasksResponse.data;
+
+ agentObj.data.debugSessionEnabled =
+ agentObj?.data?.debugSessionEnabled && agentObj?.isLocked; //disable debug session if agent is not locked (locked agent means that it's open in the Agent builder)
+
+ if (version) {
+ const deploymentsList = await mwSysAPI.get(
+ `/ai-agent/${agentID}/deployments`,
+ includeAuth(token)
+ );
+ const deployment =
+ version == "latest"
+ ? deploymentsList?.data?.deployments[0]
+ : deploymentsList?.data?.deployments?.find(
+ (deployment) => deployment.version === version
+ );
+ if (deployment) {
+ const deployResponse = await mwSysAPI.get(
+ `/ai-agent/deployments/${deployment.id}`,
+ includeAuth(token)
+ );
+ agentObj.data = deployResponse?.data?.deployment?.aiAgentData;
+ agentObj.data.debugSessionEnabled = false; //never enable debug session when using a deployed version
+ agentObj.data.agentVersion = deployment.version;
+ } else {
+ //if (version !== 'latest') {
+ throw new Error(`Requested Deploy Version not found: ${version}`);
+ //} // if version == 'latest' but no deployment is found we just fallback to the agent live data
+ }
}
+
+ //TODO: Also include team and subscription info
+
+ //agentObj.data.auth = authData;
+ if (!agentObj?.data?.auth?.method || agentObj?.data?.auth?.method == "none")
+ agentObj.data.auth = authData;
+
+ agentObj.data = migrateAgentData(agentObj.data);
+
+ return agentObj;
+ } catch (error: any) {
+ console.error(error.response?.data, error.message);
+ console.log(
+ `Error getting agent data for agentId=${agentID}: ${error?.message}`
+ );
+ throw new Error(
+ `Error getting agent data for agentId=${agentID}: ${error?.message}`
+ );
+ }
}
// #region Agent Auth Data
// Constants for agent auth data
const AGENT_AUTH = {
- SETTINGS_KEY: 'agent-auth-data',
- CACHE: {
- KEY_PREFIX: 'agent:auth_data',
- TTL: 60 * 60 * 24 * 7, // 7 days in seconds
- },
+ SETTINGS_KEY: "agent-auth-data",
+ CACHE: {
+ KEY_PREFIX: "agent:auth_data",
+ TTL: 60 * 60 * 24 * 7, // 7 days in seconds
+ },
} as const;
/**
@@ -243,8 +294,10 @@ const AGENT_AUTH = {
* @returns Promise containing the agent settings
*/
async function fetchAgentAuthData(agentId: string) {
- const accountConnector = ConnectorService.getAccountConnector();
- return await accountConnector.user(AccessCandidate.agent(agentId)).getAgentSetting(AGENT_AUTH.SETTINGS_KEY);
+ const accountConnector = ConnectorService.getAccountConnector();
+ return await accountConnector
+ .user(AccessCandidate.agent(agentId))
+ .getAgentSetting(AGENT_AUTH.SETTINGS_KEY);
}
/**
@@ -254,23 +307,23 @@ async function fetchAgentAuthData(agentId: string) {
*/
// TODO: To get data from cache, we need to reset the cache from UI backend when auth data is updated
export async function getAgentAuthData(agentId: string) {
- // const cacheConnector = ConnectorService.getCacheConnector();
- // const cacheKey = `${AGENT_AUTH.CACHE.KEY_PREFIX}:${agentId}`;
+ // const cacheConnector = ConnectorService.getCacheConnector();
+ // const cacheKey = `${AGENT_AUTH.CACHE.KEY_PREFIX}:${agentId}`;
- // const cachedSettings = await cacheConnector.user(AccessCandidate.agent(agentId))?.get(cacheKey);
- // if (cachedSettings) {
- // return JSON.parse(cachedSettings);
- // }
+ // const cachedSettings = await cacheConnector.user(AccessCandidate.agent(agentId))?.get(cacheKey);
+ // if (cachedSettings) {
+ // return JSON.parse(cachedSettings);
+ // }
- const freshSettings = await fetchAgentAuthData(agentId);
+ const freshSettings = await fetchAgentAuthData(agentId);
- // void cacheConnector
- // .user(AccessCandidate.agent(agentId))
- // .set(cacheKey, JSON.stringify(freshSettings), AGENT_AUTH.CACHE.TTL)
- // .catch((error) => {
- // console.warn('Error setting agent auth data in cache', error?.message || error);
- // });
+ // void cacheConnector
+ // .user(AccessCandidate.agent(agentId))
+ // .set(cacheKey, JSON.stringify(freshSettings), AGENT_AUTH.CACHE.TTL)
+ // .catch((error) => {
+ // console.warn('Error setting agent auth data in cache', error?.message || error);
+ // });
- return JSON.parse(freshSettings || '{}');
+ return JSON.parse(freshSettings || "{}");
}
// #endregion Agent Auth Data
diff --git a/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts b/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts
index e5afe2b0..2139eb73 100644
--- a/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts
@@ -1,125 +1,159 @@
-import fs from 'fs';
-import path from 'path';
+import fs from "fs";
+import path from "path";
-import { getAgentDataById, getAgentEmbodiments, getAgentIdByDomain } from '@embodiment/helpers/agent.helper';
-import { EMBODIMENT_TYPES } from '@embodiment/constants';
-import { TemplateStringHelper, JSONContentHelper } from 'smyth-runtime';
-import { ChatGPTManifest } from '@embodiment/types/chatgpt.types';
+import { ChatGPTManifest } from "@/modules/embodiment/types/chatgpt.types";
+import { EMBODIMENT_TYPES } from "@core/constants";
+import {
+ getAgentDataById,
+ getAgentEmbodiments,
+ getAgentIdByDomain,
+} from "@embodiment/helpers/agent.helper";
+import { JSONContentHelper, TemplateStringHelper } from "@smythos/sre";
-let chatGPTDataPath = './data/chatGPT';
+let chatGPTDataPath = "./data/chatGPT";
// Path to data files differs between server ('./data/chatGPT') and tests ('../data/chatGPT').
if (process.env.TEST_ENV) {
- chatGPTDataPath = '../data/chatGPT';
+ chatGPTDataPath = "../data/chatGPT";
}
// a function that splits a string on a word boundary not exceeding a max characters length
-function splitOnSeparator(str = '', maxLen, separator = ' .') {
- if (str.length <= maxLen) {
- return str;
- }
+function splitOnSeparator(str = "", maxLen, separator = " .") {
+ if (str.length <= maxLen) {
+ return str;
+ }
- // Find the last occurrence of the separator before maxLen
- let idx = str.lastIndexOf(separator, maxLen);
+ // Find the last occurrence of the separator before maxLen
+ let idx = str.lastIndexOf(separator, maxLen);
- // If the separator is not found, return the substring up to maxLen
- if (idx === -1) {
- return str.substring(0, maxLen);
- }
+ // If the separator is not found, return the substring up to maxLen
+ if (idx === -1) {
+ return str.substring(0, maxLen);
+ }
- // Return the substring from the start of the string to the last occurrence of the separator
- return str.substring(0, idx);
+ // Return the substring from the start of the string to the last occurrence of the separator
+ return str.substring(0, idx);
}
//FIXME load version from prod domain
-export async function getChatGPTManifestById(agentId: string, domain: string, version: string): Promise<ChatGPTManifest> {
- console.log('getChatGPTManifestById', agentId, domain, version);
- if (!agentId) {
- throw new Error('Agent not found');
- }
- const agentData = await getAgentDataById(agentId, version).catch((error) => {
- console.error(error);
- return { error };
- });
- if (agentData?.error) {
- throw new Error(agentData.error);
+export async function getChatGPTManifestById(
+ agentId: string,
+ domain: string,
+ version: string
+): Promise<ChatGPTManifest> {
+ console.log("getChatGPTManifestById", agentId, domain, version);
+ if (!agentId) {
+ throw new Error("Agent not found");
+ }
+ const agentData = await getAgentDataById(agentId, version).catch((error) => {
+ console.error(error);
+ return { error };
+ });
+ if (agentData?.error) {
+ throw new Error(agentData.error);
+ }
+
+ const embodiments = await getAgentEmbodiments(agentId);
+
+ // find chatgpt embodiment as we have multiple embodiments per agent
+ const chatgptEmbodiment = embodiments.find(
+ (embodiment: any) =>
+ embodiment.type?.toLowerCase() === EMBODIMENT_TYPES.ChatGPT.toLowerCase()
+ );
+
+ // Extract properties from the ChatGPT embodiment
+ const _chatgptDesctiption = chatgptEmbodiment?.properties?.modelDescription;
+ const _chatgptHumanName = chatgptEmbodiment?.properties?.humanName;
+ const _chatgptModelName = chatgptEmbodiment?.properties?.modelName;
+ const _chatgptHumanDescription =
+ chatgptEmbodiment?.properties?.humanDescription;
+ const _contactEmail = chatgptEmbodiment?.properties?.contactEmail;
+ const _legalInfoUrl = chatgptEmbodiment?.properties?.legalInfoUrl;
+
+ const name = _chatgptHumanName || agentData.name || "Smyth Agent";
+ const modelName =
+ _chatgptModelName || name.replace(/ /g, "_") || "Smyth Agent";
+
+ //data.description is deprecated, use data.shortDescription for human description and data.behavior for model description
+ const humanDescription = splitOnSeparator(
+ _chatgptHumanDescription ||
+ agentData.data.shortDescription ||
+ agentData.data.description ||
+ "",
+ 120,
+ "."
+ );
+ const description = splitOnSeparator(
+ _chatgptDesctiption ||
+ agentData.data.behavior ||
+ agentData.data.description ||
+ "",
+ 8000,
+ "."
+ );
+
+ const icon_url =
+ chatgptEmbodiment?.properties?.logoUrl ||
+ "https://proxy-02.api.smyth.ai/static/img/icon.svg";
+ const contact_email = _contactEmail || "";
+ const legal_info_url = _legalInfoUrl || "";
+
+ const aiPluginTemplate = fs.readFileSync(
+ path.resolve(__dirname, `${chatGPTDataPath}/ai-plugin.tpl.json`),
+ "utf8"
+ );
+
+ let manifest = TemplateStringHelper.create(aiPluginTemplate).parse({
+ human_name: name,
+ model_name: modelName,
+ human_description: humanDescription,
+ model_description: description,
+ icon_url,
+ contact_email,
+ legal_info_url,
+ domain,
+ }).result;
+ const parsedManifest = JSONContentHelper.create(manifest).tryParse();
+ manifest =
+ typeof parsedManifest === "string"
+ ? JSON.parse(parsedManifest)
+ : parsedManifest;
+
+ const auth = (manifest as any).auth;
+ const authMethod = agentData.data?.auth?.method;
+ const authProvider = agentData.data?.auth?.provider[authMethod];
+ if (authProvider) {
+ if (authMethod === "oauth-oidc") {
+ auth.type = "oauth";
+ auth.client_url = `https://${domain}/oauth/authorize`;
+ auth.scope = "offline_access openid profile email";
+ auth.authorization_url = `https://${domain}/oauth/token`;
+ auth.authorization_content_type = "application/json";
+ auth.verification_tokens = {
+ openai: authProvider?.OIDCOpenAIVerificationToken,
+ };
}
- const embodiments = await getAgentEmbodiments(agentId);
-
- // find chatgpt embodiment as we have multiple embodiments per agent
- const chatgptEmbodiment = embodiments.find((embodiment: any) => embodiment.type?.toLowerCase() === EMBODIMENT_TYPES.ChatGPT.toLowerCase());
-
- // Extract properties from the ChatGPT embodiment
- const _chatgptDesctiption = chatgptEmbodiment?.properties?.modelDescription;
- const _chatgptHumanName = chatgptEmbodiment?.properties?.humanName;
- const _chatgptModelName = chatgptEmbodiment?.properties?.modelName;
- const _chatgptHumanDescription = chatgptEmbodiment?.properties?.humanDescription;
- const _contactEmail = chatgptEmbodiment?.properties?.contactEmail;
- const _legalInfoUrl = chatgptEmbodiment?.properties?.legalInfoUrl;
-
- const name = _chatgptHumanName || agentData.name || 'Smyth Agent';
- const modelName = _chatgptModelName || name.replace(/ /g, '_') || 'Smyth Agent';
-
- //data.description is deprecated, use data.shortDescription for human description and data.behavior for model description
- const humanDescription = splitOnSeparator(
- _chatgptHumanDescription || agentData.data.shortDescription || agentData.data.description || '',
- 120,
- '.'
- );
- const description = splitOnSeparator(_chatgptDesctiption || agentData.data.behavior || agentData.data.description || '', 8000, '.');
-
- const icon_url = chatgptEmbodiment?.properties?.logoUrl || 'https://proxy-02.api.smyth.ai/static/img/icon.svg';
- const contact_email = _contactEmail || '';
- const legal_info_url = _legalInfoUrl || '';
-
- const aiPluginTemplate = fs.readFileSync(path.resolve(__dirname, `${chatGPTDataPath}/ai-plugin.tpl.json`), 'utf8');
-
- let manifest = TemplateStringHelper.create(aiPluginTemplate).parse({
- human_name: name,
- model_name: modelName,
- human_description: humanDescription,
- model_description: description,
- icon_url,
- contact_email,
- legal_info_url,
- domain,
- }).result;
- const parsedManifest = JSONContentHelper.create(manifest).tryParse();
- manifest = typeof parsedManifest === 'string' ? JSON.parse(parsedManifest) : parsedManifest;
-
- const auth = (manifest as any).auth;
- const authMethod = agentData.data?.auth?.method;
- const authProvider = agentData.data?.auth?.provider[authMethod];
- if (authProvider) {
- if (authMethod === 'oauth-oidc') {
- auth.type = 'oauth';
- auth.client_url = `https://${domain}/oauth/authorize`;
- auth.scope = 'offline_access openid profile email';
- auth.authorization_url = `https://${domain}/oauth/token`;
- auth.authorization_content_type = 'application/json';
- auth.verification_tokens = {
- openai: authProvider?.OIDCOpenAIVerificationToken,
- };
- }
-
- if (authMethod === 'api-key-bearer') {
- auth.type = 'service_http';
- auth.authorization_type = 'bearer';
- auth.verification_tokens = {
- openai: authProvider?.BearerOpenAIVerificationToken,
- };
- }
+ if (authMethod === "api-key-bearer") {
+ auth.type = "service_http";
+ auth.authorization_type = "bearer";
+ auth.verification_tokens = {
+ openai: authProvider?.BearerOpenAIVerificationToken,
+ };
}
+ }
- return manifest as unknown as ChatGPTManifest;
+ return manifest as unknown as ChatGPTManifest;
}
-export async function getChatGPTManifest(domain: string, version: string): Promise<ChatGPTManifest> {
- const agentId = await getAgentIdByDomain(domain);
- if (!agentId) {
- throw new Error('Agent not found');
- }
+export async function getChatGPTManifest(
+ domain: string,
+ version: string
+): Promise<ChatGPTManifest> {
+ const agentId = await getAgentIdByDomain(domain);
+ if (!agentId) {
+ throw new Error("Agent not found");
+ }
- return getChatGPTManifestById(agentId, domain, version);
+ return getChatGPTManifestById(agentId, domain, version);
}
diff --git a/packages/runtime/src/modules/embodiment/helpers/formPreview.helper.ts b/packages/runtime/src/modules/embodiment/helpers/formPreview.helper.ts
index 526d0b78..b24f885f 100644
--- a/packages/runtime/src/modules/embodiment/helpers/formPreview.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/formPreview.helper.ts
@@ -1,45 +1,50 @@
-import config from '@embodiment/config';
-import axios, { AxiosError } from 'axios';
+import axios, { AxiosError } from "axios";
+
+import config from "@core/config";
export type CallSkillParams = {
- agentId: string;
+ agentId: string;
};
export type CallSkillBody = {
- componentId: string;
- payload?: Record<string, any> | null | '';
- version?: 'dev' | 'latest';
+ componentId: string;
+ payload?: Record<string, any> | null | "";
+ version?: "dev" | "latest";
};
export type CallSkillType = {
- params: CallSkillParams;
- body: CallSkillBody;
- endpoint: string;
+ params: CallSkillParams;
+ body: CallSkillBody;
+ endpoint: string;
};
export async function callSkill({ params, body, endpoint }: CallSkillType) {
- const RUNTIME_AGENT_URL = config.env.BASE_URL;
-
- const request: {
- body: string | null;
- headers: { [key: string]: string };
- } = { body: null, headers: {} };
-
- request.body = JSON.stringify(body?.payload || {});
- request.headers = {
- 'Content-Type': 'application/json',
- 'X-DEBUG-SKIP': 'true',
- ...(body.version !== 'dev' && { 'X-AGENT-VERSION': body.version }), // if version is dev, don't send it
- 'X-AGENT-ID': params.agentId,
- };
-
- try {
- const res = await axios.post(`${RUNTIME_AGENT_URL}/api/${endpoint}`, request.body, {
- headers: request.headers,
- });
- return res.data;
- } catch (error) {
- const axiosErr = error as AxiosError;
- return axiosErr.response?.data || axiosErr.message;
- }
+ const RUNTIME_AGENT_URL = config.env.BASE_URL;
+
+ const request: {
+ body: string | null;
+ headers: { [key: string]: string };
+ } = { body: null, headers: {} };
+
+ request.body = JSON.stringify(body?.payload || {});
+ request.headers = {
+ "Content-Type": "application/json",
+ "X-DEBUG-SKIP": "true",
+ ...(body.version !== "dev" && { "X-AGENT-VERSION": body.version }), // if version is dev, don't send it
+ "X-AGENT-ID": params.agentId,
+ };
+
+ try {
+ const res = await axios.post(
+ `${RUNTIME_AGENT_URL}/api/${endpoint}`,
+ request.body,
+ {
+ headers: request.headers,
+ }
+ );
+ return res.data;
+ } catch (error) {
+ const axiosErr = error as AxiosError;
+ return axiosErr.response?.data || axiosErr.message;
+ }
}
diff --git a/packages/runtime/src/modules/embodiment/helpers/logto.helper.ts b/packages/runtime/src/modules/embodiment/helpers/logto.helper.ts
index 3fbf055e..2e6c9cce 100644
--- a/packages/runtime/src/modules/embodiment/helpers/logto.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/logto.helper.ts
@@ -1,68 +1,70 @@
-import axios from 'axios';
-import qs from 'querystring';
-import config from '../config';
+import axios from "axios";
+import qs from "querystring";
+
+import config from "@core/config";
+
//M2M test
const postData = {
- grant_type: 'client_credentials',
- resource: 'https://default.logto.app/api',
- scope: 'all',
+ grant_type: "client_credentials",
+ resource: "https://default.logto.app/api",
+ scope: "all",
};
-const base64Credentials = Buffer.from(`${config.env.LOGTO_M2M_APP_ID}:${config.env.LOGTO_M2M_APP_SECRET}`, 'utf8').toString('base64');
+const base64Credentials = Buffer.from(
+ `${config.env.LOGTO_M2M_APP_ID}:${config.env.LOGTO_M2M_APP_SECRET}`,
+ "utf8"
+).toString("base64");
let tokenData = {
- access_token: null,
+ access_token: null,
};
export function getM2MToken(resource?, scope?) {
- return new Promise((resolve, reject) => {
- if (tokenData.access_token) {
- return resolve(tokenData.access_token);
- }
+ return new Promise((resolve, reject) => {
+ if (tokenData.access_token) {
+ return resolve(tokenData.access_token);
+ }
- const body = {
- grant_type: 'client_credentials',
- resource: resource || config.env.LOGTO_API_RESOURCE,
- scope: scope || '',
- };
- axios({
- method: 'post',
- url: `${config.env.LOGTO_SERVER}/oidc/token`,
- headers: {
- Authorization: 'Basic ' + base64Credentials,
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- data: qs.stringify(body),
- })
- .then((response) => {
- tokenData.access_token = response.data.access_token;
- setTimeout(
- () => {
- tokenData.access_token = null;
- },
- (response.data.expires_in - 100) * 1000,
- );
- resolve(tokenData.access_token);
- })
- .catch((error) => {
- reject({ error: error.response.data });
- });
- });
+ const body = {
+ grant_type: "client_credentials",
+ resource: resource || config.env.LOGTO_API_RESOURCE,
+ scope: scope || "",
+ };
+ axios({
+ method: "post",
+ url: `${config.env.LOGTO_SERVER}/oidc/token`,
+ headers: {
+ Authorization: "Basic " + base64Credentials,
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ data: qs.stringify(body),
+ })
+ .then((response) => {
+ tokenData.access_token = response.data.access_token;
+ setTimeout(() => {
+ tokenData.access_token = null;
+ }, (response.data.expires_in - 100) * 1000);
+ resolve(tokenData.access_token);
+ })
+ .catch((error) => {
+ reject({ error: error.response.data });
+ });
+ });
}
export async function getUserInfo(userId: string) {
- const token = await getM2MToken('https://default.logto.app/api', 'all');
+ const token = await getM2MToken("https://default.logto.app/api", "all");
- const response: any = await axios({
- method: 'get',
- url: `${config.env.LOGTO_SERVER}/api/users/${userId}`,
- headers: {
- Authorization: `Bearer ${token}`,
- },
- }).catch((error) => ({ error }));
+ const response: any = await axios({
+ method: "get",
+ url: `${config.env.LOGTO_SERVER}/api/users/${userId}`,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ }).catch((error) => ({ error }));
- if (response.error) {
- return null;
- }
+ if (response.error) {
+ return null;
+ }
- return response.data;
+ return response.data;
}
diff --git a/packages/runtime/src/modules/embodiment/helpers/openapi-adapter.helper.ts b/packages/runtime/src/modules/embodiment/helpers/openapi-adapter.helper.ts
index fc76084f..b9905f20 100644
--- a/packages/runtime/src/modules/embodiment/helpers/openapi-adapter.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/openapi-adapter.helper.ts
@@ -1,14 +1,13 @@
-import { AgentDataConnector } from "@smythos/sre";
+import config from "@/core/config";
import {
- getAgentIdByDomain,
+ addDefaultComponentsAndConnections,
getAgentDataById,
-} from "@embodiment/helpers/agent.helper";
-import { addDefaultComponentsAndConnections } from "@core/services/agent-helper";
-import config from "@embodiment/config";
-import { Logger } from "@smythos/sre";
-import type { AgentData, OpenAPISpec } from "@embodiment/types/openapi.types";
+ getAgentIdByDomain,
+} from "@core/helpers/agent.helper";
+import type { AgentData, OpenAPISpec } from "@core/types/openapi.types";
+import { AgentDataConnector, Logger } from "@smythos/sre";
-const console = Logger("[Embodiment] Helper: OpenAPI Adapter");
+const console = Logger("openapi-adapter.helper.ts");
/**
* AgentDataConnector implementation for sre-embodiment-server
@@ -201,6 +200,6 @@ export async function getOpenAPIJSONForAI(
// Export utility functions for backward compatibility
export {
- getAgentIdByDomain,
getAgentDataById,
-} from "@embodiment/helpers/agent.helper";
+ getAgentIdByDomain,
+} from "@core/helpers/agent.helper";
diff --git a/packages/runtime/src/modules/embodiment/helpers/openapi.helper.ts b/packages/runtime/src/modules/embodiment/helpers/openapi.helper.ts
deleted file mode 100644
index ee37298c..00000000
--- a/packages/runtime/src/modules/embodiment/helpers/openapi.helper.ts
+++ /dev/null
@@ -1,472 +0,0 @@
-/**
- * @fileoverview DEPRECATED - This file is deprecated and will be removed in a future version.
- * Use @/helpers/openapi-adapter.helper.ts instead, which integrates with the SRE core AgentDataConnector.
- *
- * Migration complete: All imports have been updated to use the new adapter.
- * The new implementation provides:
- * - Better error handling with JSONContent.tryParse()
- * - Integration with SRE core AgentDataConnector
- * - Identical OpenAPI JSON output
- * - More robust template processing
- */
-
-import fs from "fs";
-import url from "url";
-import path from "path";
-import { Logger } from "@smythos/sre";
-import { parseTemplate } from "@core/utils/general.utils";
-import {
- getAgentIdByDomain,
- getAgentDataById,
-} from "@embodiment/helpers/agent.helper";
-import config from "@embodiment/config";
-import { addDefaultComponentsAndConnections } from "@core/services/agent-helper";
-
-const console = Logger("[Embodiment] Helper: OpenAPI");
-
-const __filename = url.fileURLToPath(import.meta.url);
-const __dirname = path.dirname(__filename);
-
-let chatGPTDataPath = "./data/chatGPT";
-
-// Path to data files differs between server ('./data/chatGPT') and tests ('../data/chatGPT').
-if (process.env.TEST_ENV) {
- chatGPTDataPath = "../data/chatGPT";
-}
-
-// const aiPluginTemplate = fs.readFileSync(path.resolve(__dirname, `${chatGPTDataPath}/ai-plugin.tpl.json`), 'utf8');
-
-export function getOpenAPIInputType(input_type) {
- switch (input_type.toLowerCase()) {
- case "binary":
- case "string":
- case "any":
- case "date":
- case "datetime":
- return "string";
- case "number":
- case "float":
- return "number";
- case "integer":
- return "integer";
- case "boolean":
- return "boolean";
- case "array":
- return "array";
- case "object":
- return "object";
- default:
- return "string";
- }
-}
-
-export function getOpenAPIParameterStyle(input_type) {
- switch (input_type.toLowerCase()) {
- case "array":
- return {
- style: "form",
- explode: false, // results in `ids=1,2,3`
- };
- case "object":
- return {
- style: "deepObject",
- explode: true, // results in `lat=value1&long=value2`
- };
- default:
- return { style: "", explode: false };
- }
-}
-
-export function getOpenAPIInputSchema(input_type) {
- switch (input_type?.toLowerCase()) {
- case "binary":
- case "string":
- case "any":
- return { type: "string" };
- case "number":
- case "float":
- return { type: "number" };
- case "integer":
- return { type: "integer" };
- case "boolean":
- return { type: "boolean" };
- case "array":
- return { type: "array", items: {} };
- case "object":
- return { type: "object", additionalProperties: {} };
- default:
- return { type: "string" };
- }
-}
-
-/**
- * @deprecated Use getOpenAPIJSON from @/helpers/openapi-adapter.helper instead.
- * This function will be removed in a future version.
- */
-export async function getOpenAPIJSON(
- agent: any,
- domain: string,
- version: string,
- aiOnly: boolean = false
-) {
- console.warn(
- "DEPRECATED: getOpenAPIJSON from openapi.helper.ts is deprecated. Use openapi-adapter.helper.ts instead."
- );
- const apiBasePath =
- version && version != "latest" ? `/v${version}/api` : "/api";
- const name = agent.name;
-
- let description = aiOnly ? agent.data.behavior : agent.data.shortDescription;
- if (!description) description = agent.data.description; //data.description is deprecated, we just use it as a fallback for now
-
- const _version = agent.data.version || "1.0.0";
- //replace all non printable characters with spaces
- //description = description.replace(/[^\x20-\x7E]+/g, ' ');
- //const version = '1.0.0';
-
- const server_url_scheme =
- config.env.NODE_ENV === "DEV" &&
- config.env.AGENT_DOMAIN_PORT &&
- domain.includes(config.env.AGENT_DOMAIN)
- ? "http"
- : "https";
- const server_url_port =
- config.env.NODE_ENV === "DEV" &&
- config.env.AGENT_DOMAIN_PORT &&
- domain.includes(config.env.AGENT_DOMAIN)
- ? `:${config.env.AGENT_DOMAIN_PORT}`
- : "";
- const server_url = `${server_url_scheme}://${domain}${server_url_port}`;
- const openapiTemplate = fs.readFileSync(
- path.resolve(__dirname, `${chatGPTDataPath}/openapi.tpl.json`),
- "utf8"
- );
- const openAPIObj = JSON.parse(
- parseTemplate(openapiTemplate, {
- model_name: name,
- model_description: description,
- server_url,
- version: _version,
- })
- );
-
- const components = agent.data.components.filter(
- (component: any) => component.name === "APIEndpoint"
- );
- for (let component of components) {
- const ai_exposed =
- component.data.ai_exposed ||
- typeof component.data.ai_exposed === "undefined";
- if (aiOnly && !ai_exposed) continue;
- let method = (component.data.method || "post").toLowerCase();
- let summary = aiOnly
- ? component.data.description || component.data.doc
- : component.data.doc || component.data.description;
- const openapiEndpointTemplate = fs.readFileSync(
- path.resolve(__dirname, `${chatGPTDataPath}/openapi-endpoint.tpl.json`),
- "utf8"
- );
-
- const openAPIEntry = JSON.parse(
- parseTemplate(openapiEndpointTemplate, {
- summary,
- operationId: component.data.endpoint,
- })
- );
- if (!openAPIObj.paths[apiBasePath + "/" + component.data.endpoint])
- openAPIObj.paths[apiBasePath + "/" + component.data.endpoint] = {};
- //const componentsSchemas = openAPIObj.components.schemas;
-
- openAPIObj.paths[apiBasePath + "/" + component.data.endpoint][method] =
- openAPIEntry;
-
- if (component.inputs.length > 0) {
- if (method === "get") {
- delete openAPIEntry.requestBody;
-
- openAPIEntry.parameters = [];
-
- for (let input of component.inputs) {
- const parameter: {
- name: string;
- in: string;
- description: string;
- required: boolean;
- schema: { type: string };
- style?: string;
- explode?: boolean;
- } = {
- name: input.name,
- in: "query",
- description: input.description,
- required: !input.optional,
- schema: getOpenAPIInputSchema(input.type),
- };
-
- // for array and object types
- const { style, explode } = getOpenAPIParameterStyle(input.type);
- if (style) {
- parameter.style = style;
- parameter.explode = explode;
- }
-
- openAPIEntry.parameters.push(parameter);
- }
- } else {
- const requiredProps: any = [];
-
- const hasBinaryType =
- !aiOnly &&
- component.inputs.some(
- (input) => input.type.toLowerCase().trim() === "binary"
- );
- //if it's an AI format, we force application/json format, becauwe we want to receive binary data as a url
- const mimetype = hasBinaryType
- ? "multipart/form-data"
- : "application/json";
- openAPIEntry.requestBody.content[mimetype] = {};
- for (let input of component.inputs) {
- if (!input.optional) requiredProps.push(input.name);
-
- if (!openAPIEntry.requestBody.content[mimetype].schema)
- openAPIEntry.requestBody.content[mimetype].schema = {
- type: "object",
- };
-
- const schema: any = openAPIEntry.requestBody.content[mimetype]
- .schema || {
- type: "object",
- };
-
- if (!schema.properties) schema.properties = {};
- schema.properties[input.name] = {
- ...getOpenAPIInputSchema(input.type),
- format:
- !aiOnly && input.type.toLowerCase().trim() === "binary"
- ? "binary"
- : undefined,
- description: input.description,
- default: input.defaultVal, // without explicit default value; models from 'Anthropic' (Claude) trying to guess and supply dummy data.
- };
- schema.required = requiredProps;
-
- if (!openAPIEntry.requestBody.content[mimetype].schema)
- openAPIEntry.requestBody.content["application/json"].schema =
- schema;
- }
- }
- } else {
- delete openAPIEntry.requestBody;
- }
- }
-
- return openAPIObj;
-}
-
-/**
- * @deprecated Use getOpenAPIJSONById from @/helpers/openapi-adapter.helper instead.
- * This function will be removed in a future version.
- */
-export async function getOpenAPIJSONById(
- agentId,
- domain,
- version,
- aiOnly: boolean = false,
- addDefaultFileParsingAgent: boolean = false
-) {
- console.warn(
- "DEPRECATED: getOpenAPIJSONById from openapi.helper.ts is deprecated. Use openapi-adapter.helper.ts instead."
- );
- if (!agentId) {
- throw new Error("Agent not found");
- }
- const apiBasePath =
- version && version != "latest" ? `/v${version}/api` : "/api";
- //@Ahmed : this should use SRE AgentDataConnector to get the agent data,
- const agentData = await getAgentDataById(agentId, version).catch((error) => {
- console.error(error);
- return { error };
- });
- if (agentData?.error) {
- throw new Error(agentData.error);
- }
- const name = agentData.name;
-
- let description = aiOnly
- ? agentData.data.behavior
- : agentData.data.shortDescription;
- if (!description) description = agentData.data.description; //data.description is deprecated, we just use it as a fallback for now
-
- const _version = agentData.data.version || "1.0.0";
- //replace all non printable characters with spaces
- //description = description.replace(/[^\x20-\x7E]+/g, ' ');
- //const version = '1.0.0';
-
- const server_url_scheme =
- config.env.NODE_ENV === "DEV" &&
- config.env.AGENT_DOMAIN_PORT &&
- domain.includes(config.env.AGENT_DOMAIN)
- ? "http"
- : "https";
- const server_url_port =
- config.env.NODE_ENV === "DEV" &&
- config.env.AGENT_DOMAIN_PORT &&
- domain.includes(config.env.AGENT_DOMAIN)
- ? `:${config.env.AGENT_DOMAIN_PORT}`
- : "";
- const server_url = `${server_url_scheme}://${domain}${server_url_port}`;
- const openapiTemplate = fs.readFileSync(
- path.resolve(__dirname, `${chatGPTDataPath}/openapi.tpl.json`),
- "utf8"
- );
- const openAPIObj = JSON.parse(
- parseTemplate(openapiTemplate, {
- model_name: name,
- model_description: description,
- server_url,
- version: _version,
- })
- );
-
- if (addDefaultFileParsingAgent) {
- addDefaultComponentsAndConnections(agentData);
- }
-
- const components = agentData.data.components.filter(
- (component: any) => component.name === "APIEndpoint"
- );
- for (let component of components) {
- const ai_exposed =
- component.data.ai_exposed ||
- typeof component.data.ai_exposed === "undefined";
- if (aiOnly && !ai_exposed) continue;
- let method = (component.data.method || "post").toLowerCase();
- let summary = aiOnly
- ? component.data.description || component.data.doc
- : component.data.doc || component.data.description;
- const openapiEndpointTemplate = fs.readFileSync(
- path.resolve(__dirname, `${chatGPTDataPath}/openapi-endpoint.tpl.json`),
- "utf8"
- );
-
- const openAPIEntry = JSON.parse(
- parseTemplate(openapiEndpointTemplate, {
- summary,
- operationId: component.data.endpoint,
- })
- );
- if (!openAPIObj.paths[apiBasePath + "/" + component.data.endpoint])
- openAPIObj.paths[apiBasePath + "/" + component.data.endpoint] = {};
- //const componentsSchemas = openAPIObj.components.schemas;
-
- openAPIObj.paths[apiBasePath + "/" + component.data.endpoint][method] =
- openAPIEntry;
-
- if (component.inputs.length > 0) {
- if (method === "get") {
- delete openAPIEntry.requestBody;
-
- openAPIEntry.parameters = [];
-
- for (let input of component.inputs) {
- const parameter: {
- name: string;
- in: string;
- description: string;
- required: boolean;
- schema: { type: string };
- style?: string;
- explode?: boolean;
- } = {
- name: input.name,
- in: "query",
- description: input.description,
- required: !input.optional,
- schema: getOpenAPIInputSchema(input.type),
- };
-
- // for array and object types
- const { style, explode } = getOpenAPIParameterStyle(input.type);
- if (style) {
- parameter.style = style;
- parameter.explode = explode;
- }
-
- openAPIEntry.parameters.push(parameter);
- }
- } else {
- const requiredProps: any = [];
-
- const hasBinaryType =
- !aiOnly &&
- component.inputs.some(
- (input) => input.type.toLowerCase().trim() === "binary"
- );
- //if it's an AI format, we force application/json format, becauwe we want to receive binary data as a url
- const mimetype = hasBinaryType
- ? "multipart/form-data"
- : "application/json";
- openAPIEntry.requestBody.content[mimetype] = {};
- for (let input of component.inputs) {
- if (!input.optional) requiredProps.push(input.name);
-
- if (!openAPIEntry.requestBody.content[mimetype].schema)
- openAPIEntry.requestBody.content[mimetype].schema = {
- type: "object",
- };
-
- const schema: any = openAPIEntry.requestBody.content[mimetype]
- .schema || {
- type: "object",
- };
-
- if (!schema.properties) schema.properties = {};
- schema.properties[input.name] = {
- ...getOpenAPIInputSchema(input.type),
- format:
- !aiOnly && input.type.toLowerCase().trim() === "binary"
- ? "binary"
- : undefined,
- description: input.description,
- default: input.defaultVal, // without explicit default value; models from 'Anthropic' (Claude) trying to guess and supply dummy data.
- };
- schema.required = requiredProps;
-
- if (!openAPIEntry.requestBody.content[mimetype].schema)
- openAPIEntry.requestBody.content["application/json"].schema =
- schema;
- }
- }
- } else {
- delete openAPIEntry.requestBody;
- }
- }
-
- return openAPIObj;
-}
-
-/**
- * @deprecated Use getOpenAPIJSONForAI from @/helpers/openapi-adapter.helper instead.
- * This function will be removed in a future version.
- */
-export async function getOpenAPIJSONForAI(
- domain,
- version: string,
- addDefaultFileParsingAgent: boolean = false
-) {
- console.warn(
- "DEPRECATED: getOpenAPIJSONForAI from openapi.helper.ts is deprecated. Use openapi-adapter.helper.ts instead."
- );
- const agentId = await getAgentIdByDomain(domain);
- if (!agentId) {
- throw new Error("Agent not found");
- }
-
- return getOpenAPIJSONById(
- agentId,
- domain,
- version,
- true,
- addDefaultFileParsingAgent
- );
-}
diff --git a/packages/runtime/src/modules/embodiment/middlewares/ChatbotLoader.mw.ts b/packages/runtime/src/modules/embodiment/middlewares/ChatbotLoader.mw.ts
new file mode 100644
index 00000000..372f8ba6
--- /dev/null
+++ b/packages/runtime/src/modules/embodiment/middlewares/ChatbotLoader.mw.ts
@@ -0,0 +1,38 @@
+import { Agent } from "@smythos/sre";
+import Chatbot from "../services/Chatbot.class";
+import ApiError from "../utils/apiError";
+//TODO : handle cache TTL
+
+const __chatbot_cache = { 0: 1 };
+export default async function ChatbotLoader(req, res, next) {
+ console.log("ChatbotLoader");
+ const agent: Agent = req._agent;
+ if (!agent) return next();
+ try {
+ if (__chatbot_cache[agent.id] && !agent.usingTestDomain) {
+ const chatBotData = __chatbot_cache[agent.id];
+ if (chatBotData.agentVersion == agent.version) {
+ console.log(
+ `Chatbot loaded from cache, domain=${chatBotData.domain} version=${chatBotData.version}`
+ );
+ const chatbot = new Chatbot(req);
+ chatbot.deserialize(chatBotData);
+ req._chatbot = chatbot;
+ }
+ }
+ if (!req._chatbot) {
+ const chatbot = new Chatbot(req);
+ req._chatbot = chatbot;
+
+ await req._chatbot.init();
+ __chatbot_cache[agent.id] = chatbot.serialize(); //we cannot store an object in session, so we serialize it
+ }
+ } catch (error) {
+ if (error.errKey == "MODEL_NOT_SUPPORTED") {
+ console.warn(error.message);
+ return next(new ApiError(400, error.message, error.errKey));
+ }
+ }
+
+ next();
+}
diff --git a/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts b/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
index 8e44f0e5..eb0ad53d 100644
--- a/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
+++ b/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
@@ -1,21 +1,18 @@
+import config from "@core/config";
import {
extractAgentVerionsAndPath,
getAgentDomainById,
getAgentIdAndVersion,
} from "../helpers/agent.helper";
-import config from "../config";
+import { addDefaultComponentsAndConnections } from "@/core/helpers/agent.helper";
import {
- ConnectorService,
- Logger,
Agent,
- AgentSettings,
AgentRequest,
+ AgentSettings,
+ ConnectorService,
+ Logger,
} from "@smythos/sre";
-import { addDefaultComponentsAndConnections } from "@core/services/agent-helper";
-
-import { refreshBillingCache } from "../services/billing-service";
-import { requestContext } from "../services/request-context";
const console = Logger("[Embodiment] Middleware: Agent Loader");
@@ -51,15 +48,17 @@ export default async function agentLoader(req, res, next) {
try {
const result = agentDataConnector?.getAgentIdByDomain?.(domain);
- if (result && typeof result.catch === 'function') {
+ if (result && typeof result.catch === "function") {
agentId = await result.catch((error) => {
console.error(error);
});
} else {
- console.error('getAgentIdByDomain method is not available or does not return a promise');
+ console.error(
+ "getAgentIdByDomain method is not available or does not return a promise"
+ );
}
} catch (error) {
- console.error('Error calling getAgentIdByDomain:', error);
+ console.error("Error calling getAgentIdByDomain:", error);
}
agentDomain = domain;
if (agentId && domain.includes(config.env.AGENT_DOMAIN)) {
@@ -80,17 +79,19 @@ export default async function agentLoader(req, res, next) {
let agentData;
try {
const result = agentDataConnector?.getAgentData?.(agentId, version);
- if (result && typeof result.catch === 'function') {
+ if (result && typeof result.catch === "function") {
agentData = await result.catch((error) => {
console.error(error);
return { error: error.message };
});
} else {
- console.error('getAgentData method is not available or does not return a promise');
- agentData = { error: 'getAgentData method is not available' };
+ console.error(
+ "getAgentData method is not available or does not return a promise"
+ );
+ agentData = { error: "getAgentData method is not available" };
}
} catch (error) {
- console.error('Error calling getAgentData:', error);
+ console.error("Error calling getAgentData:", error);
agentData = { error: error.message };
}
@@ -122,17 +123,6 @@ export default async function agentLoader(req, res, next) {
maxLatency: 100,
};
- const parentTeamId = agentData.data?.parentTeamId;
- const teamId = agentData.data?.teamId;
-
- // Store team info in request context (for use by hook services like Conversation.prompt)
- // TODO: This is a temporary workaround to provide team information to the hook services. The ideal solution is to pass all necessary data through the hook service arguments.
- requestContext.set(`team_info:${agentId}`, {
- planInfo: req._plan,
- parentTeamId,
- teamId,
- });
-
req.socket.on("close", () => {
// console.log('Client socket closed, killing agent');
// Handle the cancellation logic
@@ -158,11 +148,6 @@ export default async function agentLoader(req, res, next) {
req._agentVersion = version;
//req._data1 = 1;
- // Pre-fetch billing data to ensure cached data is readily available for usage limit validation
- // To avoid an additional network call in this middleware, we pass teamId to refreshBillingCache
- // The parentTeamId is then derived from the teamId within refreshBillingCache.
- refreshBillingCache(parentTeamId, teamId);
-
console.log(
`Loaded Agent:${agentId} v=${version} path=${path} isTestDomain=${isTestDomain} domain=${agentDomain}`
);
diff --git a/packages/runtime/src/modules/embodiment/modules/API/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/API/routes/router.ts
index bef94119..61b07608 100644
--- a/packages/runtime/src/modules/embodiment/modules/API/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/API/routes/router.ts
@@ -1,6 +1,7 @@
-import express from "express";
-import { getOpenAPIJSON } from "../../../helpers/openapi-adapter.helper";
import { Agent } from "@smythos/sre";
+import express from "express";
+
+import { getOpenAPIJSON } from "@embodiment/helpers/openapi-adapter.helper";
import agentLoader from "@embodiment/middlewares/agentLoader.mw";
const router = express.Router();
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 8ddb3e37..7ee4f149 100644
--- a/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts
@@ -1,17 +1,17 @@
import express from "express";
+import Joi from "joi";
import config from "@core/config";
import { getM2MToken } from "@core/helpers/logto.helper";
-import agentLoader from "@core/middlewares/agentLoader.mw";
-import ChatbotLoader from "@core/middlewares/ChatbotLoader.mw";
-import cors from "@embodiment/middlewares/cors.mw";
import UserAgentAccessCheck from "@core/middlewares/userAgentAccessCheck.mw";
import { validate } from "@core/middlewares/validate.mw";
-import Chatbot from "@embodiment/modules/chatbot/services/Chatbot.class";
import { requestContext } from "@core/services/request-context";
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/modules/chatbot/services/Chatbot.class";
import { buildConversationId } from "@embodiment/utils/chat.utils";
-import Joi from "joi";
// Import ChatbotResponse type for proper typing
type ChatbotResponse = {
@@ -29,7 +29,7 @@ type ChatbotResponse = {
const router = express.Router();
-const middlewares = [UserAgentAccessCheck, agentLoader, ChatbotLoader, cors];
+const middlewares = [UserAgentAccessCheck, agentLoader, ChatbotLoader];
router.use(middlewares);
let localAgentAuthorizations = {
diff --git a/packages/runtime/src/modules/embodiment/modules/agentChat/services/SmythChatStorage.class.ts b/packages/runtime/src/modules/embodiment/modules/agentChat/services/SmythChatStorage.class.ts
deleted file mode 100644
index e607fc05..00000000
--- a/packages/runtime/src/modules/embodiment/modules/agentChat/services/SmythChatStorage.class.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-import { Readable } from 'stream';
-import { HeadObjectCommand, PutObjectCommandInput } from '@aws-sdk/client-s3';
-
-import config from '@embodiment/config';
-import { Metadata } from '../../../types';
-import S3Storage from '../S3Storage.class';
-import { stream2buffer } from '../../utils';
-
-type Metadata = {
- [key: string]: string;
-};
-
-type AclRules = Metadata;
-
-// TODO: This file has code redundancy with SmythStorage.class.ts
-// It was needed at the time of implementation
-// Refactor to remove redundancy
-
-export class SmythChatStorage extends S3Storage {
- teamId: string = '';
- userId: string = '';
- agentId: string = '';
- conversationId: string = '';
-
- constructor() {
- super(config.env.AWS_S3_BUCKET_NAME || '');
- }
-
- setParams({ teamId, userId, agentId, conversationId }: { teamId: string; userId: string; agentId: string; conversationId: string }) {
- this.teamId = teamId;
- this.userId = userId;
- this.agentId = agentId;
- this.conversationId = conversationId;
-
- if (!this.teamId || !this.userId || !this.agentId || !this.conversationId) {
- throw new Error('teamId, userId, agentId and conversationId are required');
- }
- }
-
- private getPrefixedKey(key: string): string {
- const preFixed = `teams/${this.teamId}/conv/${this.conversationId}/${key}`;
- console.log('prefixed', preFixed);
- return preFixed;
- }
-
- private async hasAccess(key: string, aclRules: AclRules): Promise<boolean> {
- const metadata = await super.getMetadata(key);
-
- if (!metadata?.teamid || !metadata?.userid) return false;
- return metadata?.teamid === aclRules?.teamid && metadata?.userid === aclRules?.userid;
- }
-
- public async exists(key: string): Promise<boolean> {
- try {
- await this.client.send(
- new HeadObjectCommand({
- Bucket: this.bucket,
- Key: this.getPrefixedKey(key),
- })
- );
- return true; // If the command succeeds, the file exists
- } catch (error: any) {
- if (error.name === 'NotFound' || error.$metadata.httpStatusCode === 404) {
- return false; // The file does not exist
- }
- // Log and rethrow any other error to handle it upstream
- console.log(`Error checking existence of object with key ${key}: `, error);
- throw error;
- }
- }
-
- public async saveContent({
- name,
- body,
- metadata,
- contentType,
- }: {
- body: any;
- name: string;
- contentType?: string;
- metadata: Metadata & Record<string, string>;
- }): Promise<any> {
- if (!metadata || !metadata?.teamid || !metadata?.userid) {
- throw new Error('Metadata is required with `teamid` and `userid`');
- }
-
- const otherParams: Partial<PutObjectCommandInput> = {
- Metadata: metadata,
- };
-
- if (contentType) otherParams.ContentType = contentType;
- return await super.putObject(name, body, otherParams);
- }
-
- public async getContent(
- key: string,
- aclRules: AclRules
- ): Promise<{ data: Buffer | Readable | undefined; lastModified: Date | undefined; contentType: string | undefined }> {
- if (aclRules && Object.keys(aclRules)) {
- if (!aclRules?.teamid || !aclRules?.userid) {
- throw new Error('ACL Rules is required with `teamid` and `userid`');
- }
-
- if (!(await this.hasAccess(key, aclRules))) {
- throw new Error('Access denied');
- }
- }
-
- const response = await super.getObject(key);
- const body = response?.Body;
-
- if (body && body instanceof Readable) {
- return {
- data: await stream2buffer(body),
- lastModified: response?.LastModified,
- contentType: response?.ContentType,
- };
- }
-
- throw new Error('getContent: Invalid response from file storage. response type:' + typeof body);
- }
-
- public async read(filename: string) {
- const content = await this.getContent(this.getPrefixedKey(filename), {
- teamid: this.teamId,
- agentid: this.agentId,
- userid: this.userId,
- }).catch((error) => {
- console.error('Error reading file:', error);
- return null;
- });
- return content?.data?.toString() || null;
- }
-
- public async write(filename: string, data: string, metadata: Record<any, any> = {}) {
- return this.saveContent({
- body: data,
- name: this.getPrefixedKey(filename),
- metadata: { teamid: this.teamId, agentid: this.agentId, userid: this.userId, ...metadata },
- }).catch((error) => {
- console.error('Error writing file:', error);
- return null;
- });
- }
-
- public async delete(filename: string) {
- return super.deleteObject(filename);
- }
-}
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 9b8d3690..20c12a53 100644
--- a/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts
@@ -1,16 +1,19 @@
+import { Agent } from "@smythos/sre";
import express from "express";
+
+import {
+ DEFAULT_AGENT_MODEL,
+ DEFAULT_AGENT_MODEL_SETTINGS_KEY,
+} from "@core/constants";
+
import agentLoader from "@embodiment/middlewares/agentLoader.mw";
-import { Agent } from "@smythos/sre";
+
import {
createAlexaSkill,
handleAlexaRequest,
isAlexaEnabled,
+ parseAlexaRequest,
} from "../services/alexa.service";
-import { parseAlexaRequest } from "../services/alexa.service";
-import {
- DEFAULT_AGENT_MODEL,
- DEFAULT_AGENT_MODEL_SETTINGS_KEY,
-} from "@embodiment/constants";
const router = express.Router();
router.post("/", agentLoader, async (req: any, res) => {
diff --git a/packages/runtime/src/modules/embodiment/modules/alexa/services/alexa.service.ts b/packages/runtime/src/modules/embodiment/modules/alexa/services/alexa.service.ts
index f4c350cc..c9ec3961 100644
--- a/packages/runtime/src/modules/embodiment/modules/alexa/services/alexa.service.ts
+++ b/packages/runtime/src/modules/embodiment/modules/alexa/services/alexa.service.ts
@@ -1,226 +1,257 @@
-import { Agent } from 'smyth-runtime';
-import axios from 'axios';
-import { Conversation } from 'smyth-runtime';
-import { getOpenAPIJSONForAI } from '@embodiment/helpers/openapi-adapter.helper';
-import { adaptModel } from '@core/utils/llm.utils';
-const SPEAKABLE_FORMAT_PROMPT = 'Return the response in speakable format';
-const ALEXA_BASE_URL = 'https://api.amazonalexa.com';
-const ALEXA_SETTINGS_KEY = 'alexa';
+import { adaptModel } from "@core/utils/llm.utils";
+import { getOpenAPIJSONForAI } from "@embodiment/helpers/openapi-adapter.helper";
+import { Agent, Conversation } from "@smythos/sre";
+import axios from "axios";
+const SPEAKABLE_FORMAT_PROMPT = "Return the response in speakable format";
+const ALEXA_BASE_URL = "https://api.amazonalexa.com";
+const ALEXA_SETTINGS_KEY = "alexa";
-export async function handleAlexaRequest(agent: Agent, alexRequest: any, model: string, isEnabled: boolean) {
- if (!isEnabled) {
- return buildAlexaResponse('Alexa is not enabled for this agent');
- }
- if (alexRequest.type === 'LaunchRequest') {
- return buildAlexaResponse('Hi I am smythos agent. What can I help you with?');
- }
- const searchQuery = alexRequest.slots.searchQuery.heardAs;
- const agentResponse = await processAlexaSearchQuery(searchQuery, model, agent);
- const response = buildAlexaResponse(agentResponse);
- return response;
+export async function handleAlexaRequest(
+ agent: Agent,
+ alexRequest: any,
+ model: string,
+ isEnabled: boolean
+) {
+ if (!isEnabled) {
+ return buildAlexaResponse("Alexa is not enabled for this agent");
+ }
+ if (alexRequest.type === "LaunchRequest") {
+ return buildAlexaResponse(
+ "Hi I am smythos agent. What can I help you with?"
+ );
+ }
+ const searchQuery = alexRequest.slots.searchQuery.heardAs;
+ const agentResponse = await processAlexaSearchQuery(
+ searchQuery,
+ model,
+ agent
+ );
+ const response = buildAlexaResponse(agentResponse);
+ return response;
}
export function parseAlexaRequest(alexRequest: any) {
- const type = alexRequest.request.type;
- const intent = alexRequest.request.intent;
- const slots = intent?.slots ? getSlotValues(intent.slots) : {};
- return { type, intent, slots };
+ const type = alexRequest.request.type;
+ const intent = alexRequest.request.intent;
+ const slots = intent?.slots ? getSlotValues(intent.slots) : {};
+ return { type, intent, slots };
}
export function getSlotValues(filledSlots) {
- const slotValues = {};
+ const slotValues = {};
- Object.keys(filledSlots).forEach((item) => {
- const name = filledSlots[item].name;
+ Object.keys(filledSlots).forEach((item) => {
+ const name = filledSlots[item].name;
- if (
- filledSlots[item] &&
- filledSlots[item].resolutions &&
- filledSlots[item].resolutions.resolutionsPerAuthority[0] &&
- filledSlots[item].resolutions.resolutionsPerAuthority[0].status &&
- filledSlots[item].resolutions.resolutionsPerAuthority[0].status.code
- ) {
- switch (filledSlots[item].resolutions.resolutionsPerAuthority[0].status.code) {
- case 'ER_SUCCESS_MATCH':
- slotValues[name] = {
- heardAs: filledSlots[item].value,
- resolved: filledSlots[item].resolutions.resolutionsPerAuthority[0].values[0].value.name,
- ERstatus: 'ER_SUCCESS_MATCH',
- };
- break;
- case 'ER_SUCCESS_NO_MATCH':
- slotValues[name] = {
- heardAs: filledSlots[item].value,
- resolved: '',
- ERstatus: 'ER_SUCCESS_NO_MATCH',
- };
- break;
- default:
- break;
- }
- } else {
- slotValues[name] = {
- heardAs: filledSlots[item].value || '', // may be null
- resolved: '',
- ERstatus: '',
- };
- }
- }, this);
+ if (
+ filledSlots[item] &&
+ filledSlots[item].resolutions &&
+ filledSlots[item].resolutions.resolutionsPerAuthority[0] &&
+ filledSlots[item].resolutions.resolutionsPerAuthority[0].status &&
+ filledSlots[item].resolutions.resolutionsPerAuthority[0].status.code
+ ) {
+ switch (
+ filledSlots[item].resolutions.resolutionsPerAuthority[0].status.code
+ ) {
+ case "ER_SUCCESS_MATCH":
+ slotValues[name] = {
+ heardAs: filledSlots[item].value,
+ resolved:
+ filledSlots[item].resolutions.resolutionsPerAuthority[0].values[0]
+ .value.name,
+ ERstatus: "ER_SUCCESS_MATCH",
+ };
+ break;
+ case "ER_SUCCESS_NO_MATCH":
+ slotValues[name] = {
+ heardAs: filledSlots[item].value,
+ resolved: "",
+ ERstatus: "ER_SUCCESS_NO_MATCH",
+ };
+ break;
+ default:
+ break;
+ }
+ } else {
+ slotValues[name] = {
+ heardAs: filledSlots[item].value || "", // may be null
+ resolved: "",
+ ERstatus: "",
+ };
+ }
+ }, this);
- return slotValues;
+ return slotValues;
}
-export function buildAlexaResponse(outputSpeech: string, reprompt = '', shouldEndSession = false) {
- return {
- version: '1.0',
- sessionAttributes: {},
- response: {
- outputSpeech: {
- type: 'PlainText',
- text: outputSpeech,
- },
- reprompt: {
- outputSpeech: {
- type: 'PlainText',
- text: reprompt,
- },
- },
- shouldEndSession: shouldEndSession,
+export function buildAlexaResponse(
+ outputSpeech: string,
+ reprompt = "",
+ shouldEndSession = false
+) {
+ return {
+ version: "1.0",
+ sessionAttributes: {},
+ response: {
+ outputSpeech: {
+ type: "PlainText",
+ text: outputSpeech,
+ },
+ reprompt: {
+ outputSpeech: {
+ type: "PlainText",
+ text: reprompt,
},
- };
+ },
+ shouldEndSession: shouldEndSession,
+ },
+ };
}
-export async function createAlexaSkill(agentName: string, accessToken: string, vendorId: string, endpoint: string) {
- try {
- const response = await axios({
- method: 'post',
- url: `${ALEXA_BASE_URL}/v1/skills`,
- headers: {
- Authorization: 'Bearer ' + accessToken,
- 'Content-Type': 'application/json',
+export async function createAlexaSkill(
+ agentName: string,
+ accessToken: string,
+ vendorId: string,
+ endpoint: string
+) {
+ try {
+ const response = await axios({
+ method: "post",
+ url: `${ALEXA_BASE_URL}/v1/skills`,
+ headers: {
+ Authorization: "Bearer " + accessToken,
+ "Content-Type": "application/json",
+ },
+ data: {
+ vendorId: vendorId,
+ manifest: {
+ apis: {
+ custom: {
+ endpoint: {
+ sslCertificateType: "Wildcard",
+ uri: endpoint,
+ },
+ interfaces: [],
+ locales: {},
},
- data: {
- vendorId: vendorId,
- manifest: {
- apis: {
- custom: {
- endpoint: {
- sslCertificateType: 'Wildcard',
- uri: endpoint,
- },
- interfaces: [],
- locales: {},
- },
- },
- manifestVersion: '1.0',
- publishingInformation: {
- category: 'ORGANIZERS_AND_ASSISTANTS',
- locales: {
- 'en-US': {
- description: 'Smythos agent',
- examplePhrases: ['Alexa open ' + agentName],
- keywords: [agentName],
- name: agentName,
- summary: 'invoke ' + agentName,
- },
- },
- },
- },
+ },
+ manifestVersion: "1.0",
+ publishingInformation: {
+ category: "ORGANIZERS_AND_ASSISTANTS",
+ locales: {
+ "en-US": {
+ description: "Smythos agent",
+ examplePhrases: ["Alexa open " + agentName],
+ keywords: [agentName],
+ name: agentName,
+ summary: "invoke " + agentName,
+ },
},
- });
- const skillId = response.data.skillId;
- await new Promise((resolve) => setTimeout(resolve, 2000));
+ },
+ },
+ },
+ });
+ const skillId = response.data.skillId;
+ await new Promise((resolve) => setTimeout(resolve, 2000));
- await axios({
- method: 'put',
- url: `${ALEXA_BASE_URL}/v1/skills/${skillId}/stages/development/interactionModel/locales/en-US`,
- headers: {
- Authorization: 'Bearer ' + accessToken,
- 'Content-Type': 'application/json',
- },
- data: {
- interactionModel: {
- languageModel: {
- invocationName: agentName.toLowerCase(),
- intents: [
- {
- name: 'AMAZON.CancelIntent',
- samples: [],
- },
- {
- name: 'AMAZON.HelpIntent',
- samples: [],
- },
- {
- name: 'AMAZON.StopIntent',
- samples: [],
- },
- {
- name: 'AMAZON.FallbackIntent',
- samples: [],
- },
- {
- name: 'AMAZON.NavigateHomeIntent',
- samples: [],
- },
- {
- name: 'SmythosQuery',
- slots: [
- {
- name: 'searchQuery',
- type: 'AMAZON.SearchQuery',
- },
- ],
- samples: ['Hi {searchQuery}', 'Hello {searchQuery}'],
- },
- ],
- types: [],
- },
- },
- },
- });
- return skillId;
- } catch (error: any) {
- console.error(error?.response?.data);
- }
+ await axios({
+ method: "put",
+ url: `${ALEXA_BASE_URL}/v1/skills/${skillId}/stages/development/interactionModel/locales/en-US`,
+ headers: {
+ Authorization: "Bearer " + accessToken,
+ "Content-Type": "application/json",
+ },
+ data: {
+ interactionModel: {
+ languageModel: {
+ invocationName: agentName.toLowerCase(),
+ intents: [
+ {
+ name: "AMAZON.CancelIntent",
+ samples: [],
+ },
+ {
+ name: "AMAZON.HelpIntent",
+ samples: [],
+ },
+ {
+ name: "AMAZON.StopIntent",
+ samples: [],
+ },
+ {
+ name: "AMAZON.FallbackIntent",
+ samples: [],
+ },
+ {
+ name: "AMAZON.NavigateHomeIntent",
+ samples: [],
+ },
+ {
+ name: "SmythosQuery",
+ slots: [
+ {
+ name: "searchQuery",
+ type: "AMAZON.SearchQuery",
+ },
+ ],
+ samples: ["Hi {searchQuery}", "Hello {searchQuery}"],
+ },
+ ],
+ types: [],
+ },
+ },
+ },
+ });
+ return skillId;
+ } catch (error: any) {
+ console.error(error?.response?.data);
+ }
}
-export function processAlexaSearchQuery(query: string, model: string, agent: Agent): Promise<string> {
- return new Promise(async (resolve, reject) => {
- // const { agentId, agentVersion } = getAgentIdAndVersion(model);
- let result = '';
- const spec = await getOpenAPIJSONForAI(agent.domain, agent.usingTestDomain ? '' : 'latest', false);
+export function processAlexaSearchQuery(
+ query: string,
+ model: string,
+ agent: Agent
+): Promise<string> {
+ return new Promise(async (resolve, reject) => {
+ // const { agentId, agentVersion } = getAgentIdAndVersion(model);
+ let result = "";
+ const spec = await getOpenAPIJSONForAI(
+ agent.domain,
+ agent.usingTestDomain ? "" : "latest",
+ false
+ );
- // 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 adaptedModel = adaptModel(model, agent?.planInfo || {});
- const conversation = new Conversation(adaptedModel, spec, {
- agentId: agent.id,
- });
- conversation.on('error', (error) => {
- console.error('Error in conversation:', error);
- throw `An error occurred. Please try again later or select a different model.`;
- });
- conversation.on('content', (content) => {
- try {
- if (content?.indexOf('}{') >= 0) {
- content = content.replace(/}{/g, '} {');
- }
- result += content;
- } catch (e) {}
- });
- conversation.on('end', () => {
- console.log('streaming: [DONE]');
- resolve(result);
- });
- conversation.streamPrompt(`${query} ${SPEAKABLE_FORMAT_PROMPT}`, {
- 'X-AGENT-ID': agent.id,
- });
+ // 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 adaptedModel = adaptModel(model, agent?.planInfo || {});
+ const conversation = new Conversation(adaptedModel, spec, {
+ agentId: agent.id,
});
+ conversation.on("error", (error) => {
+ console.error("Error in conversation:", error);
+ throw `An error occurred. Please try again later or select a different model.`;
+ });
+ conversation.on("content", (content) => {
+ try {
+ if (content?.indexOf("}{") >= 0) {
+ content = content.replace(/}{/g, "} {");
+ }
+ result += content;
+ } catch (e) {}
+ });
+ conversation.on("end", () => {
+ console.log("streaming: [DONE]");
+ resolve(result);
+ });
+ conversation.streamPrompt(`${query} ${SPEAKABLE_FORMAT_PROMPT}`, {
+ "X-AGENT-ID": agent.id,
+ });
+ });
}
export function isAlexaEnabled(agent: Agent) {
- if (agent.usingTestDomain) {
- return true;
- }
- return agent.agentSettings?.get(ALEXA_SETTINGS_KEY) === 'true';
+ if (agent.usingTestDomain) {
+ return true;
+ }
+ return agent.agentSettings?.get(ALEXA_SETTINGS_KEY) === "true";
}
diff --git a/packages/runtime/src/modules/embodiment/modules/chatGPT/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/chatGPT/routes/router.ts
index d1f5904c..1b334e14 100644
--- a/packages/runtime/src/modules/embodiment/modules/chatGPT/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/chatGPT/routes/router.ts
@@ -1,7 +1,7 @@
-import express from "express";
import { getChatGPTManifest } from "@embodiment/helpers/chatgpt.helper";
import { getOpenAPIJSON } from "@embodiment/helpers/openapi-adapter.helper";
import agentLoader from "@embodiment/middlewares/agentLoader.mw";
+import express from "express";
const router = express.Router();
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 705226a4..4ed31c6a 100644
--- a/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts
@@ -1,15 +1,15 @@
-import config from "@embodiment/config";
-import { EMBODIMENT_TYPES } from "@embodiment/constants";
+import config from "@core/config";
+import { EMBODIMENT_TYPES } from "@core/constants";
+import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
+import { AccessCandidate, Agent, BinaryInput } from "@smythos/sre";
+import axios from "axios";
+import express from "express";
+
import { readAgentOAuthConfig } from "@embodiment/helpers/agent.helper";
import { getChatGPTManifest } from "@embodiment/helpers/chatgpt.helper";
import agentLoader from "@embodiment/middlewares/agentLoader.mw";
import ChatbotLoader from "@embodiment/middlewares/ChatbotLoader.mw";
-import cors from "@embodiment/middlewares/cors.mw";
-import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
import { buildConversationId } from "@embodiment/utils/chat.utils";
-import axios from "axios";
-import express from "express";
-import { AccessCandidate, Agent, BinaryInput } from "@smythos/sre";
// Import ChatbotResponse type for proper typing
type ChatbotResponse = {
@@ -29,7 +29,7 @@ const MAX_TTL_CHATBOT_FILE_UPLOAD = 60 * 60 * 24 * 1; // 1 day
let localAgentAuthorizations = {};
-const middleweares = [agentLoader, ChatbotLoader, cors];
+const middleweares = [agentLoader, ChatbotLoader];
router.use(middleweares);
router.get("/", async (req, res) => {
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
index 3e59fbcf..cf8628f3 100644
--- a/packages/runtime/src/modules/embodiment/modules/chatbot/services/ChatDataManager.class.ts
+++ b/packages/runtime/src/modules/embodiment/modules/chatbot/services/ChatDataManager.class.ts
@@ -1,4 +1,8 @@
-import { IChatMessage, IChatStorage, IMetadataFile } from '@core/types/chat.types';
+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
@@ -9,248 +13,276 @@ import { IChatMessage, IChatStorage, IMetadataFile } from '@core/types/chat.type
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'];
+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;
- 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 });
+ 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"
+ );
}
- async initManager() {
- const metaData = await this.getMetaData();
- console.log('initManager', metaData);
+ this.storage.setParams({ teamId, userId, agentId, conversationId });
+ }
- if (metaData) {
- this.chunkIndex = metaData.lastChunkId || 0;
- }
- return this; // to allow chaining
- }
+ async initManager() {
+ const metaData = await this.getMetaData();
+ console.log("initManager", metaData);
- getChunkFileName(chunkId?: number): string {
- return `chunk_${chunkId || this.chunkIndex}.json`;
+ if (metaData) {
+ this.chunkIndex = metaData.lastChunkId || 0;
}
-
- async storeMetaData(metaData: IMetadataFile) {
- await this.storage.write(this.metaDataFilename, JSON.stringify(metaData), {});
- return this.metaUpdateCallback(metaData);
+ 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;
}
- async initConversation(metaData: IMetadataFile) {
- return this.storeMetaData(metaData);
+ 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 [];
}
- 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;
+ 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--;
}
- 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;
+ 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--;
}
- async getLatestChunkFile(createIfNeeded?: boolean): Promise<ChunkFile> {
- return this.getChunkFile(this.chunkIndex, createIfNeeded);
+ // 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
+ }
}
- async getNextChunkFile(current: number): Promise<ChunkFile> {
- const index = current + 1;
- return this.getChunkFile(index);
- }
+ if (chunkFile.length >= this.maxChunks) {
+ this.chunkIndex++;
- async getPrevChunkFile(current: number): Promise<ChunkFile> {
- const index = Math.max(current - 1, 0);
- return this.getChunkFile(index);
- }
+ if (metaData) {
+ metaData.lastChunkId = this.chunkIndex;
+ this.storeMetaData(metaData);
+ }
- // 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);
+ chunkFile = []; // to only store current message in the new file
}
- // #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;
+ 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--;
}
- 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;
- }
+ 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
index ce761f2d..7f9fb82a 100644
--- a/packages/runtime/src/modules/embodiment/modules/chatbot/services/Chatbot.class.ts
+++ b/packages/runtime/src/modules/embodiment/modules/chatbot/services/Chatbot.class.ts
@@ -1,12 +1,14 @@
+import { Agent, AgentLogger, Conversation } from "@smythos/sre";
import { Request } from "express";
-import { Agent, AgentLogger, Conversation } from "smyth-runtime";
-import config from "@embodiment/config";
-import { EMBODIMENT_TYPES } from "@embodiment/constants";
-import { getOpenAPIJSONForAI } from "@embodiment/helpers/openapi-adapter.helper";
-import { ChatConversationsEnv } from "@embodiment/utils/chat.utils";
+import config from "@core/config";
+import { EMBODIMENT_TYPES } from "@core/constants";
import { delay } from "@core/utils/date-time.utils";
import { adaptModel } from "@core/utils/llm.utils";
+
+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";
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
index 7ecfc8fd..86a9d340 100644
--- 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
@@ -1,66 +1,77 @@
-import { Readable } from 'stream';
-import * as fs from 'fs';
-import path from 'path';
-import * as chatUtils from '@embodiment/utils/chat.utils';
-import { fsExists } from '@core/utils/general.utils';
+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;
+ stream: fs.ReadStream;
+ convId: string;
};
export class FsChatbotContextExporter {
- private sessionsPath: string;
- private agentId: string;
+ private sessionsPath: string;
+ private agentId: string;
- constructor({ sessionsPath, agentId }: { sessionsPath: string; agentId: string }) {
- this.sessionsPath = sessionsPath;
- this.agentId = agentId;
- }
+ 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'];
+ /**
+ * 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;
+ // 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;
+ 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;
- }
+ // 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;
- });
+ 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', '') };
- }
+ 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
index 3921c9bf..bea9e29c 100644
--- 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
@@ -1,94 +1,118 @@
-import fs from 'fs';
-import path from 'path';
-import { EStorageTypes } from '@core/types/fileStorage.types';
-import type { ILLMContextStore } from 'smyth-runtime';
-import * as chatUtils from '@embodiment/utils/chat.utils';
-import { fsExists } from '@core/utils/general.utils';
-import { Readable } from 'stream';
-import { FsChatbotContextExporter } from './FsChatbotContextExporter.class';
+import { EStorageTypes } from "@/modules/embodiment/types/fileStorage.types";
+import { fsExists } from "@core/utils/general.utils";
+import type { ILLMContextStore } from "@smythos/sre";
+import fs from "fs";
+import path from "path";
+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;
+ 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,
- });
+ constructor({
+ agentId,
+ conversationID,
+ dataPath,
+ }: {
+ agentId: string;
+ conversationID: string;
+ dataPath?: string;
+ }) {
+ if (!dataPath) {
+ throw new Error("dataPath is required.");
}
- 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);
- }
+ if (!fs.existsSync(dataPath)) {
+ throw new Error(`The data folder at ${dataPath} does not exist.`);
}
- public async load(count?: number): Promise<any[]> {
- const conversations = await this.getConversationById(this.agentId, this.conversationID);
- if (count === undefined) return conversations;
+ this.dataFolder = dataPath;
+ this.agentId = agentId;
+ this.conversationID = conversationID;
+ this.sessionsPath = path.join(dataPath, "chat_sessions");
+ this.exporter = new FsChatbotContextExporter({
+ sessionsPath: this.sessionsPath,
+ agentId,
+ });
+ }
- if (typeof count === 'number' && count > 0) {
- return conversations.slice(-count);
- }
+ 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;
- public async getMessage(message_id: string): Promise<Record<string, any>> {
- return {};
+ if (typeof count === "number" && count > 0) {
+ return conversations.slice(-count);
}
+ }
- private async getConversationById(agentId: string, conversationId: string): Promise<Record<string, any>[]> {
- const folderPath = path.join(this.sessionsPath, agentId);
+ public async getMessage(message_id: string): Promise<any> {
+ return [];
+ }
- if (!(await fsExists(folderPath))) {
- return [];
- }
+ private async getConversationById(
+ agentId: string,
+ conversationId: string
+ ): Promise<Record<string, any>[]> {
+ const folderPath = path.join(this.sessionsPath, agentId);
- const filePath = path.join(folderPath, conversationId + '.json');
+ if (!(await fsExists(folderPath))) {
+ return [];
+ }
- if (!(await fsExists(filePath))) {
- return [];
- }
+ const filePath = path.join(folderPath, conversationId + ".json");
- try {
- const fileContent = await fs.promises.readFile(filePath, { encoding: 'utf8' });
- return JSON.parse(fileContent);
- } catch (error) {
- return [];
- }
+ if (!(await fsExists(filePath))) {
+ return [];
}
- private getConversationFilePath(agentId: string, conversationID: string): string {
- return path.join(this.sessionsPath, agentId, `${conversationID}.json`);
+ 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 });
+ 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/modules/formPreview/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts
index 2f1da18b..f6792626 100644
--- a/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts
@@ -1,13 +1,12 @@
-import express from "express";
-import { Agent } from "@smythos/sre";
-import agentLoader from "@embodiment/middlewares/agentLoader.mw";
-import cors from "@embodiment/middlewares/cors.mw";
-import config from "@embodiment/config";
+import config from "@core/config";
import { callSkill } from "@embodiment/helpers/formPreview.helper";
+import agentLoader from "@embodiment/middlewares/agentLoader.mw";
+import { Agent } from "@smythos/sre";
+import express from "express";
const router = express.Router();
-const middlewares = [agentLoader, cors];
+const middlewares = [agentLoader];
router.use(middlewares);
router.get("/", async (req, res) => {
diff --git a/packages/runtime/src/modules/embodiment/modules/mcp/services/mcp.services.ts b/packages/runtime/src/modules/embodiment/modules/mcp/services/mcp.services.ts
index 06b1a746..acac4552 100644
--- a/packages/runtime/src/modules/embodiment/modules/mcp/services/mcp.services.ts
+++ b/packages/runtime/src/modules/embodiment/modules/mcp/services/mcp.services.ts
@@ -1,65 +1,65 @@
-import { Agent } from 'smyth-runtime';
-const MCP_SETTINGS_KEY = 'mcp';
+import { Agent } from "@smythos/sre";
+const MCP_SETTINGS_KEY = "mcp";
export const isMcpEnabled = (agent: Agent) => {
- if (agent.usingTestDomain) {
- return true;
+ if (agent.usingTestDomain) {
+ return true;
+ }
+ const mcpSettings = agent.agentSettings?.get(MCP_SETTINGS_KEY);
+ let isEnabled = false;
+ if (mcpSettings) {
+ try {
+ const parsedMcpSettings = JSON.parse(mcpSettings);
+ if (parsedMcpSettings.isEnabled) {
+ isEnabled = true;
+ }
+ } catch (error) {
+ isEnabled = false;
}
- const mcpSettings = agent.agentSettings?.get(MCP_SETTINGS_KEY);
- let isEnabled = false;
- if (mcpSettings) {
- try {
- const parsedMcpSettings = JSON.parse(mcpSettings);
- if (parsedMcpSettings.isEnabled) {
- isEnabled = true;
- }
- } catch (error) {
- isEnabled = false;
- }
- }
- return isEnabled;
+ }
+ return isEnabled;
};
export function extractMCPToolSchema(jsonSpec: any, method: string) {
- if (method.toLowerCase() === 'get') {
- const schema = jsonSpec?.parameters;
- if (!schema) return {};
+ if (method.toLowerCase() === "get") {
+ const schema = jsonSpec?.parameters;
+ if (!schema) return {};
- const properties = {};
- const required = [];
+ const properties = {};
+ const required = [];
- schema.forEach(param => {
- if (param.in === 'query') {
- properties[param.name] = param.schema;
- if (param.required) {
- required.push(param.name);
- }
- }
- });
+ schema.forEach((param) => {
+ if (param.in === "query") {
+ properties[param.name] = param.schema;
+ if (param.required) {
+ required.push(param.name);
+ }
+ }
+ });
- return {
- type: 'object',
- properties,
- required
- };
- }
- const schema = jsonSpec?.requestBody?.content?.['application/json']?.schema;
- return schema;
+ return {
+ type: "object",
+ properties,
+ required,
+ };
+ }
+ const schema = jsonSpec?.requestBody?.content?.["application/json"]?.schema;
+ return schema;
}
export function formatMCPSchemaProperties(schema: any) {
- const properties = schema?.properties || {};
- for (const property in properties) {
- const propertySchema = properties[property];
+ const properties = schema?.properties || {};
+ for (const property in properties) {
+ const propertySchema = properties[property];
- if (propertySchema.type === 'array') {
- properties[property] = {
- type: 'array',
- items: {
- type: ['string', 'number', 'boolean', 'object', 'array'],
- },
- };
- }
+ if (propertySchema.type === "array") {
+ properties[property] = {
+ type: "array",
+ items: {
+ type: ["string", "number", "boolean", "object", "array"],
+ },
+ };
}
- return properties;
-}
\ No newline at end of file
+ }
+ return properties;
+}
diff --git a/packages/runtime/src/modules/embodiment/modules/openai/routes/index.ts b/packages/runtime/src/modules/embodiment/modules/openai/routes/index.ts
index 811b6db2..d89f330d 100644
--- a/packages/runtime/src/modules/embodiment/modules/openai/routes/index.ts
+++ b/packages/runtime/src/modules/embodiment/modules/openai/routes/index.ts
@@ -1,17 +1,17 @@
-import OpenAI from "openai";
-import { Readable } from "stream";
-import { Router, Request, Response } from "express";
-import ApiError from "@core/utils/apiError";
-import { Logger } from "@smythos/sre";
-import { extractBearerToken } from "@core/services/smythAPIReq";
-import { validate } from "@core/middlewares/validate.mw";
-import { chatService } from "@embodiment/modules/openai/services/chat.service";
-import { chatValidations } from "@embodiment/modules/openai/validations/openai.validation";
import {
DEFAULT_AGENT_MODEL,
DEFAULT_AGENT_MODEL_SETTINGS_KEY,
-} from "@embodiment/constants";
+} from "@core/constants";
+import { validate } from "@core/middlewares/validate.mw";
+import { extractBearerToken } from "@core/services/smythAPIReq";
+import ApiError from "@core/utils/apiError";
import agentLoader from "@embodiment/middlewares/agentLoader.mw";
+import { chatService } from "@embodiment/modules/openai/services/chat.service";
+import { chatValidations } from "@embodiment/modules/openai/validations/openai.validation";
+import { Logger } from "@smythos/sre";
+import { Request, Response, Router } from "express";
+import OpenAI from "openai";
+import { Readable } from "stream";
const router = Router();
const console = Logger("[Embodiment] Router: OpenAI");
diff --git a/packages/runtime/src/modules/embodiment/modules/openai/services/chat.service.ts b/packages/runtime/src/modules/embodiment/modules/openai/services/chat.service.ts
index 75994adc..a57f3dac 100644
--- a/packages/runtime/src/modules/embodiment/modules/openai/services/chat.service.ts
+++ b/packages/runtime/src/modules/embodiment/modules/openai/services/chat.service.ts
@@ -1,16 +1,16 @@
-import crypto from "crypto";
-import { OpenAI } from "openai";
-import { Readable } from "stream";
import ApiError from "@core/utils/apiError";
+import { adaptModel } from "@core/utils/llm.utils";
import { getAgentIdAndVersion } from "@embodiment/helpers/agent.helper";
import {
- ConnectorService,
AccessCandidate,
- Logger,
- Conversation,
Agent,
+ ConnectorService,
+ Conversation,
+ Logger,
} from "@smythos/sre";
-import { adaptModel } from "@core/utils/llm.utils";
+import crypto from "crypto";
+import { OpenAI } from "openai";
+import { Readable } from "stream";
const console = Logger("[Embodiment] Service: OpenAI Chat");
diff --git a/packages/runtime/src/modules/embodiment/modules/postman/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/postman/routes/router.ts
index b1c92906..b60a0b2d 100644
--- a/packages/runtime/src/modules/embodiment/modules/postman/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/postman/routes/router.ts
@@ -1,7 +1,7 @@
-import express from "express";
import { getOpenAPIJSON } from "@embodiment/helpers/openapi-adapter.helper";
-import Converter from "openapi-to-postmanv2";
import agentLoader from "@embodiment/middlewares/agentLoader.mw";
+import express from "express";
+import Converter from "openapi-to-postmanv2";
const router = express.Router();
diff --git a/packages/runtime/src/modules/embodiment/modules/swagger/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/swagger/routes/router.ts
index 0f7ab133..7da36bf4 100644
--- a/packages/runtime/src/modules/embodiment/modules/swagger/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/swagger/routes/router.ts
@@ -1,10 +1,10 @@
import express from "express";
+import swaggerUi from "swagger-ui-express";
+import config from "@core/config";
import { getOpenAPIJSON } from "@embodiment/helpers/openapi-adapter.helper";
-import swaggerUi from "swagger-ui-express";
-import { Agent } from "@smythos/sre";
-import config from "@embodiment/config";
import agentLoader from "@embodiment/middlewares/agentLoader.mw";
+import { Agent } from "@smythos/sre";
const router = express.Router();
diff --git a/packages/runtime/src/modules/embodiment/routes/index.ts b/packages/runtime/src/modules/embodiment/routes/index.ts
index cdc6bca1..8611d6fa 100644
--- a/packages/runtime/src/modules/embodiment/routes/index.ts
+++ b/packages/runtime/src/modules/embodiment/routes/index.ts
@@ -1,15 +1,15 @@
-import express, { Router } from "express";
-import { openaiRouter } from "@embodiment/modules/openai/routes";
-import { apiRouter } from "@embodiment/modules/API/routes/router";
import config from "@core/config";
-import { chatGPTRouter } from "@embodiment/modules/chatGPT/routes/router";
-import { postmanRouter } from "@embodiment/modules/postman/routes/router";
-import { swaggerRouter } from "@embodiment/modules/swagger/routes/router";
-import { chatBotRouter } from "@embodiment/modules/chatbot/routes/router";
import { agentChatRouter } from "@embodiment/modules/agentChat/routes/router";
import { alexaRouter } from "@embodiment/modules/alexa/routes/router";
-import { mcpRouter } from "@embodiment/modules/mcp/routes/router";
+import { apiRouter } from "@embodiment/modules/API/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";
+import { mcpRouter } from "@embodiment/modules/mcp/routes/router";
+import { openaiRouter } from "@embodiment/modules/openai/routes";
+import { postmanRouter } from "@embodiment/modules/postman/routes/router";
+import { swaggerRouter } from "@embodiment/modules/swagger/routes/router";
+import { Router } from "express";
const mainRouter = Router();
diff --git a/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts b/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts
new file mode 100644
index 00000000..8e1a793e
--- /dev/null
+++ b/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts
@@ -0,0 +1,452 @@
+import { Agent, AgentLogger, Conversation } from "@smythos/sre";
+import { Request } from "express";
+
+import config from "@core/config";
+import { EMBODIMENT_TYPES } from "@core/constants";
+
+import { getOpenAPIJSONForAI } from "../helpers/openapi-adapter.helper";
+import { FsChatbotContextStore } from "../services/FsChatbotContextStore.class";
+import { ChatConversationsEnv } from "../utils/chat.utils";
+import { delay } from "../utils/date-time.utils";
+import { adaptModel } from "../utils/llm.utils";
+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 adaptedModel = adaptModel(this.model, this.agent?.planInfo || {});
+ const conversation = new Conversation(adaptedModel, 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/services/FsChatbotContextStore.class/FsChatbotContextExporter.class.ts b/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/FsChatbotContextExporter.class.ts
new file mode 100644
index 00000000..3e736829
--- /dev/null
+++ b/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/FsChatbotContextExporter.class.ts
@@ -0,0 +1,79 @@
+import * as fs from "fs";
+import path from "path";
+
+import * as chatUtils from "@embodiment/utils/chat.utils";
+import { fsExists } from "@embodiment/utils/general.utils";
+
+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/services/FsChatbotContextStore.class/index.ts b/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/index.ts
new file mode 100644
index 00000000..eed4e30d
--- /dev/null
+++ b/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/index.ts
@@ -0,0 +1,121 @@
+import fs from "fs";
+import path from "path";
+
+import type { ILLMContextStore } from "@smythos/sre";
+
+import { EStorageTypes } from "@embodiment/types/fileStorage.types";
+import { fsExists } from "@embodiment/utils/general.utils";
+
+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/core/types/chat.types.ts b/packages/runtime/src/modules/embodiment/types/chat.types.ts
similarity index 100%
rename from packages/runtime/src/core/types/chat.types.ts
rename to packages/runtime/src/modules/embodiment/types/chat.types.ts
diff --git a/packages/runtime/src/core/types/chatgpt.types.ts b/packages/runtime/src/modules/embodiment/types/chatgpt.types.ts
similarity index 100%
rename from packages/runtime/src/core/types/chatgpt.types.ts
rename to packages/runtime/src/modules/embodiment/types/chatgpt.types.ts
diff --git a/packages/runtime/src/core/types/fileStorage.types.ts b/packages/runtime/src/modules/embodiment/types/fileStorage.types.ts
similarity index 100%
rename from packages/runtime/src/core/types/fileStorage.types.ts
rename to packages/runtime/src/modules/embodiment/types/fileStorage.types.ts
diff --git a/packages/runtime/src/modules/embodiment/utils/apiError.ts b/packages/runtime/src/modules/embodiment/utils/apiError.ts
new file mode 100644
index 00000000..95b231ee
--- /dev/null
+++ b/packages/runtime/src/modules/embodiment/utils/apiError.ts
@@ -0,0 +1,40 @@
+/**
+ * @class ApiError
+ * @extends Error
+ * @public
+ * @description
+ * ApiError class is used to create an error object that will be used by the error handler middleware.
+ * It is the primary error class that will be used in the application.
+
+ */
+class ApiError extends Error {
+ statusCode: number | null | undefined;
+
+ isOperational: boolean;
+
+ stack: string | undefined;
+
+ errKey: string | undefined;
+
+ isApiError: boolean;
+
+ /**
+ *
+ * @param statusCode - http status code of the error
+ * @param message - error message
+ * @param isOperational - whether the error should be shown in production or not (if not, internal server error will be shown)
+ * @param stack - error stack trace
+ * @param errKey - error code to be used in the response
+ */
+
+ // eslint-disable-next-line default-param-last
+ constructor(statusCode: number | null | undefined, message: string, errKey?: string, isOperational = true, stack?: string) {
+ super(message);
+ this.statusCode = statusCode;
+ this.isOperational = isOperational === undefined ? true : isOperational;
+ this.errKey = errKey;
+ this.isApiError = true;
+ }
+}
+
+export default ApiError;
diff --git a/packages/runtime/src/modules/embodiment/utils/chat.utils.ts b/packages/runtime/src/modules/embodiment/utils/chat.utils.ts
new file mode 100644
index 00000000..4430f81b
--- /dev/null
+++ b/packages/runtime/src/modules/embodiment/utils/chat.utils.ts
@@ -0,0 +1,33 @@
+import crypto from 'crypto';
+import { getCurrentFormattedDate, toDateFromFormattedDateStr } from './date-time.utils';
+export type ChatConversationsEnv = 'test' | 'prod';
+export const CHAT_PREFIXES: Record<ChatConversationsEnv, string> = {
+ test: 'chat-test-',
+ prod: 'chat-',
+};
+
+export const buildConversationId = (uid?: string, isTestConv = false) => {
+ const prefix = isTestConv ? CHAT_PREFIXES.test : CHAT_PREFIXES.prod;
+ const convId = uid ?? `${prefix}${getCurrentFormattedDate()}-${crypto.randomBytes(8).toString('hex')}`;
+ return `${prefix}${getCurrentFormattedDate()}-${convId}`;
+};
+export const parseDateFromConvId = (convId: string) => {
+ const match = convId.match(/\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}/);
+
+ if (!match) return null;
+ return toDateFromFormattedDateStr(match[0]);
+};
+
+export const getChatPrefixByEnv = (env: ChatConversationsEnv) => {
+ return CHAT_PREFIXES[env];
+};
+
+export const parseDateRange = (dateRange: string) => {
+ const [start, end] = dateRange.split(',');
+ return { start: parseInt(start), end: parseInt(end) };
+};
+export const isValidDateRange = (dateRange: string) => {
+ if (!dateRange) return false;
+ const { start, end } = parseDateRange(dateRange);
+ return !isNaN(start) && !isNaN(end) && start < end;
+};
diff --git a/packages/runtime/src/modules/embodiment/utils/date-time.utils copy.ts b/packages/runtime/src/modules/embodiment/utils/date-time.utils copy.ts
new file mode 100644
index 00000000..9184e5d5
--- /dev/null
+++ b/packages/runtime/src/modules/embodiment/utils/date-time.utils copy.ts
@@ -0,0 +1,27 @@
+export function getCurrentFormattedDate() {
+ const date = new Date();
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
+ const day = String(date.getDate()).padStart(2, '0');
+ const hours = String(date.getHours()).padStart(2, '0');
+ const minutes = String(date.getMinutes()).padStart(2, '0');
+ const seconds = String(date.getSeconds()).padStart(2, '0');
+ return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
+}
+
+export function toDateFromFormattedDateStr(formattedDate: string) {
+ const [year, month, day, hour, minute, second] = formattedDate.split('-').map(Number);
+ return new Date(year, month - 1, day, hour, minute, second);
+}
+
+export function getDayFormattedDate() {
+ const date = new Date();
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}`;
+}
+
+export function delay(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+}
diff --git a/packages/runtime/src/modules/embodiment/utils/date-time.utils.ts b/packages/runtime/src/modules/embodiment/utils/date-time.utils.ts
new file mode 100644
index 00000000..9184e5d5
--- /dev/null
+++ b/packages/runtime/src/modules/embodiment/utils/date-time.utils.ts
@@ -0,0 +1,27 @@
+export function getCurrentFormattedDate() {
+ const date = new Date();
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
+ const day = String(date.getDate()).padStart(2, '0');
+ const hours = String(date.getHours()).padStart(2, '0');
+ const minutes = String(date.getMinutes()).padStart(2, '0');
+ const seconds = String(date.getSeconds()).padStart(2, '0');
+ return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
+}
+
+export function toDateFromFormattedDateStr(formattedDate: string) {
+ const [year, month, day, hour, minute, second] = formattedDate.split('-').map(Number);
+ return new Date(year, month - 1, day, hour, minute, second);
+}
+
+export function getDayFormattedDate() {
+ const date = new Date();
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}`;
+}
+
+export function delay(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+}
diff --git a/packages/runtime/src/modules/embodiment/utils/general.utils.ts b/packages/runtime/src/modules/embodiment/utils/general.utils.ts
new file mode 100644
index 00000000..75de713d
--- /dev/null
+++ b/packages/runtime/src/modules/embodiment/utils/general.utils.ts
@@ -0,0 +1,52 @@
+import fs from 'fs/promises';
+
+export function uid() {
+ return (Date.now() + Math.random()).toString(36).replace('.', '').toUpperCase();
+}
+
+export const hasKeyTemplateVar = (str: string = ''): boolean => {
+ if (!str || typeof str !== 'string') return false;
+ return (str?.match(/{{KEY\((.*?)\)}}/g) ?? []).length > 0;
+};
+
+export function parseTemplate(str, obj, { escapeString = true, processUnmatched = true, unmached = '' } = {}) {
+ try {
+ const parsed = str?.replace(/{{(.*?)}}/g, function (match, varName) {
+ // if key template var, return as is
+ if (hasKeyTemplateVar(match)) return match;
+
+ let objVal = obj[varName.trim()];
+
+ if (typeof objVal === 'object') {
+ objVal = JSON.stringify(objVal);
+ } else {
+ if (escapeString && typeof objVal === 'string') {
+ //escape double quotes, slashes ...
+ objVal = objVal?.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t');
+ }
+ }
+
+ // Need to consider boolean 'false' as a valid value
+ // const val = objVal || match;
+ const val = objVal !== undefined ? objVal : match;
+
+ return typeof val == 'string' || typeof val == 'number' ? val : JSON.stringify(val);
+ });
+
+ //replace unmached vars with default value, make sure to ignore the key template var
+ return str == parsed && processUnmatched ? parsed?.replace(/{{(?!KEY\().*?}}/g, unmached) : parsed;
+ } catch (err) {
+ console.log('Error on parse template: ', err);
+
+ return str;
+ }
+}
+
+export const fsExists = async (path: string) => {
+ try {
+ await fs.access(path);
+ return true;
+ } catch {
+ return false;
+ }
+};
diff --git a/packages/runtime/src/modules/embodiment/utils/llm.utils.ts b/packages/runtime/src/modules/embodiment/utils/llm.utils.ts
new file mode 100644
index 00000000..6a63f456
--- /dev/null
+++ b/packages/runtime/src/modules/embodiment/utils/llm.utils.ts
@@ -0,0 +1,40 @@
+import { MODELS_FOR_LEGACY_USERS } from "@core/constants";
+
+/**
+ * Adapts a model name based on user plan information and model availability.
+ *
+ * For users without access to built-in models (free users or users without the hasBuiltinModels flag),
+ * this function prefixes certain models with 'legacy/' to ensure they can still be used.
+ *
+ * @param {string} model - The original model name to be adapted
+ * @param {Record<string, any>} planInfo - User's plan information object
+ * @param {boolean} [planInfo.isDefaultPlan] - Whether the user is on the default/free plan
+ * @param {Object} [planInfo.flags] - Feature flags for the user's plan
+ * @param {boolean} [planInfo.flags.hasBuiltinModels] - Whether the user has access to built-in models
+ * @returns {string} The adapted model name, potentially prefixed with 'legacy/' if conditions are met.
+ * In case of any error during processing, returns the original model unchanged.
+ *
+ * @example
+ * -- For a free user trying to use a legacy model
+ * adaptModel('gpt-3.5-turbo', { isDefaultPlan: true }) // Returns 'legacy/gpt-3.5-turbo'
+ *
+ * @example
+ * -- For a premium user
+ * adaptModel('gpt-4', { isDefaultPlan: false, flags: { hasBuiltinModels: true } }) // Returns 'gpt-4'
+ */
+export function adaptModel(model: string, planInfo: Record<string, any>) {
+ try {
+ const isFreeUser = planInfo?.isDefaultPlan;
+ const hasBuiltInModels = isFreeUser || planInfo?.flags?.hasBuiltinModels;
+
+ // If the model is listed in the legacy models array and the user doesn't have access to built-in models, prefix the model with 'legacy/' to allow the model to be used
+ if (!hasBuiltInModels && MODELS_FOR_LEGACY_USERS.includes(model)) {
+ return `legacy/${model}`;
+ }
+
+ return model;
+ } catch {
+ // Fallback: if any error occurs during processing, return the original model to ensure function never throws
+ return model;
+ }
+}