@botonic/plugin-ai-agents 0.45.0-alpha.1 → 0.46.0-alpha-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/lib/cjs/agent-builder.d.ts +5 -0
  2. package/lib/cjs/agent-builder.js +7 -15
  3. package/lib/cjs/agent-builder.js.map +1 -1
  4. package/lib/cjs/bot-config-tools.d.ts +7 -0
  5. package/lib/cjs/bot-config-tools.js +19 -0
  6. package/lib/cjs/bot-config-tools.js.map +1 -0
  7. package/lib/cjs/constants.d.ts +2 -1
  8. package/lib/cjs/constants.js +3 -2
  9. package/lib/cjs/constants.js.map +1 -1
  10. package/lib/cjs/debug-logger.d.ts +4 -2
  11. package/lib/cjs/debug-logger.js +12 -14
  12. package/lib/cjs/debug-logger.js.map +1 -1
  13. package/lib/cjs/guardrails/input.d.ts +8 -1
  14. package/lib/cjs/guardrails/input.js +48 -2
  15. package/lib/cjs/guardrails/input.js.map +1 -1
  16. package/lib/cjs/index.d.ts +4 -1
  17. package/lib/cjs/index.js +34 -13
  18. package/lib/cjs/index.js.map +1 -1
  19. package/lib/cjs/llm-config.d.ts +15 -0
  20. package/lib/cjs/llm-config.js +66 -0
  21. package/lib/cjs/llm-config.js.map +1 -0
  22. package/lib/cjs/runner.d.ts +7 -1
  23. package/lib/cjs/runner.js +94 -11
  24. package/lib/cjs/runner.js.map +1 -1
  25. package/lib/cjs/services/hubtype-api-client.d.ts +14 -0
  26. package/lib/{esm → cjs/services}/hubtype-api-client.js +19 -5
  27. package/lib/cjs/services/hubtype-api-client.js.map +1 -0
  28. package/lib/cjs/services/types.d.ts +85 -0
  29. package/lib/cjs/services/types.js +13 -0
  30. package/lib/cjs/services/types.js.map +1 -0
  31. package/lib/cjs/tools/retrieve-knowledge.js +1 -1
  32. package/lib/cjs/tools/retrieve-knowledge.js.map +1 -1
  33. package/lib/cjs/types.d.ts +7 -0
  34. package/lib/esm/agent-builder.d.ts +5 -0
  35. package/lib/esm/agent-builder.js +7 -15
  36. package/lib/esm/agent-builder.js.map +1 -1
  37. package/lib/esm/bot-config-tools.d.ts +7 -0
  38. package/lib/esm/bot-config-tools.js +19 -0
  39. package/lib/esm/bot-config-tools.js.map +1 -0
  40. package/lib/esm/constants.d.ts +2 -1
  41. package/lib/esm/constants.js +3 -2
  42. package/lib/esm/constants.js.map +1 -1
  43. package/lib/esm/debug-logger.d.ts +4 -2
  44. package/lib/esm/debug-logger.js +12 -14
  45. package/lib/esm/debug-logger.js.map +1 -1
  46. package/lib/esm/guardrails/input.d.ts +8 -1
  47. package/lib/esm/guardrails/input.js +48 -2
  48. package/lib/esm/guardrails/input.js.map +1 -1
  49. package/lib/esm/index.d.ts +4 -1
  50. package/lib/esm/index.js +34 -13
  51. package/lib/esm/index.js.map +1 -1
  52. package/lib/esm/llm-config.d.ts +15 -0
  53. package/lib/esm/llm-config.js +66 -0
  54. package/lib/esm/llm-config.js.map +1 -0
  55. package/lib/esm/runner.d.ts +7 -1
  56. package/lib/esm/runner.js +94 -11
  57. package/lib/esm/runner.js.map +1 -1
  58. package/lib/esm/services/hubtype-api-client.d.ts +14 -0
  59. package/lib/{cjs → esm/services}/hubtype-api-client.js +19 -5
  60. package/lib/esm/services/hubtype-api-client.js.map +1 -0
  61. package/lib/esm/services/types.d.ts +85 -0
  62. package/lib/esm/services/types.js +13 -0
  63. package/lib/esm/services/types.js.map +1 -0
  64. package/lib/esm/tools/retrieve-knowledge.js +1 -1
  65. package/lib/esm/tools/retrieve-knowledge.js.map +1 -1
  66. package/lib/esm/types.d.ts +7 -0
  67. package/package.json +5 -4
  68. package/src/agent-builder.ts +22 -19
  69. package/src/bot-config-tools.ts +21 -0
  70. package/src/constants.ts +3 -2
  71. package/src/debug-logger.ts +24 -28
  72. package/src/guardrails/input.ts +82 -4
  73. package/src/index.ts +56 -16
  74. package/src/llm-config.ts +96 -0
  75. package/src/runner.ts +140 -12
  76. package/src/{hubtype-api-client.ts → services/hubtype-api-client.ts} +31 -83
  77. package/src/services/types.ts +106 -0
  78. package/src/tools/retrieve-knowledge.ts +1 -1
  79. package/src/types.ts +8 -0
  80. package/lib/cjs/hubtype-api-client.d.ts +0 -23
  81. package/lib/cjs/hubtype-api-client.js.map +0 -1
  82. package/lib/cjs/openai.d.ts +0 -1
  83. package/lib/cjs/openai.js +0 -39
  84. package/lib/cjs/openai.js.map +0 -1
  85. package/lib/esm/hubtype-api-client.d.ts +0 -23
  86. package/lib/esm/hubtype-api-client.js.map +0 -1
  87. package/lib/esm/openai.d.ts +0 -1
  88. package/lib/esm/openai.js +0 -39
  89. package/lib/esm/openai.js.map +0 -1
  90. package/src/openai.ts +0 -49
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.HubtypeApiClient = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const axios_1 = tslib_1.__importDefault(require("axios"));
6
- const constants_1 = require("./constants");
6
+ const constants_1 = require("../constants");
7
7
  class HubtypeApiClient {
8
8
  constructor(authToken) {
9
9
  this.authToken = authToken;
@@ -41,14 +41,14 @@ class HubtypeApiClient {
41
41
  .map(message => this.formatMessage(message));
42
42
  return filteredMessages.slice(-maxMemoryLength);
43
43
  }
44
- async getMessages(request, maxMemoryLength) {
44
+ async getMessages(botContext, maxMemoryLength) {
45
45
  const url = `${constants_1.HUBTYPE_API_URL}/external/v1/ai/agent/message_history/`;
46
46
  const headers = {
47
47
  'Content-Type': 'application/json',
48
48
  Authorization: `Bearer ${this.authToken}`,
49
49
  };
50
50
  const params = {
51
- last_message_id: request.input.message_id,
51
+ last_message_id: botContext.input.message_id,
52
52
  num_messages: maxMemoryLength,
53
53
  };
54
54
  try {
@@ -64,14 +64,14 @@ class HubtypeApiClient {
64
64
  throw new Error('Failed to get messages from Hubtype');
65
65
  }
66
66
  }
67
- async getMessagesV2(request, options = {}) {
67
+ async getMessagesV2(botContext, options = {}) {
68
68
  const url = `${constants_1.HUBTYPE_API_URL}/external/v2/ai/agent/message_history/`;
69
69
  const headers = {
70
70
  'Content-Type': 'application/json',
71
71
  Authorization: `Bearer ${this.authToken}`,
72
72
  };
73
73
  const params = {
74
- last_message_id: request.input.message_id,
74
+ last_message_id: botContext.input.message_id,
75
75
  ...(options.maxMessages !== undefined && {
76
76
  max_messages: options.maxMessages,
77
77
  }),
@@ -164,6 +164,20 @@ class HubtypeApiClient {
164
164
  throw new Error(`Invalid message role: ${message.role}`);
165
165
  }
166
166
  }
167
+ async trackLlmRuns(botId, data) {
168
+ // Not stop the bot execution if the tracking fails, just log the error
169
+ try {
170
+ const url = `${constants_1.HUBTYPE_API_URL}/external/v2/conversational_apps/${botId}/track_llm_runs/`;
171
+ const headers = {
172
+ 'Content-Type': 'application/json',
173
+ Authorization: `Bearer ${this.authToken}`,
174
+ };
175
+ await axios_1.default.post(url, data, { headers });
176
+ }
177
+ catch (error) {
178
+ console.error('Failed to track LLM runs:', error);
179
+ }
180
+ }
167
181
  formatMessage(message) {
168
182
  if (message.role === 'user') {
169
183
  return {
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hubtype-api-client.js","sourceRoot":"","sources":["../../../src/services/hubtype-api-client.ts"],"names":[],"mappings":";;;;AAEA,0DAAyB;AAEzB,4CAA8C;AAc9C,MAAa,gBAAgB;IAG3B,YAAY,SAAiB;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;IAC5B,CAAC;IAED,KAAK,CAAC,qBAAqB,CACzB,KAAa,EACb,SAAmB;QAEnB,MAAM,GAAG,GAAG,GAAG,2BAAe,gDAAgD,CAAA;QAC9E,MAAM,OAAO,GAAG;YACd,cAAc,EAAE,kBAAkB;YAClC,aAAa,EAAE,UAAU,IAAI,CAAC,SAAS,EAAE;SAC1C,CAAA;QACD,MAAM,MAAM,GAAG;YACb,KAAK;YACL,UAAU,EAAE,SAAS;YACrB,UAAU,EAAE,CAAC;SACd,CAAA;QACD,MAAM,QAAQ,GAAG,MAAM,eAAK,CAAC,IAAI,CAAC,G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,MAAM,GAAG,GAAG,GAAG,2BAAe,oCAAoC,KAAK,kBAAkB,CAAA;YACzF,MAAM,OAAO,GAAG;gBACd,cAAc,EAAE,kBAAkB;gBAClC,aAAa,EAAE,UAAU,IAAI,CAAC,SAAS,EAAE;aAC1C,CAAA;YACD,MAAM,eAAK,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,CAAC,CAAA;QAC1C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAA;QACnD,CAAC;IACH,CAAC;IAEO,aAAa,CAAC,OAAuB;QAC3C,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC5B,OAAO;gBACL,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,IAAI,EAAE,MAAM;aACb,CAAA;QACH,CAAC;aAAM,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;YACxC,OAAO;gBACL,IAAI,EAAE,WAAW;gBACjB,OAAO,EAAE;oBACP;wBACE,IAAI,EAAE,aAAa;wBACnB,IAAI,EAAE,OAAO,CAAC,OAAO;qBACtB;iBACF;gBACD,MAAM,EAAE,WAAW;aACpB,CAAA;QACH,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAA;QACzC,CAAC;IACH,CAAC;CACF;AA7ND,4CA6NC"}
@@ -0,0 +1,85 @@
1
+ import type { AgenticInputMessage } from '../types';
2
+ export declare enum TrackProductName {
3
+ AI_AGENT = "ai_agent"
4
+ }
5
+ export declare enum TrackFeature {
6
+ AI_AGENT_RUN = "ai_agent_run",
7
+ AI_AGENT_GUARDRAIL = "ai_agent_guardrail"
8
+ }
9
+ export interface LlmRunData {
10
+ inference_id: string;
11
+ is_test: boolean;
12
+ product_name: string;
13
+ deployment_name: string;
14
+ model_name: string;
15
+ feature: string;
16
+ api_version: string;
17
+ num_prompt_tokens: number;
18
+ num_completion_tokens: number;
19
+ duration_in_milliseconds: number;
20
+ temperature: number;
21
+ error: string | null;
22
+ }
23
+ export interface TrackLlmRunsData {
24
+ llm_runs: LlmRunData[];
25
+ }
26
+ interface HubtypeAssistantMessage {
27
+ role: 'assistant';
28
+ content: string;
29
+ }
30
+ interface HubtypeUserMessage {
31
+ role: 'user';
32
+ content: string;
33
+ }
34
+ export type HubtypeMessage = HubtypeAssistantMessage | HubtypeUserMessage;
35
+ interface HubtypeToolCall {
36
+ id: string;
37
+ type: 'function';
38
+ function: {
39
+ name: string;
40
+ arguments: string;
41
+ };
42
+ }
43
+ interface HubtypeUserMessageV2 {
44
+ role: 'user';
45
+ content: string | null;
46
+ }
47
+ export interface HubtypeAssistantMessageV2 {
48
+ role: 'assistant';
49
+ content: string | null;
50
+ tool_calls?: HubtypeToolCall[] | null;
51
+ }
52
+ export interface HubtypeToolMessageV2 {
53
+ role: 'tool';
54
+ content: string | null;
55
+ tool_call_id: string;
56
+ }
57
+ interface HubtypeSystemMessageV2 {
58
+ role: 'system';
59
+ content: string | null;
60
+ }
61
+ export type HubtypeMessageV2 = HubtypeUserMessageV2 | HubtypeAssistantMessageV2 | HubtypeToolMessageV2 | HubtypeSystemMessageV2;
62
+ export interface MessageHistoryResponseV2 {
63
+ messages: HubtypeMessageV2[];
64
+ conversation_id: string | null;
65
+ truncated: boolean;
66
+ }
67
+ export interface GetMessagesV2Options {
68
+ maxMessages?: number;
69
+ includeToolCalls?: boolean;
70
+ maxFullToolResults?: number;
71
+ debugMode?: boolean;
72
+ }
73
+ export interface GetMessagesV2Result {
74
+ messages: AgenticInputMessage[];
75
+ conversationId: string | null;
76
+ truncated: boolean;
77
+ }
78
+ export interface MessageHistoryV2Params {
79
+ last_message_id: string;
80
+ max_messages?: number;
81
+ include_tool_calls?: boolean;
82
+ max_full_tool_results?: number;
83
+ debug_mode?: boolean;
84
+ }
85
+ export {};
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TrackFeature = exports.TrackProductName = void 0;
4
+ var TrackProductName;
5
+ (function (TrackProductName) {
6
+ TrackProductName["AI_AGENT"] = "ai_agent";
7
+ })(TrackProductName || (exports.TrackProductName = TrackProductName = {}));
8
+ var TrackFeature;
9
+ (function (TrackFeature) {
10
+ TrackFeature["AI_AGENT_RUN"] = "ai_agent_run";
11
+ TrackFeature["AI_AGENT_GUARDRAIL"] = "ai_agent_guardrail";
12
+ })(TrackFeature || (exports.TrackFeature = TrackFeature = {}));
13
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/services/types.ts"],"names":[],"mappings":";;;AAEA,IAAY,gBAEX;AAFD,WAAY,gBAAgB;IAC1B,yCAAqB,CAAA;AACvB,CAAC,EAFW,gBAAgB,gCAAhB,gBAAgB,QAE3B;AAED,IAAY,YAGX;AAHD,WAAY,YAAY;IACtB,6CAA6B,CAAA;IAC7B,yDAAyC,CAAA;AAC3C,CAAC,EAHW,YAAY,4BAAZ,YAAY,QAGvB"}
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.retrieveKnowledge = void 0;
4
4
  const agents_1 = require("@openai/agents");
5
5
  const zod_1 = require("zod");
6
- const hubtype_api_client_1 = require("../hubtype-api-client");
6
+ const hubtype_api_client_1 = require("../services/hubtype-api-client");
7
7
  exports.retrieveKnowledge = (0, agents_1.tool)({
8
8
  name: 'retrieve_knowledge',
9
9
  description: 'Consult the knowledge base for information before answering. Use this tool to make sure the information you provide is faithful.',
@@ -1 +1 @@
1
- {"version":3,"file":"retrieve-knowledge.js","sourceRoot":"","sources":["../../../src/tools/retrieve-knowledge.ts"],"names":[],"mappings":";;;AAAA,2CAAsD;AACtD,6BAAuB;AAEvB,8DAAwD;AAG3C,QAAA,iBAAiB,GAAG,IAAA,aAAI,EAAC;IACpC,IAAI,EAAE,oBAAoB;IAC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C,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,4CAA4C,CAAC;KACzE,CAAC;IACF,OAAO,EAAE,KAAK,EACZ,KAAwB,EACxB,UAAgC,EACb,EAAE;QACrB,MAAM,OAAO,GAAG,UAAU,EAAE,OAAO,CAAA;QACnC,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAA;QACzB,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAA;QACxC,CAAC;QACD,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,CAAA;QACnC,MAAM,MAAM,GAAG,IAAI,qCAAgB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;QACtD,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,qBAAqB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;QACnE,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;QAElD,OAAO,CAAC,aAAa,GAAG;YACtB,KAAK;YACL,SAAS;YACT,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC;YACxC,UAAU;SACX,CAAA;QAED,OAAO,UAAU,CAAA;IACnB,CAAC;CACF,CAAC,CAAA"}
@@ -45,5 +45,12 @@ export interface PluginAiAgentOptions<TPlugins extends ResolvedPlugins = Resolve
45
45
  /** Enable debug logging for AI agent configuration and execution details. */
46
46
  enableDebug?: boolean;
47
47
  }
48
+ export interface ResultRawResponse {
49
+ usage: {
50
+ inputTokens: number;
51
+ outputTokens: number;
52
+ };
53
+ providerData?: Record<string, unknown>;
54
+ }
48
55
  export type AgenticInputMessage = AgentInputItem;
49
56
  export { AgenticOutputMessage, AiAgentArgs, GuardrailRule, InferenceResponse, RunResult, };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botonic/plugin-ai-agents",
3
- "version": "0.45.0-alpha.1",
3
+ "version": "0.46.0-alpha-3",
4
4
  "main": "./lib/cjs/index.js",
5
5
  "module": "./lib/esm/index.js",
6
6
  "description": "Use AI Agents to generate your contents",
@@ -14,12 +14,13 @@
14
14
  "format": "biome format --write src/ tests/"
15
15
  },
16
16
  "dependencies": {
17
- "@botonic/core": "^0.45.0-alpha.1",
17
+ "@botonic/core": "^0.46.0-alpha-3",
18
18
  "@openai/agents": "^0.3.9",
19
- "axios": "^1.13.2",
19
+ "axios": "^1.13.6",
20
20
  "openai": "^6.0.0",
21
21
  "uuid": "^10.0.0",
22
- "zod": "3.25.76"
22
+ "zod": "3.25.76",
23
+ "zod-to-json-schema": "^3.25.1"
23
24
  },
24
25
  "devDependencies": {
25
26
  "@types/uuid": "^10.0.0"
@@ -3,12 +3,13 @@ import {
3
3
  Agent,
4
4
  type AgentOutputType,
5
5
  type InputGuardrail,
6
- type ModelSettings,
7
6
  } from '@openai/agents'
8
7
 
9
- import { OPENAI_MODEL, OPENAI_PROVIDER } from './constants'
8
+ import { OPENAI_PROVIDER } from './constants'
10
9
  import type { DebugLogger } from './debug-logger'
11
10
  import { createInputGuardrail } from './guardrails'
11
+ import type { GuardrailTrackingContext } from './guardrails/input'
12
+ import type { LLMConfig } from './llm-config'
12
13
  import { OutputSchema } from './structured-output'
13
14
  import { mandatoryTools, retrieveKnowledge } from './tools'
14
15
  import type { AIAgent, Context, GuardrailRule, Tool } from './types'
@@ -24,7 +25,9 @@ interface AIAgentBuilderOptions<
24
25
  contactInfo: ContactInfo[]
25
26
  inputGuardrailRules: GuardrailRule[]
26
27
  sourceIds: string[]
28
+ llmConfig: LLMConfig
27
29
  logger: DebugLogger
30
+ guardrailTrackingContext: GuardrailTrackingContext
28
31
  }
29
32
 
30
33
  export class AIAgentBuilder<
@@ -35,6 +38,7 @@ export class AIAgentBuilder<
35
38
  private instructions: string
36
39
  private tools: Tool<TPlugins, TExtraData>[]
37
40
  private inputGuardrails: InputGuardrail[]
41
+ public llmConfig: LLMConfig
38
42
  private logger: DebugLogger
39
43
 
40
44
  constructor(options: AIAgentBuilderOptions<TPlugins, TExtraData>) {
@@ -46,35 +50,35 @@ export class AIAgentBuilder<
46
50
  )
47
51
  this.tools = this.addHubtypeTools(options.tools, options.sourceIds)
48
52
  this.inputGuardrails = []
53
+ this.llmConfig = options.llmConfig
49
54
  this.logger = options.logger
50
55
  if (options.inputGuardrailRules.length > 0) {
51
- const inputGuardrail = createInputGuardrail(options.inputGuardrailRules)
56
+ const inputGuardrail = createInputGuardrail(
57
+ options.inputGuardrailRules,
58
+ options.llmConfig,
59
+ options.guardrailTrackingContext
60
+ )
52
61
  this.inputGuardrails.push(inputGuardrail)
53
62
  }
54
63
  }
55
64
 
56
65
  build(): AIAgent<TPlugins, TExtraData> {
57
- const modelSettings: ModelSettings = {} as ModelSettings
58
- if (OPENAI_PROVIDER === 'openai') {
59
- modelSettings.reasoning = { effort: 'none' }
60
- modelSettings.text = { verbosity: 'medium' }
61
- }
62
-
63
- const hasRetrieveKnowledge = this.tools.includes(retrieveKnowledge)
64
- if (hasRetrieveKnowledge && OPENAI_PROVIDER === 'azure') {
65
- modelSettings.toolChoice = retrieveKnowledge.name
66
- }
67
-
68
66
  // When using standard OpenAI API, we need to specify the model
69
67
  // Azure OpenAI uses deployment name instead
70
- const model = OPENAI_PROVIDER === 'openai' ? OPENAI_MODEL : undefined
68
+
69
+ const model = this.llmConfig.modelName
70
+ const hasRetrieveKnowledge = this.tools.includes(retrieveKnowledge)
71
71
 
72
72
  this.logger.logModelSettings({
73
73
  provider: OPENAI_PROVIDER,
74
74
  model,
75
- reasoning: modelSettings.reasoning as { effort: string } | undefined,
76
- text: modelSettings.text as { verbosity: string } | undefined,
77
- toolChoice: modelSettings.toolChoice as string | undefined,
75
+ reasoning: this.llmConfig.modelSettings.reasoning as
76
+ | { effort: string }
77
+ | undefined,
78
+ text: this.llmConfig.modelSettings.text as
79
+ | { verbosity: string }
80
+ | undefined,
81
+ toolChoice: this.llmConfig.modelSettings.toolChoice as string | undefined,
78
82
  hasRetrieveKnowledge,
79
83
  })
80
84
 
@@ -89,7 +93,6 @@ export class AIAgentBuilder<
89
93
  outputType: OutputSchema,
90
94
  inputGuardrails: this.inputGuardrails,
91
95
  outputGuardrails: [],
92
- modelSettings,
93
96
  })
94
97
  }
95
98
 
@@ -0,0 +1,21 @@
1
+ import type { ToolConfigJSON } from '@botonic/core'
2
+ import { zodToJsonSchema } from 'zod-to-json-schema'
3
+
4
+ import type { CustomTool } from './types'
5
+
6
+ /**
7
+ * Maps custom AI agent tools to the format expected by bot config (e.g. for flow-builder).
8
+ * Converts each tool's Zod schema to JSON Schema so it can be serialized in the config.
9
+ */
10
+ export function getToolsForBotConfig(
11
+ customTools: CustomTool[]
12
+ ): ToolConfigJSON[] {
13
+ return customTools.map(tool => ({
14
+ name: tool.name,
15
+ description: tool.description,
16
+ // Cast to avoid TS "Type instantiation is excessively deep" with zodToJsonSchema + ZodSchema
17
+ schema: zodToJsonSchema(tool.schema as never, {
18
+ $refStrategy: 'none',
19
+ }) as ToolConfigJSON['schema'],
20
+ }))
21
+ }
package/src/constants.ts CHANGED
@@ -10,11 +10,12 @@ export const OPENAI_PROVIDER: 'openai' | 'azure' =
10
10
  // Azure OpenAI Configuration
11
11
  export const AZURE_OPENAI_API_KEY = process.env.AZURE_OPENAI_API_KEY // pragma: allowlist secret
12
12
  export const AZURE_OPENAI_API_BASE = process.env.AZURE_OPENAI_API_BASE
13
- export const AZURE_OPENAI_API_DEPLOYMENT_NAME =
14
- process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME || 'gpt-41-mini_p1'
15
13
  export const AZURE_OPENAI_API_VERSION =
16
14
  process.env.AZURE_OPENAI_API_VERSION || '2025-01-01-preview'
17
15
 
18
16
  export const isProd = process.env.NODE_ENV === 'production'
19
17
 
20
18
  export const MAX_MEMORY_LENGTH = 25
19
+
20
+ export const DEFAULT_TIMEOUT_16_SECONDS = 16000
21
+ export const DEFAULT_MAX_RETRIES = 2
@@ -1,12 +1,6 @@
1
- import type { AiAgentArgs } from '@botonic/core'
2
-
3
- import {
4
- AZURE_OPENAI_API_BASE,
5
- AZURE_OPENAI_API_DEPLOYMENT_NAME,
6
- MAX_MEMORY_LENGTH,
7
- OPENAI_MODEL,
8
- OPENAI_PROVIDER,
9
- } from './constants'
1
+ import type { AiAgentArgs, ToolExecution } from '@botonic/core'
2
+ import type { ModelSettings } from '@openai/agents'
3
+ import { MAX_MEMORY_LENGTH, OPENAI_PROVIDER } from './constants'
10
4
  import type { AgenticInputMessage, MemoryOptions, RunResult } from './types'
11
5
 
12
6
  const PREFIX = '[BotonicPluginAiAgents]'
@@ -36,32 +30,17 @@ export interface DebugLogger {
36
30
  messages: AgenticInputMessage[]
37
31
  ): void
38
32
  logModelSettings(settings: ModelSettingsInfo): void
39
- logRunnerStart(): void
33
+ logRunnerStart(model: string, modelSettings: ModelSettings): void
40
34
  logRunResult(runResult: RunResult, startTime: number): void
41
35
  logGuardrailTriggered(): void
42
36
  logRunnerError(startTime: number, error: unknown): void
37
+ logToolExecution(toolExecution: ToolExecution): void
43
38
  }
44
39
 
45
40
  class EnabledDebugLogger implements DebugLogger {
46
- private getModelInfo(): { model: string; apiBase: string } {
47
- const model =
48
- OPENAI_PROVIDER === 'azure'
49
- ? AZURE_OPENAI_API_DEPLOYMENT_NAME
50
- : OPENAI_MODEL
51
- const apiBase =
52
- OPENAI_PROVIDER === 'azure' && AZURE_OPENAI_API_BASE
53
- ? AZURE_OPENAI_API_BASE
54
- : 'OpenAI API'
55
- return { model, apiBase }
56
- }
57
-
58
41
  logInitialConfig(config: DebugLoggerConfig): void {
59
- const { model, apiBase } = this.getModelInfo()
60
-
61
42
  console.log(`${PREFIX} === Plugin Initialization ===`)
62
43
  console.log(`${PREFIX} Provider: ${OPENAI_PROVIDER}`)
63
- console.log(`${PREFIX} Model/Deployment: ${model}`)
64
- console.log(`${PREFIX} API Base: ${apiBase}`)
65
44
  console.log(
66
45
  `${PREFIX} Message History API Version: ${config.messageHistoryApiVersion}`
67
46
  )
@@ -116,8 +95,10 @@ class EnabledDebugLogger implements DebugLogger {
116
95
  console.log(`${PREFIX} === End Model Settings ===`)
117
96
  }
118
97
 
119
- logRunnerStart(): void {
98
+ logRunnerStart(model: string, modelSettings: ModelSettings): void {
120
99
  console.log(`${PREFIX} === Runner Execution Start ===`)
100
+ console.log(`${PREFIX} Model: ${model}`)
101
+ console.log(`${PREFIX} Model Settings: ${JSON.stringify(modelSettings)}`)
121
102
  }
122
103
 
123
104
  logRunResult(runResult: RunResult, startTime: number): void {
@@ -153,16 +134,31 @@ class EnabledDebugLogger implements DebugLogger {
153
134
  console.log(`${PREFIX} Runner execution failed after ${elapsedMs}ms`)
154
135
  console.log(`${PREFIX} Error:`, error)
155
136
  }
137
+
138
+ logToolExecution(toolExecution: ToolExecution): void {
139
+ console.log(`${PREFIX} Tool Execution: ${toolExecution.toolName}`)
140
+ console.log(
141
+ `${PREFIX} Tool Arguments: ${JSON.stringify(toolExecution.toolArguments)}`
142
+ )
143
+ console.log(`${PREFIX} Tool Results: ${toolExecution.toolResults}`)
144
+ console.log(
145
+ `${PREFIX} Knowledgebase Sources IDs: ${JSON.stringify(toolExecution.knowledgebaseSourcesIds)}`
146
+ )
147
+ console.log(
148
+ `${PREFIX} Knowledgebase Chunks IDs: ${JSON.stringify(toolExecution.knowledgebaseChunksIds)}`
149
+ )
150
+ }
156
151
  }
157
152
 
158
153
  class DisabledDebugLogger implements DebugLogger {
159
154
  logInitialConfig(): void {}
160
155
  logAgentDebugInfo(): void {}
161
156
  logModelSettings(): void {}
162
- logRunnerStart(): void {}
157
+ logRunnerStart(_model: string, _modelSettings: ModelSettings): void {}
163
158
  logRunResult(): void {}
164
159
  logGuardrailTriggered(): void {}
165
160
  logRunnerError(): void {}
161
+ logToolExecution(): void {}
166
162
  }
167
163
 
168
164
  export function createDebugLogger(enableDebug: boolean): DebugLogger {
@@ -1,14 +1,28 @@
1
1
  import {
2
2
  Agent,
3
3
  type InputGuardrail,
4
- run,
4
+ Runner,
5
5
  type UserMessageItem,
6
6
  } from '@openai/agents'
7
7
  import { z } from 'zod'
8
+ import { AZURE_OPENAI_API_VERSION, isProd, OPENAI_PROVIDER } from '../constants'
9
+ import type { LLMConfig } from '../llm-config'
10
+ import { HubtypeApiClient } from '../services/hubtype-api-client'
11
+ import { TrackFeature, TrackProductName } from '../services/types'
12
+ import type { GuardrailRule, ResultRawResponse } from '../types'
8
13
 
9
- import type { GuardrailRule } from '../types'
14
+ export interface GuardrailTrackingContext {
15
+ botId: string
16
+ isTest: boolean
17
+ authToken: string
18
+ inferenceId: string
19
+ }
10
20
 
11
- export function createInputGuardrail(rules: GuardrailRule[]): InputGuardrail {
21
+ export function createInputGuardrail(
22
+ rules: GuardrailRule[],
23
+ llmConfig: LLMConfig,
24
+ trackingContext: GuardrailTrackingContext
25
+ ): InputGuardrail {
12
26
  const outputType = z.object(
13
27
  Object.fromEntries(
14
28
  rules.map(rule => [rule.name, z.boolean().describe(rule.description)])
@@ -26,7 +40,26 @@ export function createInputGuardrail(rules: GuardrailRule[]): InputGuardrail {
26
40
  name: 'InputGuardrail',
27
41
  execute: async ({ input, context }) => {
28
42
  const lastMessage = input[input.length - 1] as UserMessageItem
29
- const result = await run(agent, [lastMessage], { context })
43
+ const modelProvider = llmConfig.modelProvider
44
+ const modelSettings = llmConfig.modelSettings
45
+ modelSettings.toolChoice = undefined
46
+ const runner = new Runner({
47
+ modelSettings,
48
+ modelProvider,
49
+ tracingDisabled: true,
50
+ })
51
+ const startTime = Date.now()
52
+ const result = await runner.run(agent, [lastMessage], { context })
53
+ const endTime = Date.now()
54
+
55
+ void sendGuardrailLlmRunTracking(
56
+ result,
57
+ trackingContext,
58
+ llmConfig,
59
+ startTime,
60
+ endTime
61
+ )
62
+
30
63
  const finalOutput = result.finalOutput as Record<string, boolean>
31
64
  if (finalOutput === undefined) {
32
65
  throw new Error('Guardrail agent failed to produce output')
@@ -42,3 +75,48 @@ export function createInputGuardrail(rules: GuardrailRule[]): InputGuardrail {
42
75
  },
43
76
  }
44
77
  }
78
+
79
+ async function sendGuardrailLlmRunTracking(
80
+ result: {
81
+ rawResponses?: ResultRawResponse[]
82
+ },
83
+ trackingContext: GuardrailTrackingContext,
84
+ llmConfig: LLMConfig,
85
+ startTime: number,
86
+ endTime: number
87
+ ): Promise<void> {
88
+ if (!isProd) {
89
+ return
90
+ }
91
+ const rawResponses = result.rawResponses ?? []
92
+ if (rawResponses.length === 0) {
93
+ return
94
+ }
95
+ const totalDuration = endTime - startTime
96
+ const durationPerCall = Math.round(totalDuration / rawResponses.length)
97
+ const temperature =
98
+ (llmConfig.modelSettings.temperature as number | undefined) ?? 0
99
+ const apiVersion = OPENAI_PROVIDER === 'azure' ? AZURE_OPENAI_API_VERSION : ''
100
+
101
+ const llmRuns = rawResponses.map(response => ({
102
+ inference_id: trackingContext.inferenceId,
103
+ is_test: trackingContext.isTest,
104
+ product_name: TrackProductName.AI_AGENT,
105
+ deployment_name: llmConfig.modelName,
106
+ model_name:
107
+ (response.providerData?.['model'] as string | undefined) ??
108
+ llmConfig.modelName,
109
+ feature: TrackFeature.AI_AGENT_GUARDRAIL,
110
+ api_version: apiVersion,
111
+ num_prompt_tokens: response.usage.inputTokens,
112
+ num_completion_tokens: response.usage.outputTokens,
113
+ duration_in_milliseconds: durationPerCall,
114
+ temperature,
115
+ error: null,
116
+ }))
117
+
118
+ const client = new HubtypeApiClient(trackingContext.authToken)
119
+ await client.trackLlmRuns(trackingContext.botId, {
120
+ llm_runs: llmRuns,
121
+ })
122
+ }