@base44-preview/sdk 0.8.34-pr.205.d800012 → 0.8.34-pr.209.1deec07
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.
- package/dist/client.js +1 -3
- package/dist/client.types.d.ts +1 -1
- package/dist/index.d.ts +2 -4
- package/dist/index.js +1 -2
- package/dist/modules/{agents/index.d.ts → agents.d.ts} +1 -1
- package/dist/modules/{agents/index.js → agents.js} +2 -10
- package/dist/modules/{agents/agents.types.d.ts → agents.types.d.ts} +2 -336
- package/dist/modules/entities.js +1 -58
- package/dist/modules/entities.types.d.ts +0 -20
- package/dist/modules/functions.js +31 -45
- package/dist/modules/functions.types.d.ts +0 -28
- package/dist/modules/types.d.ts +1 -1
- package/dist/modules/types.js +1 -1
- package/dist/utils/axios-client.js +11 -1
- package/package.json +1 -1
- package/dist/modules/agents/gateway.d.ts +0 -34
- package/dist/modules/agents/gateway.js +0 -41
- package/dist/modules/agents/loop.d.ts +0 -4
- package/dist/modules/agents/loop.js +0 -146
- package/dist/modules/agents/provider.d.ts +0 -53
- package/dist/modules/agents/provider.js +0 -1
- package/dist/modules/agents/providers/openai-compatible.d.ts +0 -8
- package/dist/modules/agents/providers/openai-compatible.js +0 -110
- package/dist/modules/agents/tool.d.ts +0 -37
- package/dist/modules/agents/tool.js +0 -38
- /package/dist/modules/{agents/agents.types.js → agents.types.js} +0 -0
package/dist/client.js
CHANGED
|
@@ -6,7 +6,7 @@ import { createSsoModule } from "./modules/sso.js";
|
|
|
6
6
|
import { createConnectorsModule, createUserConnectorsModule, } from "./modules/connectors.js";
|
|
7
7
|
import { getAccessToken } from "./utils/auth-utils.js";
|
|
8
8
|
import { createFunctionsModule } from "./modules/functions.js";
|
|
9
|
-
import { createAgentsModule } from "./modules/agents
|
|
9
|
+
import { createAgentsModule } from "./modules/agents.js";
|
|
10
10
|
import { createAppLogsModule } from "./modules/app-logs.js";
|
|
11
11
|
import { createUsersModule } from "./modules/users.js";
|
|
12
12
|
import { RoomsSocket } from "./utils/socket-utils.js";
|
|
@@ -149,7 +149,6 @@ export function createClient(config) {
|
|
|
149
149
|
appId,
|
|
150
150
|
serverUrl,
|
|
151
151
|
token,
|
|
152
|
-
getToken: () => token || getAccessToken() || undefined,
|
|
153
152
|
}),
|
|
154
153
|
appLogs: createAppLogsModule(axiosClient, appId),
|
|
155
154
|
users: createUsersModule(axiosClient, appId),
|
|
@@ -192,7 +191,6 @@ export function createClient(config) {
|
|
|
192
191
|
appId,
|
|
193
192
|
serverUrl,
|
|
194
193
|
token,
|
|
195
|
-
getToken: () => serviceToken,
|
|
196
194
|
}),
|
|
197
195
|
appLogs: createAppLogsModule(serviceRoleAxiosClient, appId),
|
|
198
196
|
cleanup: () => {
|
package/dist/client.types.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { AuthModule } from "./modules/auth.types.js";
|
|
|
4
4
|
import type { SsoModule } from "./modules/sso.types.js";
|
|
5
5
|
import type { ConnectorsModule, UserConnectorsModule } from "./modules/connectors.types.js";
|
|
6
6
|
import type { FunctionsModule } from "./modules/functions.types.js";
|
|
7
|
-
import type { AgentsModule } from "./modules/agents
|
|
7
|
+
import type { AgentsModule } from "./modules/agents.types.js";
|
|
8
8
|
import type { AppLogsModule } from "./modules/app-logs.types.js";
|
|
9
9
|
import type { AnalyticsModule } from "./modules/analytics.types.js";
|
|
10
10
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -1,18 +1,16 @@
|
|
|
1
1
|
import { createClient, createClientFromRequest, type Base44Client, type CreateClientConfig, type CreateClientOptions } from "./client.js";
|
|
2
2
|
import { Base44Error, type Base44ErrorJSON } from "./utils/axios-client.js";
|
|
3
3
|
import { getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl } from "./utils/auth-utils.js";
|
|
4
|
-
|
|
5
|
-
export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, tool, };
|
|
4
|
+
export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, };
|
|
6
5
|
export type { Base44Client, CreateClientConfig, CreateClientOptions, Base44ErrorJSON, };
|
|
7
6
|
export * from "./types.js";
|
|
8
7
|
export type { DeleteManyResult, DeleteResult, EntitiesModule, EntityFilterOperators, EntityFilterQuery, EntityFilterValue, EntityHandler, EntityRecord, EntityTypeRegistry, ImportResult, RealtimeEventType, RealtimeEvent, RealtimeCallback, SortField, UpdateManyResult, } from "./modules/entities.types.js";
|
|
9
8
|
export type { AuthModule, LoginResponse, RegisterParams, VerifyOtpParams, ChangePasswordParams, ResetPasswordParams, User, } from "./modules/auth.types.js";
|
|
10
9
|
export type { IntegrationsModule, IntegrationEndpointFunction, CoreIntegrations, InvokeLLMParams, GenerateImageParams, GenerateImageResult, UploadFileParams, UploadFileResult, SendEmailParams, SendEmailResult, ExtractDataFromUploadedFileParams, ExtractDataFromUploadedFileResult, UploadPrivateFileParams, UploadPrivateFileResult, CreateFileSignedUrlParams, CreateFileSignedUrlResult, } from "./modules/integrations.types.js";
|
|
11
10
|
export type { FunctionsModule, FunctionName, FunctionNameRegistry, } from "./modules/functions.types.js";
|
|
12
|
-
export type { AgentsModule, AgentName, AgentNameRegistry, AgentConversation, AgentMessage, AgentMessageReasoning, AgentMessageToolCall, AgentMessageUsage, AgentMessageCustomContext, AgentMessageMetadata, CreateConversationParams, } from "./modules/agents
|
|
11
|
+
export type { AgentsModule, AgentName, AgentNameRegistry, AgentConversation, AgentMessage, AgentMessageReasoning, AgentMessageToolCall, AgentMessageUsage, AgentMessageCustomContext, AgentMessageMetadata, CreateConversationParams, } from "./modules/agents.types.js";
|
|
13
12
|
export type { AppLogsModule } from "./modules/app-logs.types.js";
|
|
14
13
|
export type { SsoModule, SsoAccessTokenResponse } from "./modules/sso.types.js";
|
|
15
14
|
export type { ConnectorsModule, UserConnectorsModule, } from "./modules/connectors.types.js";
|
|
16
15
|
export type { CustomIntegrationsModule, CustomIntegrationCallParams, CustomIntegrationCallResponse, } from "./modules/custom-integrations.types.js";
|
|
17
|
-
export type { Tool, JSONSchema, ChatMessage, Step, RunUsage, RunResult, RunInput, RunOptions, ToolChoice, AgentConfig, Agent, FinishReason, } from "./modules/agents/agents.types.js";
|
|
18
16
|
export type { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions, GetLoginUrlOptions, } from "./utils/auth-utils.types.js";
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { createClient, createClientFromRequest, } from "./client.js";
|
|
2
2
|
import { Base44Error } from "./utils/axios-client.js";
|
|
3
3
|
import { getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, } from "./utils/auth-utils.js";
|
|
4
|
-
|
|
5
|
-
export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, tool, };
|
|
4
|
+
export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, };
|
|
6
5
|
export * from "./types.js";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { AgentsModule, AgentsModuleConfig } from "./agents.types.js";
|
|
2
|
-
export declare function createAgentsModule({ axios, getSocket, appId, serverUrl, token,
|
|
2
|
+
export declare function createAgentsModule({ axios, getSocket, appId, serverUrl, token, }: AgentsModuleConfig): AgentsModule;
|
|
@@ -1,12 +1,5 @@
|
|
|
1
|
-
import { getAccessToken } from "
|
|
2
|
-
|
|
3
|
-
import { openAICompatibleProvider } from "./providers/openai-compatible.js";
|
|
4
|
-
import { createAgent } from "./loop.js";
|
|
5
|
-
export function createAgentsModule({ axios, getSocket, appId, serverUrl, token, getToken, }) {
|
|
6
|
-
const model = openAICompatibleProvider(createGatewayTransport({
|
|
7
|
-
serverUrl: serverUrl !== null && serverUrl !== void 0 ? serverUrl : "",
|
|
8
|
-
getToken: getToken !== null && getToken !== void 0 ? getToken : (() => token),
|
|
9
|
-
}));
|
|
1
|
+
import { getAccessToken } from "../utils/auth-utils.js";
|
|
2
|
+
export function createAgentsModule({ axios, getSocket, appId, serverUrl, token, }) {
|
|
10
3
|
const baseURL = `/apps/${appId}/agents`;
|
|
11
4
|
// Track active conversations
|
|
12
5
|
const currentConversations = {};
|
|
@@ -92,6 +85,5 @@ export function createAgentsModule({ axios, getSocket, appId, serverUrl, token,
|
|
|
92
85
|
subscribeToConversation,
|
|
93
86
|
getWhatsAppConnectURL,
|
|
94
87
|
getTelegramConnectURL,
|
|
95
|
-
create(config) { return createAgent(config, model); },
|
|
96
88
|
};
|
|
97
89
|
}
|
|
@@ -1,317 +1,6 @@
|
|
|
1
1
|
import { AxiosInstance } from "axios";
|
|
2
|
-
import { RoomsSocket } from "
|
|
3
|
-
import { ModelFilterParams } from "
|
|
4
|
-
/**
|
|
5
|
-
* A JSON Schema object describing a tool's input parameters.
|
|
6
|
-
* Use the standard JSON Schema `object` shape: `{ type: "object", properties: {...}, required: [...] }`.
|
|
7
|
-
*/
|
|
8
|
-
export type JSONSchema = Record<string, unknown>;
|
|
9
|
-
/**
|
|
10
|
-
* A tool an agent can call. Create one with {@linkcode tool | tool()}, or derive it from a
|
|
11
|
-
* resource with `.asTool()`.
|
|
12
|
-
*/
|
|
13
|
-
export interface Tool {
|
|
14
|
-
/** Natural-language description the model uses to decide when to call the tool. */
|
|
15
|
-
description: string;
|
|
16
|
-
/** JSON Schema for the tool's arguments. */
|
|
17
|
-
parameters: JSONSchema;
|
|
18
|
-
/** Runs the tool. Receives parsed arguments; returns any JSON-serializable value (or a string). */
|
|
19
|
-
execute: (args: any) => Promise<unknown> | unknown;
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* Why the agent run ended.
|
|
23
|
-
* `"max_steps"` is set by the SDK when the step cap is hit; all other values come from the model/normalization layer.
|
|
24
|
-
*/
|
|
25
|
-
export type FinishReason = "stop" | "length" | "tool-calls" | "content-filter" | "error" | "other";
|
|
26
|
-
/** An OpenAI-shaped chat message accepted by {@linkcode Agent.run}. */
|
|
27
|
-
export interface ChatMessage {
|
|
28
|
-
role: "system" | "user" | "assistant" | "tool";
|
|
29
|
-
content?: string | null;
|
|
30
|
-
tool_calls?: Array<{
|
|
31
|
-
id: string;
|
|
32
|
-
type: "function";
|
|
33
|
-
function: {
|
|
34
|
-
name: string;
|
|
35
|
-
arguments: string;
|
|
36
|
-
};
|
|
37
|
-
}>;
|
|
38
|
-
tool_call_id?: string;
|
|
39
|
-
}
|
|
40
|
-
/** One iteration of the agent loop: the tool calls the model made and their results. */
|
|
41
|
-
export interface Step {
|
|
42
|
-
toolResults: Array<{
|
|
43
|
-
toolCallId: string;
|
|
44
|
-
toolName: string;
|
|
45
|
-
args: unknown;
|
|
46
|
-
result: string;
|
|
47
|
-
}>;
|
|
48
|
-
/** Token/credit usage of the model call that produced this step's tool calls. */
|
|
49
|
-
usage?: RunUsage;
|
|
50
|
-
}
|
|
51
|
-
/** Token/credit usage for a single model call or a sum across calls. `credits` is the Base44 gateway's `base44_credits`. */
|
|
52
|
-
export interface RunUsage {
|
|
53
|
-
inputTokens?: number;
|
|
54
|
-
outputTokens?: number;
|
|
55
|
-
totalTokens?: number;
|
|
56
|
-
credits?: number;
|
|
57
|
-
}
|
|
58
|
-
/** Result of {@linkcode Agent.run}. */
|
|
59
|
-
export interface RunResult {
|
|
60
|
-
/** The model's final text output. */
|
|
61
|
-
text: string;
|
|
62
|
-
/** The loop history (one entry per step that made tool calls). */
|
|
63
|
-
steps: Step[];
|
|
64
|
-
/**
|
|
65
|
-
* Why the run ended.
|
|
66
|
-
* Values come from the model/normalization layer (`"stop"`, `"length"`, `"tool-calls"`, `"content-filter"`, `"error"`, `"other"`)
|
|
67
|
-
* or from the SDK itself (`"max_steps"`, set when the step cap is reached).
|
|
68
|
-
*/
|
|
69
|
-
finishReason: FinishReason | "max_steps";
|
|
70
|
-
/** Token and credit usage from the final completion. */
|
|
71
|
-
usage: RunUsage;
|
|
72
|
-
/** Summed across all model calls in the loop; `usage` is the final call only. */
|
|
73
|
-
totalUsage: RunUsage;
|
|
74
|
-
/** The raw final completion body, for advanced use. */
|
|
75
|
-
raw: unknown;
|
|
76
|
-
}
|
|
77
|
-
/** Input to {@linkcode Agent.run}: either a single prompt or a full message list. */
|
|
78
|
-
export type RunInput = {
|
|
79
|
-
prompt: string;
|
|
80
|
-
} | {
|
|
81
|
-
messages: ChatMessage[];
|
|
82
|
-
};
|
|
83
|
-
/**
|
|
84
|
-
* Per-run options passed as the second argument to {@linkcode Agent.run}.
|
|
85
|
-
*
|
|
86
|
-
* @example
|
|
87
|
-
* ```typescript
|
|
88
|
-
* const controller = new AbortController();
|
|
89
|
-
* setTimeout(() => controller.abort(), 10_000);
|
|
90
|
-
*
|
|
91
|
-
* const result = await agent.run(
|
|
92
|
-
* { prompt: "Summarize last month's sales." },
|
|
93
|
-
* { abortSignal: controller.signal },
|
|
94
|
-
* );
|
|
95
|
-
* ```
|
|
96
|
-
*/
|
|
97
|
-
export interface RunOptions {
|
|
98
|
-
/** Abort the run (and the in-flight gateway request). */
|
|
99
|
-
abortSignal?: AbortSignal;
|
|
100
|
-
}
|
|
101
|
-
/** OpenAI-compatible tool choice. */
|
|
102
|
-
export type ToolChoice = "auto" | "none" | "required" | {
|
|
103
|
-
type: "function";
|
|
104
|
-
function: {
|
|
105
|
-
name: string;
|
|
106
|
-
};
|
|
107
|
-
};
|
|
108
|
-
/**
|
|
109
|
-
* Configuration for a code-defined agent passed to {@linkcode AgentsModule.create}.
|
|
110
|
-
*
|
|
111
|
-
* @example
|
|
112
|
-
* ```typescript
|
|
113
|
-
* const agent = base44.agents.create({
|
|
114
|
-
* model: "claude_sonnet_4_6",
|
|
115
|
-
* system: "You are a concise travel planner.",
|
|
116
|
-
* tools: { getWeather, searchFlights },
|
|
117
|
-
* maxSteps: 5,
|
|
118
|
-
* });
|
|
119
|
-
* ```
|
|
120
|
-
*/
|
|
121
|
-
export interface AgentConfig {
|
|
122
|
-
/**
|
|
123
|
-
* Model alias or vendor model ID to use for this agent.
|
|
124
|
-
*
|
|
125
|
-
* Use a Base44 model alias (e.g. `"claude_sonnet_4_6"`, `"gpt_4o"`, `"gpt_5_mini"`) or a
|
|
126
|
-
* fully-qualified vendor ID. Available aliases are listed in the Base44 console.
|
|
127
|
-
*/
|
|
128
|
-
model: string;
|
|
129
|
-
/**
|
|
130
|
-
* System prompt prepended to every run.
|
|
131
|
-
*
|
|
132
|
-
* Provide instructions, persona, or constraints for the model.
|
|
133
|
-
* Omit to let the model run without a system message.
|
|
134
|
-
*/
|
|
135
|
-
system?: string;
|
|
136
|
-
/**
|
|
137
|
-
* Tools the agent may call, keyed by their function name.
|
|
138
|
-
*
|
|
139
|
-
* Each value must be a {@linkcode Tool} object — use the {@linkcode tool | tool()} factory
|
|
140
|
-
* to create one, or use `.asTool()` on a resource such as an entity or function.
|
|
141
|
-
*
|
|
142
|
-
* @example
|
|
143
|
-
* ```typescript
|
|
144
|
-
* import { tool } from "@base44/sdk";
|
|
145
|
-
*
|
|
146
|
-
* const getWeather = tool({
|
|
147
|
-
* description: "Get the current weather for a city.",
|
|
148
|
-
* parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
|
|
149
|
-
* execute: async ({ city }) => fetch(`/weather?city=${city}`).then(r => r.json()),
|
|
150
|
-
* });
|
|
151
|
-
*
|
|
152
|
-
* const agent = base44.agents.create({ model: "claude_sonnet_4_6", tools: { getWeather } });
|
|
153
|
-
* ```
|
|
154
|
-
*/
|
|
155
|
-
tools?: Record<string, Tool>;
|
|
156
|
-
/**
|
|
157
|
-
* Maximum number of tool-calling loop iterations before the run stops.
|
|
158
|
-
*
|
|
159
|
-
* Each iteration is one round-trip to the model. If the model keeps calling tools
|
|
160
|
-
* and this limit is reached, the run ends with `finishReason: "max_steps"`.
|
|
161
|
-
* Defaults to `8`.
|
|
162
|
-
*/
|
|
163
|
-
maxSteps?: number;
|
|
164
|
-
/**
|
|
165
|
-
* Sampling temperature passed to the model.
|
|
166
|
-
*
|
|
167
|
-
* Controls output randomness: lower values (e.g. `0`) produce more deterministic
|
|
168
|
-
* responses; higher values (e.g. `1`) increase variety. Omit to use the model default.
|
|
169
|
-
*
|
|
170
|
-
* Note: GPT-5 series models only accept `temperature: 1`.
|
|
171
|
-
*/
|
|
172
|
-
temperature?: number;
|
|
173
|
-
/**
|
|
174
|
-
* JSON Schema to constrain the model's output to structured JSON.
|
|
175
|
-
*
|
|
176
|
-
* When set, the request is sent with `response_format: { type: "json_schema", … }`.
|
|
177
|
-
* The model's response will be valid JSON matching the schema; access it by parsing
|
|
178
|
-
* `RunResult.text`.
|
|
179
|
-
* The schema is sent with strict JSON-schema mode, so it should have `additionalProperties: false` and list every property in `required` (otherwise the provider may reject it).
|
|
180
|
-
*
|
|
181
|
-
* @example
|
|
182
|
-
* ```typescript
|
|
183
|
-
* const agent = base44.agents.create({
|
|
184
|
-
* model: "claude_sonnet_4_6",
|
|
185
|
-
* responseFormat: {
|
|
186
|
-
* type: "object",
|
|
187
|
-
* properties: { summary: { type: "string" }, score: { type: "number" } },
|
|
188
|
-
* required: ["summary", "score"],
|
|
189
|
-
* },
|
|
190
|
-
* });
|
|
191
|
-
* const { text } = await agent.run({ prompt: "Rate this product description." });
|
|
192
|
-
* const { summary, score } = JSON.parse(text);
|
|
193
|
-
* ```
|
|
194
|
-
*/
|
|
195
|
-
responseFormat?: JSONSchema;
|
|
196
|
-
/**
|
|
197
|
-
* Controls whether and which tool the model must call.
|
|
198
|
-
*
|
|
199
|
-
* - `"auto"` (default when tools are provided): the model decides.
|
|
200
|
-
* - `"none"`: the model must not call any tool.
|
|
201
|
-
* - `"required"`: the model must call at least one tool.
|
|
202
|
-
* - `{ type: "function", function: { name } }`: force a specific tool.
|
|
203
|
-
*/
|
|
204
|
-
toolChoice?: ToolChoice;
|
|
205
|
-
}
|
|
206
|
-
/**
|
|
207
|
-
* A reusable code-defined agent returned by {@linkcode AgentsModule.create}.
|
|
208
|
-
*
|
|
209
|
-
* An agent runs a multi-step tool-calling loop: it sends messages to the model,
|
|
210
|
-
* executes any tool calls the model requests, feeds the results back, and repeats
|
|
211
|
-
* until the model produces a final answer or `maxSteps` is reached.
|
|
212
|
-
*
|
|
213
|
-
* @example
|
|
214
|
-
* ```typescript
|
|
215
|
-
* const agent = base44.agents.create({
|
|
216
|
-
* model: "claude_sonnet_4_6",
|
|
217
|
-
* system: "You are a concise travel planner.",
|
|
218
|
-
* tools: { getWeather },
|
|
219
|
-
* });
|
|
220
|
-
*
|
|
221
|
-
* const { text } = await agent.run({ prompt: "What's the weather like in Tel Aviv?" });
|
|
222
|
-
* console.log(text);
|
|
223
|
-
* ```
|
|
224
|
-
*/
|
|
225
|
-
export interface Agent {
|
|
226
|
-
/**
|
|
227
|
-
* Runs the agent's tool-calling loop to completion and returns the final result.
|
|
228
|
-
*
|
|
229
|
-
* Builds an initial message list from `input`, then repeatedly calls the model,
|
|
230
|
-
* executes any tool calls, and feeds results back until the model stops or
|
|
231
|
-
* `maxSteps` (from {@linkcode AgentConfig}) is reached.
|
|
232
|
-
*
|
|
233
|
-
* Tool errors are fed back to the model as tool results rather than thrown, so
|
|
234
|
-
* the model can recover or explain the failure.
|
|
235
|
-
*
|
|
236
|
-
* @param input - The run input: either `{ prompt: string }` for a simple user
|
|
237
|
-
* message, or `{ messages: ChatMessage[] }` to supply a full conversation history.
|
|
238
|
-
* @param options - Optional {@linkcode RunOptions} (e.g. an `AbortSignal`).
|
|
239
|
-
* @returns Promise resolving to a {@linkcode RunResult} containing the model's
|
|
240
|
-
* final text, per-step tool call history, finish reason, and token/credit usage.
|
|
241
|
-
*
|
|
242
|
-
* @example
|
|
243
|
-
* ```typescript
|
|
244
|
-
* // Simple prompt
|
|
245
|
-
* const { text, usage } = await agent.run({ prompt: "Plan a one-day trip to Haifa." });
|
|
246
|
-
* console.log(text);
|
|
247
|
-
* console.log(`Credits used: ${usage.credits}`);
|
|
248
|
-
* ```
|
|
249
|
-
*
|
|
250
|
-
* @example
|
|
251
|
-
* ```typescript
|
|
252
|
-
* // Supply a full message history
|
|
253
|
-
* const { text } = await agent.run({
|
|
254
|
-
* messages: [
|
|
255
|
-
* { role: "user", content: "What is the capital of France?" },
|
|
256
|
-
* { role: "assistant", content: "Paris." },
|
|
257
|
-
* { role: "user", content: "And what is the population?" },
|
|
258
|
-
* ],
|
|
259
|
-
* });
|
|
260
|
-
* ```
|
|
261
|
-
*
|
|
262
|
-
* @example
|
|
263
|
-
* ```typescript
|
|
264
|
-
* // Cancel a long-running run
|
|
265
|
-
* const controller = new AbortController();
|
|
266
|
-
* setTimeout(() => controller.abort(), 15_000);
|
|
267
|
-
* const { text } = await agent.run(
|
|
268
|
-
* { prompt: "Summarize all open support tickets." },
|
|
269
|
-
* { abortSignal: controller.signal },
|
|
270
|
-
* );
|
|
271
|
-
* ```
|
|
272
|
-
*/
|
|
273
|
-
run(input: RunInput, options?: RunOptions): Promise<RunResult>;
|
|
274
|
-
/**
|
|
275
|
-
* Wraps this agent as a {@linkcode Tool} so another agent can call it as a sub-agent.
|
|
276
|
-
*
|
|
277
|
-
* The returned tool exposes a single `prompt` parameter. When called, it invokes
|
|
278
|
-
* {@linkcode Agent.run | run()} with that prompt and returns the text result.
|
|
279
|
-
* Use this to build agent hierarchies where a coordinator agent delegates tasks
|
|
280
|
-
* to specialized sub-agents.
|
|
281
|
-
*
|
|
282
|
-
* @param opts - Options for the tool wrapper.
|
|
283
|
-
* @param opts.description - Required. Natural-language description the calling
|
|
284
|
-
* model uses to decide when to invoke this sub-agent.
|
|
285
|
-
* @param opts.name - Optional display name for the tool. Defaults to the
|
|
286
|
-
* agent config's model alias when omitted.
|
|
287
|
-
* @returns A {@linkcode Tool} that can be passed in another agent's `tools` map.
|
|
288
|
-
* @note The sub-agent runs independently — the parent's `abortSignal` is not propagated and
|
|
289
|
-
* the sub-agent's token/credit usage is not included in the parent's `totalUsage`.
|
|
290
|
-
*
|
|
291
|
-
* @example
|
|
292
|
-
* ```typescript
|
|
293
|
-
* const researchAgent = base44.agents.create({
|
|
294
|
-
* model: "claude_sonnet_4_6",
|
|
295
|
-
* tools: { webSearch },
|
|
296
|
-
* });
|
|
297
|
-
*
|
|
298
|
-
* const writerAgent = base44.agents.create({
|
|
299
|
-
* model: "claude_sonnet_4_6",
|
|
300
|
-
* tools: {
|
|
301
|
-
* research: researchAgent.asTool({
|
|
302
|
-
* description: "Search the web and return a research summary.",
|
|
303
|
-
* }),
|
|
304
|
-
* },
|
|
305
|
-
* });
|
|
306
|
-
*
|
|
307
|
-
* const { text } = await writerAgent.run({ prompt: "Write a blog post about coral reefs." });
|
|
308
|
-
* ```
|
|
309
|
-
*/
|
|
310
|
-
asTool(opts: {
|
|
311
|
-
name?: string;
|
|
312
|
-
description: string;
|
|
313
|
-
}): Tool;
|
|
314
|
-
}
|
|
2
|
+
import { RoomsSocket } from "../utils/socket-utils.js";
|
|
3
|
+
import { ModelFilterParams } from "../types.js";
|
|
315
4
|
/**
|
|
316
5
|
* Registry of agent names. The [`types generate`](/developers/references/cli/commands/types-generate) command fills this registry, then [`AgentName`](#agentname) resolves to a union of the keys.
|
|
317
6
|
*/
|
|
@@ -473,8 +162,6 @@ export interface AgentsModuleConfig {
|
|
|
473
162
|
serverUrl?: string;
|
|
474
163
|
/** Authentication token */
|
|
475
164
|
token?: string;
|
|
476
|
-
/** Returns the current bearer token at call time (thunk — never a captured string). Used by `create()`. */
|
|
477
|
-
getToken?: () => string | undefined;
|
|
478
165
|
}
|
|
479
166
|
/**
|
|
480
167
|
* Agents module for managing AI agent conversations.
|
|
@@ -669,27 +356,6 @@ export interface AgentsModule {
|
|
|
669
356
|
* ```
|
|
670
357
|
*/
|
|
671
358
|
subscribeToConversation(conversationId: string, onUpdate?: (conversation: AgentConversation) => void): () => void;
|
|
672
|
-
/**
|
|
673
|
-
* Creates a code-defined agent: you specify the model, system prompt, and tools in code,
|
|
674
|
-
* and the SDK runs the tool-calling loop against the Base44 AI Gateway.
|
|
675
|
-
*
|
|
676
|
-
* Returns a reusable {@linkcode Agent} you can {@linkcode Agent.run | run} or expose to
|
|
677
|
-
* another agent as a tool with {@linkcode Agent.asTool | asTool}.
|
|
678
|
-
*
|
|
679
|
-
* @param config - Model alias, optional system prompt, tools, and step limit.
|
|
680
|
-
* @returns A reusable {@linkcode Agent} with {@linkcode Agent.run | run()} and {@linkcode Agent.asTool | asTool()}.
|
|
681
|
-
*
|
|
682
|
-
* @example
|
|
683
|
-
* ```typescript
|
|
684
|
-
* const agent = base44.agents.create({
|
|
685
|
-
* model: "claude_sonnet_4_6",
|
|
686
|
-
* system: "You plan trips.",
|
|
687
|
-
* tools: { getWeather },
|
|
688
|
-
* });
|
|
689
|
-
* const { text } = await agent.run({ prompt: "Plan a day in Haifa." });
|
|
690
|
-
* ```
|
|
691
|
-
*/
|
|
692
|
-
create(config: AgentConfig): Agent;
|
|
693
359
|
/**
|
|
694
360
|
* Gets WhatsApp connection URL for an agent.
|
|
695
361
|
*
|
package/dist/modules/entities.js
CHANGED
|
@@ -53,7 +53,7 @@ function parseRealtimeMessage(dataStr) {
|
|
|
53
53
|
*/
|
|
54
54
|
function createEntityHandler(axios, appId, entityName, getSocket) {
|
|
55
55
|
const baseURL = `/apps/${appId}/entities/${entityName}`;
|
|
56
|
-
|
|
56
|
+
return {
|
|
57
57
|
// List entities with optional pagination and sorting
|
|
58
58
|
async list(sort, limit, skip, fields) {
|
|
59
59
|
const params = {};
|
|
@@ -159,62 +159,5 @@ function createEntityHandler(axios, appId, entityName, getSocket) {
|
|
|
159
159
|
});
|
|
160
160
|
return unsubscribe;
|
|
161
161
|
},
|
|
162
|
-
asTool(opts = {}) {
|
|
163
|
-
var _a;
|
|
164
|
-
const operations = (_a = opts.operations) !== null && _a !== void 0 ? _a : ["read"];
|
|
165
|
-
const tools = {};
|
|
166
|
-
if (operations.includes("read")) {
|
|
167
|
-
tools[`read_${entityName}`] = {
|
|
168
|
-
description: `Read ${entityName} entities. For the query param, use MongoDB query syntax, e.g. { "status": "open", "price": { "$gt": 30 } }.`,
|
|
169
|
-
parameters: {
|
|
170
|
-
type: "object",
|
|
171
|
-
properties: {
|
|
172
|
-
query: { type: "object", description: `MongoDB-style filter over ${entityName} fields.`, additionalProperties: true },
|
|
173
|
-
sort: { type: "string", description: "Field to sort by; prefix with '-' for descending (e.g. '-created_date')." },
|
|
174
|
-
limit: { type: "number", description: "Maximum number of records to return." },
|
|
175
|
-
skip: { type: "number", description: "Number of records to skip (pagination)." },
|
|
176
|
-
fields: { type: "array", items: { type: "string" }, description: "Subset of fields to return." },
|
|
177
|
-
},
|
|
178
|
-
},
|
|
179
|
-
execute: (args = {}) => { var _a; return handler.filter(((_a = args.query) !== null && _a !== void 0 ? _a : {}), args.sort, args.limit, args.skip, args.fields); },
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
|
-
if (operations.includes("create")) {
|
|
183
|
-
tools[`create_${entityName}`] = {
|
|
184
|
-
description: `Create a new ${entityName} entity`,
|
|
185
|
-
// open object: the SDK has no runtime schema, so the model supplies fields directly
|
|
186
|
-
parameters: { type: "object", additionalProperties: true },
|
|
187
|
-
execute: (args = {}) => handler.create(args),
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
if (operations.includes("update")) {
|
|
191
|
-
tools[`update_${entityName}`] = {
|
|
192
|
-
description: `Update an existing ${entityName} entity`,
|
|
193
|
-
parameters: {
|
|
194
|
-
type: "object",
|
|
195
|
-
properties: { id: { type: "string", description: `The id of the ${entityName} to update.` } },
|
|
196
|
-
required: ["id"],
|
|
197
|
-
additionalProperties: true,
|
|
198
|
-
},
|
|
199
|
-
execute: (args) => {
|
|
200
|
-
const { id, ...data } = args !== null && args !== void 0 ? args : {};
|
|
201
|
-
return handler.update(id, data);
|
|
202
|
-
},
|
|
203
|
-
};
|
|
204
|
-
}
|
|
205
|
-
if (operations.includes("delete")) {
|
|
206
|
-
tools[`delete_${entityName}`] = {
|
|
207
|
-
description: `Delete an existing ${entityName} entity`,
|
|
208
|
-
parameters: {
|
|
209
|
-
type: "object",
|
|
210
|
-
properties: { id: { type: "string", description: `The id of the ${entityName} to delete.` } },
|
|
211
|
-
required: ["id"],
|
|
212
|
-
},
|
|
213
|
-
execute: (args) => handler.delete(args.id),
|
|
214
|
-
};
|
|
215
|
-
}
|
|
216
|
-
return tools;
|
|
217
|
-
},
|
|
218
162
|
};
|
|
219
|
-
return handler;
|
|
220
163
|
}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { Tool } from "./agents/agents.types.js";
|
|
2
1
|
/**
|
|
3
2
|
* Event types for realtime entity updates.
|
|
4
3
|
*/
|
|
@@ -641,25 +640,6 @@ export interface EntityHandler<T = any> {
|
|
|
641
640
|
* ```
|
|
642
641
|
*/
|
|
643
642
|
subscribe(callback: RealtimeCallback<T>): () => void;
|
|
644
|
-
/**
|
|
645
|
-
* Turns this entity into a map of agent tools — one per allowed operation
|
|
646
|
-
* (`read_<Entity>`, `create_<Entity>`, `update_<Entity>`, `delete_<Entity>`).
|
|
647
|
-
* Read-only by default, pass `operations` to opt into writes. Spread the result into an agent's `tools`.
|
|
648
|
-
*
|
|
649
|
-
* @param opts - Optional `operations` (`"read" | "create" | "update" | "delete"`, default `["read"]`).
|
|
650
|
-
* @returns A map of tool-name to {@linkcode Tool}. Keys follow the pattern `read_<EntityName>`, `create_<EntityName>`, `update_<EntityName>`, `delete_<EntityName>`.
|
|
651
|
-
*
|
|
652
|
-
* @example
|
|
653
|
-
* ```typescript
|
|
654
|
-
* const agent = base44.agents.create({
|
|
655
|
-
* model: "claude_sonnet_4_6",
|
|
656
|
-
* tools: { ...base44.entities.Order.asTool({ operations: ["read", "update"] }) },
|
|
657
|
-
* });
|
|
658
|
-
* ```
|
|
659
|
-
*/
|
|
660
|
-
asTool(opts?: {
|
|
661
|
-
operations?: ("read" | "create" | "update" | "delete")[];
|
|
662
|
-
}): Record<string, Tool>;
|
|
663
643
|
}
|
|
664
644
|
/**
|
|
665
645
|
* Typed entities module - maps registry keys to typed handlers (full record type).
|
|
@@ -31,40 +31,38 @@ export function createFunctionsModule(axios, appId, config) {
|
|
|
31
31
|
}
|
|
32
32
|
return headers;
|
|
33
33
|
};
|
|
34
|
-
// Hoisted so both the returned `invoke` property and `asTool.execute` can reference it
|
|
35
|
-
// without relying on `this` (which breaks when the object is spread into the client).
|
|
36
|
-
const invoke = async (functionName, data) => {
|
|
37
|
-
// Validate input
|
|
38
|
-
if (typeof data === "string") {
|
|
39
|
-
throw new Error(`Function ${functionName} must receive an object with named parameters, received: ${data}`);
|
|
40
|
-
}
|
|
41
|
-
let formData;
|
|
42
|
-
let contentType;
|
|
43
|
-
// Handle file uploads with FormData
|
|
44
|
-
if (data instanceof FormData ||
|
|
45
|
-
(data && Object.values(data).some((value) => value instanceof File))) {
|
|
46
|
-
formData = new FormData();
|
|
47
|
-
Object.keys(data).forEach((key) => {
|
|
48
|
-
if (data[key] instanceof File) {
|
|
49
|
-
formData.append(key, data[key], data[key].name);
|
|
50
|
-
}
|
|
51
|
-
else if (typeof data[key] === "object" && data[key] !== null) {
|
|
52
|
-
formData.append(key, JSON.stringify(data[key]));
|
|
53
|
-
}
|
|
54
|
-
else {
|
|
55
|
-
formData.append(key, data[key]);
|
|
56
|
-
}
|
|
57
|
-
});
|
|
58
|
-
contentType = "multipart/form-data";
|
|
59
|
-
}
|
|
60
|
-
else {
|
|
61
|
-
formData = data;
|
|
62
|
-
contentType = "application/json";
|
|
63
|
-
}
|
|
64
|
-
return axios.post(`/apps/${appId}/functions/${functionName}`, formData || data, { headers: { "Content-Type": contentType } });
|
|
65
|
-
};
|
|
66
34
|
return {
|
|
67
|
-
|
|
35
|
+
// Invoke a custom backend function by name
|
|
36
|
+
async invoke(functionName, data) {
|
|
37
|
+
// Validate input
|
|
38
|
+
if (typeof data === "string") {
|
|
39
|
+
throw new Error(`Function ${functionName} must receive an object with named parameters, received: ${data}`);
|
|
40
|
+
}
|
|
41
|
+
let formData;
|
|
42
|
+
let contentType;
|
|
43
|
+
// Handle file uploads with FormData
|
|
44
|
+
if (data instanceof FormData ||
|
|
45
|
+
(data && Object.values(data).some((value) => value instanceof File))) {
|
|
46
|
+
formData = new FormData();
|
|
47
|
+
Object.keys(data).forEach((key) => {
|
|
48
|
+
if (data[key] instanceof File) {
|
|
49
|
+
formData.append(key, data[key], data[key].name);
|
|
50
|
+
}
|
|
51
|
+
else if (typeof data[key] === "object" && data[key] !== null) {
|
|
52
|
+
formData.append(key, JSON.stringify(data[key]));
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
formData.append(key, data[key]);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
contentType = "multipart/form-data";
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
formData = data;
|
|
62
|
+
contentType = "application/json";
|
|
63
|
+
}
|
|
64
|
+
return axios.post(`/apps/${appId}/functions/${functionName}`, formData || data, { headers: { "Content-Type": contentType } });
|
|
65
|
+
},
|
|
68
66
|
// Fetch a backend function endpoint directly.
|
|
69
67
|
async fetch(path, init = {}) {
|
|
70
68
|
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
@@ -77,17 +75,5 @@ export function createFunctionsModule(axios, appId, config) {
|
|
|
77
75
|
const response = await fetch(joinBaseUrl(config === null || config === void 0 ? void 0 : config.baseURL, primaryPath), requestInit);
|
|
78
76
|
return response;
|
|
79
77
|
},
|
|
80
|
-
// Turn a backend function into an agent tool.
|
|
81
|
-
asTool(name, opts) {
|
|
82
|
-
var _a;
|
|
83
|
-
return {
|
|
84
|
-
description: opts.description,
|
|
85
|
-
parameters: (_a = opts.parameters) !== null && _a !== void 0 ? _a : { type: "object", properties: {}, additionalProperties: true },
|
|
86
|
-
execute: async (args) => {
|
|
87
|
-
const res = await invoke(name, args !== null && args !== void 0 ? args : {});
|
|
88
|
-
return res === null || res === void 0 ? void 0 : res.data;
|
|
89
|
-
},
|
|
90
|
-
};
|
|
91
|
-
},
|
|
92
78
|
};
|
|
93
79
|
}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { Tool } from "./agents/agents.types.js";
|
|
2
1
|
/**
|
|
3
2
|
* Registry of function names. The [`types generate`](/developers/references/cli/commands/types-generate) command fills this registry, then [`FunctionName`](#functionname) resolves to a union of the keys.
|
|
4
3
|
*/
|
|
@@ -87,33 +86,6 @@ export interface FunctionsModule {
|
|
|
87
86
|
* ```
|
|
88
87
|
*/
|
|
89
88
|
invoke(functionName: FunctionName, data?: Record<string, any>): Promise<any>;
|
|
90
|
-
/**
|
|
91
|
-
* Turns a backend function into a {@linkcode Tool} an agent can call.
|
|
92
|
-
*
|
|
93
|
-
* Functions are invoked by name with no server-known input schema, so you supply a
|
|
94
|
-
* `description` and (optionally) JSON Schema `parameters` for the model.
|
|
95
|
-
*
|
|
96
|
-
* @param name - The backend function name.
|
|
97
|
-
* @param opts - `description` (required) and optional JSON Schema `parameters`.
|
|
98
|
-
* @returns A {@linkcode Tool} for use in an agent's `tools` map.
|
|
99
|
-
*
|
|
100
|
-
* @example
|
|
101
|
-
* ```typescript
|
|
102
|
-
* const emailTool = base44.functions.asTool("sendOrderEmail", {
|
|
103
|
-
* description: "Send an order confirmation email to the customer.",
|
|
104
|
-
* parameters: {
|
|
105
|
-
* type: "object",
|
|
106
|
-
* properties: { orderId: { type: "string" } },
|
|
107
|
-
* required: ["orderId"],
|
|
108
|
-
* },
|
|
109
|
-
* });
|
|
110
|
-
* const agent = base44.agents.create({ model: "claude_sonnet_4_6", tools: { emailTool } });
|
|
111
|
-
* ```
|
|
112
|
-
*/
|
|
113
|
-
asTool(name: FunctionName, opts: {
|
|
114
|
-
description: string;
|
|
115
|
-
parameters?: Record<string, unknown>;
|
|
116
|
-
}): Tool;
|
|
117
89
|
/**
|
|
118
90
|
* Performs a direct HTTP request to a backend function path and returns the native `Response`.
|
|
119
91
|
*
|
package/dist/modules/types.d.ts
CHANGED
package/dist/modules/types.js
CHANGED
|
@@ -130,6 +130,16 @@ export function createAxiosClient({ baseURL, headers = {}, token, interceptRespo
|
|
|
130
130
|
}
|
|
131
131
|
// Add origin URL in browser environment
|
|
132
132
|
client.interceptors.request.use((config) => {
|
|
133
|
+
var _a;
|
|
134
|
+
// Axios selects its Node HTTP adapter in Deno, where DELETE requests with
|
|
135
|
+
// a body fail in the node:http compatibility layer. deleteMany relies on
|
|
136
|
+
// that request shape, while Deno's native fetch handles it correctly.
|
|
137
|
+
if (typeof globalThis.Deno !==
|
|
138
|
+
"undefined" &&
|
|
139
|
+
((_a = config.method) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === "delete" &&
|
|
140
|
+
config.data !== undefined) {
|
|
141
|
+
config.adapter = "fetch";
|
|
142
|
+
}
|
|
133
143
|
if (typeof window !== "undefined") {
|
|
134
144
|
config.headers.set("X-Origin-URL", window.location.href);
|
|
135
145
|
// On unauthenticated requests, attach a stable anonymous visitor id so the
|
|
@@ -155,7 +165,7 @@ export function createAxiosClient({ baseURL, headers = {}, token, interceptRespo
|
|
|
155
165
|
},
|
|
156
166
|
}, "*");
|
|
157
167
|
}
|
|
158
|
-
catch (
|
|
168
|
+
catch (_b) {
|
|
159
169
|
/* skip the logging */
|
|
160
170
|
}
|
|
161
171
|
}
|
package/package.json
CHANGED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Minimal authenticated JSON POST against the gateway. The provider supplies the wire-specific
|
|
3
|
-
* path (e.g. `/chat/completions`), so the transport stays neutral across provider formats.
|
|
4
|
-
* @internal
|
|
5
|
-
*/
|
|
6
|
-
export type GatewayTransport = {
|
|
7
|
-
post(path: string, body: Record<string, unknown>, opts?: {
|
|
8
|
-
signal?: AbortSignal;
|
|
9
|
-
}): Promise<unknown>;
|
|
10
|
-
};
|
|
11
|
-
/** @internal */
|
|
12
|
-
export interface GatewayConfig {
|
|
13
|
-
serverUrl: string;
|
|
14
|
-
/** Returns the current bearer token at call time (thunk — never a captured string). */
|
|
15
|
-
getToken: () => string | undefined;
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* Resolves the AI Gateway connection from a client config.
|
|
19
|
-
* @internal
|
|
20
|
-
*/
|
|
21
|
-
export declare function resolveConnection(config: GatewayConfig): {
|
|
22
|
-
baseURL: string;
|
|
23
|
-
apiKey: string;
|
|
24
|
-
};
|
|
25
|
-
/**
|
|
26
|
-
* Creates the gateway transport — owns the single HTTP call to the OpenAI-compatible
|
|
27
|
-
* `/chat/completions` endpoint.
|
|
28
|
-
* @internal
|
|
29
|
-
*/
|
|
30
|
-
export declare function createGatewayTransport(config: GatewayConfig): {
|
|
31
|
-
post(path: string, body: Record<string, unknown>, opts?: {
|
|
32
|
-
signal?: AbortSignal;
|
|
33
|
-
}): Promise<unknown>;
|
|
34
|
-
};
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { Base44Error } from "../../utils/axios-client.js";
|
|
2
|
-
/**
|
|
3
|
-
* Resolves the AI Gateway connection from a client config.
|
|
4
|
-
* @internal
|
|
5
|
-
*/
|
|
6
|
-
export function resolveConnection(config) {
|
|
7
|
-
var _a;
|
|
8
|
-
const { serverUrl, getToken } = config;
|
|
9
|
-
// No appId in the path: the gateway resolves the app by request Host.
|
|
10
|
-
return {
|
|
11
|
-
baseURL: `${serverUrl}/api/ai/unified/v1`,
|
|
12
|
-
apiKey: (_a = getToken()) !== null && _a !== void 0 ? _a : "",
|
|
13
|
-
};
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Creates the gateway transport — owns the single HTTP call to the OpenAI-compatible
|
|
17
|
-
* `/chat/completions` endpoint.
|
|
18
|
-
* @internal
|
|
19
|
-
*/
|
|
20
|
-
export function createGatewayTransport(config) {
|
|
21
|
-
return {
|
|
22
|
-
async post(path, body, opts = {}) {
|
|
23
|
-
const { baseURL, apiKey } = resolveConnection(config);
|
|
24
|
-
const res = await fetch(`${baseURL}${path}`, {
|
|
25
|
-
method: "POST",
|
|
26
|
-
headers: {
|
|
27
|
-
"Content-Type": "application/json",
|
|
28
|
-
Authorization: `Bearer ${apiKey}`,
|
|
29
|
-
},
|
|
30
|
-
body: JSON.stringify(body),
|
|
31
|
-
signal: opts.signal,
|
|
32
|
-
});
|
|
33
|
-
const json = await res.json().catch(() => null);
|
|
34
|
-
if (!res.ok) {
|
|
35
|
-
const err = (json && json.error) || {};
|
|
36
|
-
throw new Base44Error(err.message || `AI Gateway request failed with status ${res.status}`, res.status, err.code || err.type || "ai_gateway_error", json, null);
|
|
37
|
-
}
|
|
38
|
-
return json;
|
|
39
|
-
},
|
|
40
|
-
};
|
|
41
|
-
}
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import type { Agent, AgentConfig } from "./agents.types.js";
|
|
2
|
-
import type { LanguageModel } from "./provider.js";
|
|
3
|
-
/** Creates an Agent from a config and a language model. @internal */
|
|
4
|
-
export declare function createAgent(agentConfig: AgentConfig, model: LanguageModel): Agent;
|
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
const DEFAULT_MAX_STEPS = 8;
|
|
2
|
-
function safeParseJson(json) {
|
|
3
|
-
try {
|
|
4
|
-
return JSON.parse(json || "{}");
|
|
5
|
-
}
|
|
6
|
-
catch (_a) {
|
|
7
|
-
return {};
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
function inputToMessages(input) {
|
|
11
|
-
if (!("messages" in input)) {
|
|
12
|
-
return [{ role: "user", content: input.prompt }];
|
|
13
|
-
}
|
|
14
|
-
// Map the public ChatMessage[] 1:1 to neutral ModelMessage[] by role.
|
|
15
|
-
return input.messages.map((message) => {
|
|
16
|
-
var _a, _b, _c;
|
|
17
|
-
if (message.role === "system") {
|
|
18
|
-
return { role: "system", content: typeof message.content === "string" ? message.content : "" };
|
|
19
|
-
}
|
|
20
|
-
if (message.role === "user") {
|
|
21
|
-
return { role: "user", content: typeof message.content === "string" ? message.content : "" };
|
|
22
|
-
}
|
|
23
|
-
if (message.role === "assistant") {
|
|
24
|
-
const toolCalls = (_a = message.tool_calls) === null || _a === void 0 ? void 0 : _a.map((call) => ({
|
|
25
|
-
id: call.id,
|
|
26
|
-
name: call.function.name,
|
|
27
|
-
args: safeParseJson(call.function.arguments),
|
|
28
|
-
}));
|
|
29
|
-
return {
|
|
30
|
-
role: "assistant",
|
|
31
|
-
content: (_b = message.content) !== null && _b !== void 0 ? _b : undefined,
|
|
32
|
-
toolCalls: (toolCalls === null || toolCalls === void 0 ? void 0 : toolCalls.length) ? toolCalls : undefined,
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
// tool
|
|
36
|
-
return {
|
|
37
|
-
role: "tool",
|
|
38
|
-
toolCallId: (_c = message.tool_call_id) !== null && _c !== void 0 ? _c : "",
|
|
39
|
-
result: typeof message.content === "string" ? message.content : "",
|
|
40
|
-
};
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
|
-
function stringifyToolResult(value) {
|
|
44
|
-
return typeof value === "string" ? value : JSON.stringify(value);
|
|
45
|
-
}
|
|
46
|
-
function sumUsage(accumulated, next) {
|
|
47
|
-
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
48
|
-
return {
|
|
49
|
-
inputTokens: ((_a = accumulated.inputTokens) !== null && _a !== void 0 ? _a : 0) + ((_b = next.inputTokens) !== null && _b !== void 0 ? _b : 0),
|
|
50
|
-
outputTokens: ((_c = accumulated.outputTokens) !== null && _c !== void 0 ? _c : 0) + ((_d = next.outputTokens) !== null && _d !== void 0 ? _d : 0),
|
|
51
|
-
totalTokens: ((_e = accumulated.totalTokens) !== null && _e !== void 0 ? _e : 0) + ((_f = next.totalTokens) !== null && _f !== void 0 ? _f : 0),
|
|
52
|
-
credits: ((_g = accumulated.credits) !== null && _g !== void 0 ? _g : 0) + ((_h = next.credits) !== null && _h !== void 0 ? _h : 0),
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
/** Creates an Agent from a config and a language model. @internal */
|
|
56
|
-
export function createAgent(agentConfig, model) {
|
|
57
|
-
var _a;
|
|
58
|
-
const maxSteps = (_a = agentConfig.maxSteps) !== null && _a !== void 0 ? _a : DEFAULT_MAX_STEPS;
|
|
59
|
-
const tools = agentConfig.tools;
|
|
60
|
-
const agent = {
|
|
61
|
-
async run(input, options = {}) {
|
|
62
|
-
var _a, _b, _c, _d;
|
|
63
|
-
const messages = [
|
|
64
|
-
...(agentConfig.system ? [{ role: "system", content: agentConfig.system }] : []),
|
|
65
|
-
...inputToMessages(input),
|
|
66
|
-
];
|
|
67
|
-
const steps = [];
|
|
68
|
-
let totalUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0, credits: 0 };
|
|
69
|
-
// The most recent model call; referenced after the loop for the max-steps return.
|
|
70
|
-
let modelResult = null;
|
|
71
|
-
for (let step = 0; step < maxSteps; step++) {
|
|
72
|
-
modelResult = await model.generate({
|
|
73
|
-
model: agentConfig.model,
|
|
74
|
-
messages,
|
|
75
|
-
tools,
|
|
76
|
-
temperature: agentConfig.temperature,
|
|
77
|
-
toolChoice: agentConfig.toolChoice,
|
|
78
|
-
responseFormat: agentConfig.responseFormat,
|
|
79
|
-
signal: options.abortSignal,
|
|
80
|
-
});
|
|
81
|
-
totalUsage = sumUsage(totalUsage, (_a = modelResult.usage) !== null && _a !== void 0 ? _a : {});
|
|
82
|
-
messages.push({
|
|
83
|
-
role: "assistant",
|
|
84
|
-
content: modelResult.text || undefined,
|
|
85
|
-
toolCalls: modelResult.toolCalls.length ? modelResult.toolCalls : undefined,
|
|
86
|
-
});
|
|
87
|
-
// No tool calls: the model is done — return its final answer.
|
|
88
|
-
if (modelResult.toolCalls.length === 0) {
|
|
89
|
-
return {
|
|
90
|
-
text: modelResult.text,
|
|
91
|
-
steps,
|
|
92
|
-
finishReason: modelResult.finishReason,
|
|
93
|
-
usage: modelResult.usage,
|
|
94
|
-
totalUsage,
|
|
95
|
-
raw: modelResult.raw,
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
// Execute each requested tool and feed the result back for the next turn.
|
|
99
|
-
const toolResults = [];
|
|
100
|
-
for (const call of modelResult.toolCalls) {
|
|
101
|
-
const matchedTool = tools === null || tools === void 0 ? void 0 : tools[call.name];
|
|
102
|
-
let resultContent;
|
|
103
|
-
if (!matchedTool) {
|
|
104
|
-
resultContent = `Error: tool "${call.name}" is not available.`;
|
|
105
|
-
}
|
|
106
|
-
else {
|
|
107
|
-
try {
|
|
108
|
-
resultContent = stringifyToolResult(await matchedTool.execute(call.args));
|
|
109
|
-
}
|
|
110
|
-
catch (error) {
|
|
111
|
-
const message = error === null || error === void 0 ? void 0 : error.message;
|
|
112
|
-
resultContent = `Error: ${message !== null && message !== void 0 ? message : String(error)}`;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
messages.push({ role: "tool", toolCallId: call.id, toolName: call.name, result: resultContent });
|
|
116
|
-
toolResults.push({ toolCallId: call.id, toolName: call.name, args: call.args, result: resultContent });
|
|
117
|
-
}
|
|
118
|
-
steps.push({ toolResults, usage: modelResult.usage });
|
|
119
|
-
}
|
|
120
|
-
// Loop exhausted without a final (tool-free) answer.
|
|
121
|
-
return {
|
|
122
|
-
text: (_b = modelResult === null || modelResult === void 0 ? void 0 : modelResult.text) !== null && _b !== void 0 ? _b : "",
|
|
123
|
-
steps,
|
|
124
|
-
finishReason: "max_steps",
|
|
125
|
-
usage: (_c = modelResult === null || modelResult === void 0 ? void 0 : modelResult.usage) !== null && _c !== void 0 ? _c : {},
|
|
126
|
-
totalUsage,
|
|
127
|
-
raw: (_d = modelResult === null || modelResult === void 0 ? void 0 : modelResult.raw) !== null && _d !== void 0 ? _d : null,
|
|
128
|
-
};
|
|
129
|
-
},
|
|
130
|
-
asTool(toolOpts) {
|
|
131
|
-
return {
|
|
132
|
-
description: toolOpts.description,
|
|
133
|
-
parameters: {
|
|
134
|
-
type: "object",
|
|
135
|
-
properties: { prompt: { type: "string", description: "What to ask the sub-agent." } },
|
|
136
|
-
required: ["prompt"],
|
|
137
|
-
},
|
|
138
|
-
execute: async (args) => {
|
|
139
|
-
const result = await agent.run({ prompt: args.prompt });
|
|
140
|
-
return result.text;
|
|
141
|
-
},
|
|
142
|
-
};
|
|
143
|
-
},
|
|
144
|
-
};
|
|
145
|
-
return agent;
|
|
146
|
-
}
|
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
import type { Tool, ToolChoice, JSONSchema, RunUsage, FinishReason } from "./agents.types.js";
|
|
2
|
-
/** A parsed tool call the model wants to make. Args are already parsed (object), never a JSON string. @internal */
|
|
3
|
-
export interface ModelToolCall {
|
|
4
|
-
id: string;
|
|
5
|
-
name: string;
|
|
6
|
-
args: unknown;
|
|
7
|
-
}
|
|
8
|
-
/**
|
|
9
|
-
* Neutral, provider-agnostic conversation message. `system` is a message role here;
|
|
10
|
-
* each provider adapter places it where its wire format expects. `content` is a string.
|
|
11
|
-
* @internal
|
|
12
|
-
*/
|
|
13
|
-
export type ModelMessage = {
|
|
14
|
-
role: "system";
|
|
15
|
-
content: string;
|
|
16
|
-
} | {
|
|
17
|
-
role: "user";
|
|
18
|
-
content: string;
|
|
19
|
-
} | {
|
|
20
|
-
role: "assistant";
|
|
21
|
-
content?: string;
|
|
22
|
-
toolCalls?: ModelToolCall[];
|
|
23
|
-
} | {
|
|
24
|
-
role: "tool";
|
|
25
|
-
toolCallId: string;
|
|
26
|
-
toolName?: string;
|
|
27
|
-
result: string;
|
|
28
|
-
};
|
|
29
|
-
/** A request to a language model. @internal */
|
|
30
|
-
export interface GenerateRequest {
|
|
31
|
-
model: string;
|
|
32
|
-
messages: ModelMessage[];
|
|
33
|
-
tools?: Record<string, Tool>;
|
|
34
|
-
temperature?: number;
|
|
35
|
-
toolChoice?: ToolChoice;
|
|
36
|
-
responseFormat?: JSONSchema;
|
|
37
|
-
signal?: AbortSignal;
|
|
38
|
-
}
|
|
39
|
-
/** Normalized model output. @internal */
|
|
40
|
-
export interface GenerateResult {
|
|
41
|
-
text: string;
|
|
42
|
-
toolCalls: ModelToolCall[];
|
|
43
|
-
finishReason: FinishReason;
|
|
44
|
-
usage: RunUsage;
|
|
45
|
-
/** Opaque vendor-specific extras (cache control, reasoning, safety, …). @internal */
|
|
46
|
-
providerMetadata?: Record<string, unknown>;
|
|
47
|
-
/** The raw vendor response, for advanced use. */
|
|
48
|
-
raw: unknown;
|
|
49
|
-
}
|
|
50
|
-
/** The provider seam. Adapters translate neutral <-> vendor wire. @internal */
|
|
51
|
-
export interface LanguageModel {
|
|
52
|
-
generate(req: GenerateRequest): Promise<GenerateResult>;
|
|
53
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import type { LanguageModel } from "../provider.js";
|
|
2
|
-
import type { GatewayTransport } from "../gateway.js";
|
|
3
|
-
/**
|
|
4
|
-
* OpenAI-compatible provider: speaks the Chat Completions wire format over the Base44
|
|
5
|
-
* gateway transport.
|
|
6
|
-
* @internal
|
|
7
|
-
*/
|
|
8
|
-
export declare function openAICompatibleProvider(transport: GatewayTransport): LanguageModel;
|
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
function serializeTools(tools) {
|
|
2
|
-
if (!tools)
|
|
3
|
-
return undefined;
|
|
4
|
-
const entries = Object.entries(tools);
|
|
5
|
-
if (entries.length === 0)
|
|
6
|
-
return undefined;
|
|
7
|
-
return entries.map(([name, toolDef]) => ({
|
|
8
|
-
type: "function",
|
|
9
|
-
function: { name, description: toolDef.description, parameters: toolDef.parameters },
|
|
10
|
-
}));
|
|
11
|
-
}
|
|
12
|
-
/** Neutral messages -> Chat Completions messages. System role in the array is passed through. */
|
|
13
|
-
function toChatMessages(messages) {
|
|
14
|
-
var _a, _b;
|
|
15
|
-
const chatMessages = [];
|
|
16
|
-
for (const message of messages) {
|
|
17
|
-
if (message.role === "system") {
|
|
18
|
-
chatMessages.push({ role: "system", content: message.content });
|
|
19
|
-
}
|
|
20
|
-
else if (message.role === "user") {
|
|
21
|
-
chatMessages.push({ role: "user", content: message.content });
|
|
22
|
-
}
|
|
23
|
-
else if (message.role === "assistant") {
|
|
24
|
-
const assistantMessage = { role: "assistant", content: (_a = message.content) !== null && _a !== void 0 ? _a : null };
|
|
25
|
-
if ((_b = message.toolCalls) === null || _b === void 0 ? void 0 : _b.length) {
|
|
26
|
-
assistantMessage.tool_calls = message.toolCalls.map((call) => {
|
|
27
|
-
var _a;
|
|
28
|
-
return ({
|
|
29
|
-
id: call.id,
|
|
30
|
-
type: "function",
|
|
31
|
-
function: { name: call.name, arguments: JSON.stringify((_a = call.args) !== null && _a !== void 0 ? _a : {}) },
|
|
32
|
-
});
|
|
33
|
-
});
|
|
34
|
-
}
|
|
35
|
-
chatMessages.push(assistantMessage);
|
|
36
|
-
}
|
|
37
|
-
else {
|
|
38
|
-
chatMessages.push({ role: "tool", tool_call_id: message.toolCallId, content: message.result });
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
return chatMessages;
|
|
42
|
-
}
|
|
43
|
-
/** Build the Chat Completions body using the param whitelist (rejected params can never appear). */
|
|
44
|
-
function buildChatCompletionsBody(req) {
|
|
45
|
-
const body = { model: req.model, messages: toChatMessages(req.messages) };
|
|
46
|
-
if (req.temperature !== undefined)
|
|
47
|
-
body.temperature = req.temperature;
|
|
48
|
-
if (req.toolChoice !== undefined)
|
|
49
|
-
body.tool_choice = req.toolChoice;
|
|
50
|
-
if (req.responseFormat !== undefined) {
|
|
51
|
-
body.response_format = { type: "json_schema", json_schema: { name: "response", schema: req.responseFormat, strict: true } };
|
|
52
|
-
}
|
|
53
|
-
const tools = serializeTools(req.tools);
|
|
54
|
-
if (tools)
|
|
55
|
-
body.tools = tools;
|
|
56
|
-
return body;
|
|
57
|
-
}
|
|
58
|
-
const FINISH = {
|
|
59
|
-
stop: "stop", length: "length", tool_calls: "tool-calls", content_filter: "content-filter",
|
|
60
|
-
};
|
|
61
|
-
function normalizeFinish(raw, hasToolCalls) {
|
|
62
|
-
if (hasToolCalls)
|
|
63
|
-
return "tool-calls";
|
|
64
|
-
if (raw !== undefined && FINISH[raw])
|
|
65
|
-
return FINISH[raw];
|
|
66
|
-
return "other";
|
|
67
|
-
}
|
|
68
|
-
function parseChatCompletion(raw) {
|
|
69
|
-
var _a, _b, _c, _d, _e;
|
|
70
|
-
const choice = (_a = raw === null || raw === void 0 ? void 0 : raw.choices) === null || _a === void 0 ? void 0 : _a[0];
|
|
71
|
-
const message = (_b = choice === null || choice === void 0 ? void 0 : choice.message) !== null && _b !== void 0 ? _b : {};
|
|
72
|
-
const toolCalls = ((_c = message.tool_calls) !== null && _c !== void 0 ? _c : []).map((call) => {
|
|
73
|
-
var _a, _b;
|
|
74
|
-
let args = {};
|
|
75
|
-
try {
|
|
76
|
-
args = JSON.parse(((_a = call.function) === null || _a === void 0 ? void 0 : _a.arguments) || "{}");
|
|
77
|
-
}
|
|
78
|
-
catch (_c) {
|
|
79
|
-
args = {};
|
|
80
|
-
}
|
|
81
|
-
return { id: call.id, name: (_b = call.function) === null || _b === void 0 ? void 0 : _b.name, args };
|
|
82
|
-
});
|
|
83
|
-
const rawUsage = (_d = raw === null || raw === void 0 ? void 0 : raw.usage) !== null && _d !== void 0 ? _d : {};
|
|
84
|
-
const usage = {
|
|
85
|
-
inputTokens: rawUsage.prompt_tokens,
|
|
86
|
-
outputTokens: rawUsage.completion_tokens,
|
|
87
|
-
totalTokens: rawUsage.total_tokens,
|
|
88
|
-
credits: rawUsage.base44_credits,
|
|
89
|
-
};
|
|
90
|
-
return {
|
|
91
|
-
text: (_e = message.content) !== null && _e !== void 0 ? _e : "",
|
|
92
|
-
toolCalls,
|
|
93
|
-
finishReason: normalizeFinish(choice === null || choice === void 0 ? void 0 : choice.finish_reason, toolCalls.length > 0),
|
|
94
|
-
usage,
|
|
95
|
-
raw,
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* OpenAI-compatible provider: speaks the Chat Completions wire format over the Base44
|
|
100
|
-
* gateway transport.
|
|
101
|
-
* @internal
|
|
102
|
-
*/
|
|
103
|
-
export function openAICompatibleProvider(transport) {
|
|
104
|
-
return {
|
|
105
|
-
async generate(req) {
|
|
106
|
-
const raw = await transport.post("/chat/completions", buildChatCompletionsBody(req), { signal: req.signal });
|
|
107
|
-
return parseChatCompletion(raw);
|
|
108
|
-
},
|
|
109
|
-
};
|
|
110
|
-
}
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import type { Tool } from "./agents.types.js";
|
|
2
|
-
/**
|
|
3
|
-
* Defines a tool an agent can call.
|
|
4
|
-
*
|
|
5
|
-
* A tool combines a natural-language `description` (used by the model to decide
|
|
6
|
-
* when to call the tool), a JSON Schema for its `parameters`, and an `execute`
|
|
7
|
-
* function that runs when the model calls it.
|
|
8
|
-
*
|
|
9
|
-
* Pass the returned tool in the `tools` map of {@linkcode AgentsModule.create | base44.agents.create()}.
|
|
10
|
-
*
|
|
11
|
-
* @param t - The tool definition: `description`, `parameters` (JSON Schema), and `execute`.
|
|
12
|
-
* @returns The same tool object, typed as {@linkcode Tool}.
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* ```typescript
|
|
16
|
-
* import { tool } from "@base44/sdk";
|
|
17
|
-
*
|
|
18
|
-
* const getWeather = tool({
|
|
19
|
-
* description: "Get the current weather for a city.",
|
|
20
|
-
* parameters: {
|
|
21
|
-
* type: "object",
|
|
22
|
-
* properties: { city: { type: "string", description: "City name, e.g. 'Tel Aviv'" } },
|
|
23
|
-
* required: ["city"],
|
|
24
|
-
* },
|
|
25
|
-
* execute: async ({ city }) => {
|
|
26
|
-
* const data = await fetchWeatherAPI(city);
|
|
27
|
-
* return { city, tempC: data.temperature };
|
|
28
|
-
* },
|
|
29
|
-
* });
|
|
30
|
-
*
|
|
31
|
-
* const agent = base44.agents.create({
|
|
32
|
-
* model: "claude_sonnet_4_6",
|
|
33
|
-
* tools: { getWeather },
|
|
34
|
-
* });
|
|
35
|
-
* ```
|
|
36
|
-
*/
|
|
37
|
-
export declare function tool(t: Tool): Tool;
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Defines a tool an agent can call.
|
|
3
|
-
*
|
|
4
|
-
* A tool combines a natural-language `description` (used by the model to decide
|
|
5
|
-
* when to call the tool), a JSON Schema for its `parameters`, and an `execute`
|
|
6
|
-
* function that runs when the model calls it.
|
|
7
|
-
*
|
|
8
|
-
* Pass the returned tool in the `tools` map of {@linkcode AgentsModule.create | base44.agents.create()}.
|
|
9
|
-
*
|
|
10
|
-
* @param t - The tool definition: `description`, `parameters` (JSON Schema), and `execute`.
|
|
11
|
-
* @returns The same tool object, typed as {@linkcode Tool}.
|
|
12
|
-
*
|
|
13
|
-
* @example
|
|
14
|
-
* ```typescript
|
|
15
|
-
* import { tool } from "@base44/sdk";
|
|
16
|
-
*
|
|
17
|
-
* const getWeather = tool({
|
|
18
|
-
* description: "Get the current weather for a city.",
|
|
19
|
-
* parameters: {
|
|
20
|
-
* type: "object",
|
|
21
|
-
* properties: { city: { type: "string", description: "City name, e.g. 'Tel Aviv'" } },
|
|
22
|
-
* required: ["city"],
|
|
23
|
-
* },
|
|
24
|
-
* execute: async ({ city }) => {
|
|
25
|
-
* const data = await fetchWeatherAPI(city);
|
|
26
|
-
* return { city, tempC: data.temperature };
|
|
27
|
-
* },
|
|
28
|
-
* });
|
|
29
|
-
*
|
|
30
|
-
* const agent = base44.agents.create({
|
|
31
|
-
* model: "claude_sonnet_4_6",
|
|
32
|
-
* tools: { getWeather },
|
|
33
|
-
* });
|
|
34
|
-
* ```
|
|
35
|
-
*/
|
|
36
|
-
export function tool(t) {
|
|
37
|
-
return t;
|
|
38
|
-
}
|
|
File without changes
|