| 1 | import type * as bedrock from "@distilled.cloud/aws/bedrock-agent-runtime"; |
| 2 | import type * as Effect from "effect/Effect"; |
| 3 | import * as Binding from "../../Binding.ts"; |
| 4 | import type { AgentAlias } from "./AgentAlias.ts"; |
| 5 | |
| 6 | /** |
| 7 | * The `InvokeAgent` request with the binding-injected `agentId` and |
| 8 | * `agentAliasId` removed — they are supplied automatically from the bound |
| 9 | * {@link AgentAlias}. |
| 10 | */ |
| 11 | export interface InvokeAgentRequest extends Omit< |
| 12 | bedrock.InvokeAgentRequest, |
| 13 | "agentId" | "agentAliasId" |
| 14 | > {} |
| 15 | |
| 16 | /** |
| 17 | * Runtime binding for `bedrock-agent-runtime:InvokeAgent` — send user input |
| 18 | * to a Bedrock agent through one of its aliases and receive the agent's |
| 19 | * response as an event stream. |
| 20 | * |
| 21 | * Bind an {@link AgentAlias} inside a function runtime to get a callable |
| 22 | * that invokes the agent. The binding grants the function |
| 23 | * `bedrock:InvokeAgent` scoped to exactly that alias. The response's |
| 24 | * `completion` is an event `Stream` of chunks (and traces when |
| 25 | * `enableTrace` is set); concatenate the chunk bytes to recover the answer. |
| 26 | * |
| 27 | * ### Invoking an Agent |
| 28 | * **Example:** Invoke and Aggregate the Completion |
| 29 | * ```typescript |
| 30 | * // init |
| 31 | * const invokeAgent = yield* Bedrock.InvokeAgent(alias); |
| 32 | * |
| 33 | * // runtime |
| 34 | * const result = yield* invokeAgent({ |
| 35 | * sessionId: crypto.randomUUID(), |
| 36 | * inputText: "What is the capital of France?", |
| 37 | * }); |
| 38 | * const events = yield* Stream.runCollect(result.completion); |
| 39 | * const decoder = new TextDecoder(); |
| 40 | * const answer = events |
| 41 | * .map((event) => |
| 42 | * event.chunk?.bytes !== undefined |
| 43 | * ? decoder.decode( |
| 44 | * Redacted.isRedacted(event.chunk.bytes) |
| 45 | * ? Redacted.value(event.chunk.bytes) |
| 46 | * : event.chunk.bytes, |
| 47 | * ) |
| 48 | * : "", |
| 49 | * ) |
| 50 | * .join(""); |
| 51 | * ``` |
| 52 | * |
| 53 | * **Example:** Continue a Session |
| 54 | * ```typescript |
| 55 | * // Reuse the same sessionId across calls to keep conversational context. |
| 56 | * const followUp = yield* invokeAgent({ |
| 57 | * sessionId, |
| 58 | * inputText: "And its population?", |
| 59 | * }); |
| 60 | * ``` |
| 61 | * |
| 62 | * @binding |
| 63 | */ |
| 64 | export interface InvokeAgent extends Binding.Service< |
| 65 | InvokeAgent, |
| 66 | "AWS.Bedrock.InvokeAgent", |
| 67 | <A extends AgentAlias>( |
| 68 | alias: A, |
| 69 | ) => Effect.Effect< |
| 70 | ( |
| 71 | request: InvokeAgentRequest, |
| 72 | ) => Effect.Effect<bedrock.InvokeAgentResponse, bedrock.InvokeAgentError> |
| 73 | > |
| 74 | > {} |
| 75 | export const InvokeAgent = Binding.Service<InvokeAgent>( |
| 76 | "AWS.Bedrock.InvokeAgent", |
| 77 | ); |