Bluestep JS Documentation
    Preparing search index...

    Class Ai

    AI services for BSJS scripts. Routes through the web-global usage gate so requests are metered against the tenant's Bluestep API key, unless an apiKey override is supplied (in which case the proxy is bypassed).

    Index

    Helpers that auto-generate AiTools from existing Relate form metadata. See B.ai.tool.forNewEntry().

    • Open a reusable AI agent that maintains connection settings, an accumulated tool registry, an onTurn callback, and a running chatHistory across multiple sendMessage(...) calls. Each sendMessage dispatches through the same usage-gated pipeline as B.ai.call and auto-threads the user message and assistant response into the agent's chatHistory so subsequent calls continue the conversation.

      const tool = B.ai.tool.custom()
      .setName("add_1")
      .setDescription("adds one!")
      .setSchema({
      type: "object",
      properties: { a: { type: "integer" }, b: { type: "integer" } },
      required: ["a", "b"],
      })
      .setExecutor((args) => args.a + args.b + 1);

      const agent = B.ai.agent()
      .addTool(tool)
      .setProvider("anthropic")
      .setModel("claude-opus-4-8")
      .setSystemPrompt("You are a helpful assistant.");

      const r1 = agent.sendMessage("What is 2 + 3?");
      const r2 = agent.sendMessage("Now add 10 to that.");

      Returns AiAgent

    • Open a reusable AI agent pre-seeded from options. Equivalent to calling the no-arg agent() and then chaining the corresponding setters / addTool calls — every field on AiClientOptions is copied straight into the agent. After construction, the agent behaves identically to one built via the fluent setters: each sendMessage(...) dispatches through the same usage-gated pipeline as B.ai.call and threads the user message and assistant response into the running chatHistory.

      const tool = B.ai.tool.custom()
      .setName("add_1")
      .setDescription("adds one!")
      .setSchema({
      type: "object",
      properties: { a: { type: "integer" }, b: { type: "integer" } },
      required: ["a", "b"],
      })
      .setExecutor((args) => args.a + args.b + 1);

      const agent = B.ai.agent({
      provider: "anthropic",
      model: "claude-opus-4-8",
      systemPrompt: "You are a helpful assistant.",
      tools: [tool],
      });

      const r1 = agent.sendMessage("What is 2 + 3?");
      const r2 = agent.sendMessage("Now add 10 to that.");

      Type Parameters

      Parameters

      Returns AiAgent

    • Sends a request to an AI provider and returns the response.

      The call is metered through the web-global AI usage gate under the tenant's Bluestep API key, with usage attributed to the calling user, the current operating Unit, the optional flag, the model, and the script that triggered the call. Pass an apiKey to bypass the proxy and call the provider directly with your own key (no metering).

      When an onTurn callback is supplied, the conversation continues for as many assistant↔user exchanges as the callback drives — analogous to a state-machine agent loop but owned by the script.

      The type parameter Schemas is inferred from the tools tuple's input_schema literals (preserved by the const modifier), so inline tool literals get a typed executor args parameter — typos in argument names and wrong-shape access fail at compile time, matching the safety of B.ai.tool.custom().

      Type Parameters

      Parameters

      Returns AiCallResult

    • Sets the AI budget for the calling tenant. Superuser only. Upserts the ai_tenant_config row for the (schema, unitId, flag) scope — the schema comes from the operating context; unitId and flag are optional (omit for the tenant-wide default, a null wildcard on that dimension). maxSpendMicros (micro-dollars; 1_000_000 = $1.00) and maxIterations are required and positive when enabling; omit them to disable (enable: false). budgetSchedule is one of HOURLY, DAILY, WEEKLY, MONTHLY, LIFETIME (default LIFETIME = cumulative cap); utcOffsetMinutes anchors windowed schedules to the tenant's local calendar. Fail-closed: any error throws.

      Parameters

      Returns void

    • Open a streaming AI agent for realtime audio (OpenAI only). Shares the connection setters and tool registry of agent(), but instead of sendMessage(text) it exposes sendAudio(...): audio is streamed straight to the model over a live session, the model may call the registered tools (executed in-script, results fed back automatically), and the final response is returned as an AiCallResult.

      Each sendAudio(...) is a one-shot turn — there is no running chatHistory or onTurn loop. Audio must already be PCM16 @ 24kHz mono.

      const tool = B.ai.tool.custom()
      .setName("lookup")
      .setDescription("look up a record")
      .setSchema({ type: "object", properties: { id: { type: "string" } }, required: ["id"] })
      .setExecutor((args) => B.find.record(args.id)?.name ?? "not found");

      // e.g. a live PCM16 mic upload posted to a BSJS endpoint
      B.net.request.binaryStream((audioIn) => {
      const result = B.ai.streamingAgent()
      .addTool(tool)
      .setSystemPrompt("You are a voice assistant. Use tools to answer.")
      .sendAudio(audioIn);
      B.net.response.json(result);
      });

      Returns StreamingAiAgent

    • Returns current AI spend against the configured budget for the calling tenant, targeting the tenant-wide default scope. Superuser only. Equivalent to calling usageReporting(options) with no scope filters. spendMicrosUsed is the sum within the current budget window; windowEnd and the limit fields are null when the scope is unconfigured (soft rollout — unlimited but still tracked) or on a LIFETIME schedule.

      Returns AiUsageReport

    • Returns current AI spend against the configured budget for the calling tenant. Superuser only. The tenant schema is taken from the operating context unless options.schemaName overrides it; unitId and flag narrow the scope (omit both for the tenant-wide default). Passing options.schemaName is restricted — the script must run with a fixed id. spendMicrosUsed is the sum within the current budget window; windowEnd and the limit fields are null when the scope is unconfigured (soft rollout — unlimited but still tracked) or on a LIFETIME schedule.

      Parameters

      • Optionaloptions: AiUsageReportingOptions

        Scope filters. All optional — omit unitId/flag for the tenant-wide default; schemaName overrides the tenant schema (restricted).

      Returns AiUsageReport

    • Returns Ai