# Build / AI --- > Source: https://loopstack.ai/llms/build/ai/agent-workflows.md --- title: Agent Workflows description: Building autonomous LLM agents that call tools in a loop. Covers the built-in AgentWorkflow module, custom agent loops with @Guard routing, error recovery, and max-iterations limits. --- # Agent Workflows Build LLM agents that call tools, handle errors, and run as sub-workflows. Use the built-in `AgentWorkflow` for the common case, or build your own loop from scratch with the same decorators. ## Using the Built-In Agent Install the agent module: ```bash npm install @loopstack/agent ``` Register tools in your module so the agent can use them: ```typescript @Module({ imports: [LlmProviderModule, ClaudeModule, AgentModule], providers: [GlobTool, GrepTool, ReadTool, MyWorkflow], exports: [MyWorkflow], }) export class MyModule {} ``` `LlmProviderModule` must be imported alongside any LLM provider module (`ClaudeModule`, `OpenAiModule`) — it registers the global provider registry the adapter tools and provider implementations depend on. See [LLM Providers](./llm-providers.md). Launch the agent from any workflow: ```typescript @Transition({ from: 'planning', to: 'implementing' }) async runAgent(state: MyState) { await this.agent.run({ system: 'You are a code exploration agent. Summarize your findings.', tools: ['glob', 'grep', 'read'], userMessage: 'Find all API endpoints in the codebase.', }, { callback: { transition: 'agentDone' } }); } ``` The agent runs a full tool-calling loop automatically: LLM turn → tool execution → loop back → until the LLM responds without tool calls. ### Agent Args | Arg | Type | Required | Description | | ------------- | ---------- | -------- | --------------------------------------------- | | `system` | `string` | yes | System prompt | | `tools` | `string[]` | yes | Tool names available to the LLM | | `userMessage` | `string` | yes | Initial user message | | `context` | `string` | no | Hidden context message (e.g. pre-loaded docs) | ### Pre-Loading Context Pass documentation or environment data as a hidden context message. The LLM sees it but it's not shown in the UI: ```typescript const docs = await this.loadFiles.call({ files: ['docs/api-reference.md', 'docs/architecture.md'], basePath: './src/assets', }); const context = this.render(join(__dirname, 'templates', 'context.md'), { docs: docs.data, projectName: args.projectName, }); await this.agent.run({ system: 'You are a documentation agent.', tools: ['read', 'write', 'glob', 'grep'], userMessage: 'Generate API documentation.', context, }); ``` ## Tool Resolution When the LLM calls a tool, it's resolved from the NestJS dependency injection container by its `@Tool({ name })` value. The agent workflow only injects the three tools it always needs (`LlmGenerateTextTool`, `LlmDelegateToolCallsTool`, `LlmUpdateToolResultTool`). Domain-specific tools like `glob` or `read` are resolved from the module at runtime. This means you register tools once in the module and they're available to the agent and all other workflows. ## Error Handling Tool errors are handled automatically. When a tool call fails (schema validation, a runtime error, or a failed sub-workflow), the error is returned to the LLM as an `is_error` tool result. The LLM sees the error message and can self-correct on the next turn. The `LlmDelegateResult` includes error metadata: ```typescript interface LlmDelegateResult { allCompleted: boolean; toolResults: { type: 'tool_result'; toolCallId: string; content?: string; isError?: boolean }[]; pendingCount: number; hasErrors: boolean; errorCount: number; errors: { toolName: string; toolCallId: string; message: string }[]; } ``` ## Canceling Pending Tools If the agent is stuck at `awaiting_tools` (e.g. a sub-workflow hasn't returned), a "Cancel pending tools" button appears in the UI. This cancels all pending child workflows recursively and returns the agent to the LLM loop. ## Building a Custom Agent The built-in `AgentWorkflow` is a regular workflow. When you need custom behavior, copy it and modify directly. Here's the full loop: ```typescript import { BaseWorkflow, Guard, Transition, Workflow } from '@loopstack/common'; import type { RunContext, TransitionInput } from '@loopstack/common'; import type { LlmDelegateResult, LlmGenerateTextResult } from '@loopstack/llm-provider'; import { LlmDelegateToolCallsTool, LlmGenerateTextTool, LlmMessageDocument, LlmUpdateToolResultTool, } from '@loopstack/llm-provider'; interface AgentState { llmResult?: LlmGenerateTextResult; delegateResult?: LlmDelegateResult; } const MyAgentSchema = z.object({ instructions: z.string() }); type MyAgentArgs = z.infer; @Workflow({ widget: './my-agent.ui.yaml', schema: MyAgentSchema, }) export class MyAgentWorkflow extends BaseWorkflow { constructor( private readonly llmGenerateText: LlmGenerateTextTool, private readonly llmDelegateToolCalls: LlmDelegateToolCallsTool, private readonly llmUpdateToolResult: LlmUpdateToolResultTool, private readonly myCustomTool: MyCustomTool, ) { super(); } @Transition({ to: 'ready' }) async setup(state: AgentState, ctx: RunContext) { await this.documentStore.save(LlmMessageDocument, { role: 'user', text: ctx.args.instructions, }); } @Transition({ from: 'ready', to: 'prompt_executed' }) async llmTurn(state: AgentState) { const result = await this.llmGenerateText.call( {}, { config: { provider: 'claude', model: 'claude-sonnet-4-6', system: 'You are a custom agent.', tools: ['my_custom_tool'], }, }, ); this.assignState({ llmResult: result.data }); } @Transition({ from: 'prompt_executed', to: 'awaiting_tools', priority: 10 }) @Guard('hasToolCalls') async executeToolCalls(state: AgentState) { const result = await this.llmDelegateToolCalls.call({ message: state.llmResult!.message, tools: ['my_custom_tool'], callback: { transition: 'toolResultReceived' }, }); this.assignState({ delegateResult: result.data }); } @Transition({ from: 'awaiting_tools', to: 'awaiting_tools', wait: true }) async toolResultReceived(state: AgentState, input: TransitionInput) { const result = await this.llmUpdateToolResult.call({ delegateResult: state.delegateResult!, completedTool: input, }); this.assignState({ delegateResult: result.data }); } @Transition({ from: 'awaiting_tools', to: 'ready' }) @Guard('allToolsComplete') toolsComplete(state: AgentState) {} @Transition({ from: 'prompt_executed', to: 'end' }) @Guard('isDone') respond(_state: AgentState) {} private hasToolCalls(state: AgentState): boolean { return state.llmResult?.message.stopReason === 'tool_use'; } private allToolsComplete(state: AgentState): boolean { return state.delegateResult?.allCompleted ?? false; } private isDone(state: AgentState): boolean { return state.llmResult?.message.stopReason === 'end_turn'; } } ``` `LlmGenerateTextTool`, `LlmDelegateToolCallsTool`, and `LlmUpdateToolResultTool` all persist their messages automatically — the assistant turn after `llmGenerateText`, and the `tool_result` user turn when all delegated tools complete (sync or async). Pass `config: { save: false }` on any of them if you want to take over persistence. ### Adding User Interaction Pause for user input between LLM turns: ```typescript // Instead of final transition, go to waiting_for_user @Transition({ from: 'prompt_executed', to: 'waiting_for_user' }) @Guard('isDone') respondToUser(state: AgentState) {} @Transition({ from: 'waiting_for_user', to: 'ready', wait: true, schema: z.string() }) async userMessage(state: AgentState, input: TransitionInput) { await this.documentStore.save(LlmMessageDocument, { role: 'user', text: input.data, }); } ``` > **Tip:** The `@loopstack/agent` package ships `ChatAgentWorkflow` which implements this pattern out of the box. Use it when you need a multi-turn chat agent without customization. ### Wrapping an Agent as a Tool Make an agent callable by other agents via a task tool: ```typescript @Tool({ name: 'explore_codebase', description: 'Launch a sub-agent to explore the codebase.', schema: z.object({ instructions: z.string() }), }) export class ExploreTask extends BaseTool { constructor(private readonly agentWorkflow: AgentWorkflow) { super(); } protected async handle( args: { instructions: string }, ctx: RunContext, options?: ToolCallOptions, ): Promise { const result = await this.agentWorkflow.run( { system: 'You are a codebase exploration agent.', tools: ['glob', 'grep', 'read'], userMessage: args.instructions, }, { callback: options?.callback }, ); return { data: { workflowId: result.workflowId }, pending: { workflowId: result.workflowId }, }; } async complete(result: Record): Promise { const data = result as { data?: { response?: string } }; return { data: data.data?.response ?? result }; } } ``` This enables multi-agent architectures where an orchestrator agent delegates tasks to specialized sub-agents. ## Registry References - [@loopstack/agent](/docs/registry/agent) — Built-in agent workflow module - [@loopstack/code-agent](/docs/registry/code-agent) — Code exploration agent (ExploreTask) built on @loopstack/agent - [Tool Errors example](/docs/examples/agent#tool-errors) — Example demonstrating tool error handling and recovery --- > Source: https://loopstack.ai/llms/build/ai/chat-flows.md --- title: Chat Flows description: Building multi-turn conversational workflows with LLMs using LlmMessageDocument, messagesSearchTag pattern, and wait transitions for user input. --- # Chat Flows Build multi-turn conversational workflows where users exchange messages with an LLM. Messages are persisted as documents and accumulated across turns using the `messagesSearchTag` pattern. ## Example ```typescript import { z } from 'zod'; import { BaseWorkflow, Transition, type TransitionInput, Workflow } from '@loopstack/common'; import { LlmContextDocument, LlmGenerateTextTool, LlmMessageDocument } from '@loopstack/llm-provider'; @Workflow({ widget: './chat.ui.yaml' }) export class ChatWorkflow extends BaseWorkflow { constructor(private readonly llmGenerateText: LlmGenerateTextTool) { super(); } @Transition({ to: 'waiting_for_user' }) async setup(state: Record) { await this.documentStore.save(LlmContextDocument, { role: 'user', text: this.render(join(__dirname, 'templates', 'systemMessage.md')), }); } @Transition({ from: 'waiting_for_user', to: 'ready', wait: true, schema: z.string() }) async userMessage(state: Record, input: TransitionInput) { await this.documentStore.save(LlmMessageDocument, { role: 'user', text: input.data }); } @Transition({ from: 'ready', to: 'waiting_for_user' }) async llmTurn(state: Record) { await this.llmGenerateText.call({}, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }); } } ``` ## YAML Config ```yaml title: 'Chat Assistant' ui: widgets: - widget: prompt-input enabledWhen: - waiting_for_user options: transition: userMessage ``` ## How Message Accumulation Works 1. All messages are saved as `LlmMessageDocument` — automatically tagged with `message` 2. The LLM provider module collects all documents with the `message` tag as conversation history by default 3. Each new message adds to the conversation — the LLM sees the full history on every turn ## Message Resolution When `LlmGenerateTextTool.call()` runs, it resolves the conversation in this priority order: 1. **`args.prompt`** — if provided, used as a single user message. Documents are ignored. 2. **`args.messages`** — if provided (and no `prompt`), used as the full message array. Documents are ignored. 3. **Documents matching `config.messagesSearchTag`** — fallback when neither arg is set. Defaults to `'message'`. When falling back to documents, the tool: - Filters `DocumentEntity` records by `doc.tags.includes(messagesSearchTag)` - Excludes any document with `doc.isInvalidated === true` - Sorts by `doc.index` to preserve chronological order - Replays an assistant message's native response (`doc.meta.response`) when the same provider wrote it, and otherwise rebuilds the message from its normalized content — see [LLM Providers — Switching Provider Within a Conversation](./llm-providers.md#switching-provider-within-a-conversation) This means you can run parallel conversation threads in the same workflow by saving messages under different tags and switching `messagesSearchTag` per call: ```typescript // Save a summary-thread message await this.documentStore.save( LlmMessageDocument, { role: 'user', text: 'Summarize the discussion so far.' }, { tags: ['summary-chat'] }, ); // Call the LLM with only the summary thread as history await this.llmGenerateText.call( {}, { config: { provider: 'claude', model: 'claude-sonnet-4-6', messagesSearchTag: 'summary-chat' } }, ); ``` If a message isn't appearing in the LLM context, check that it has the expected tag and is not invalidated. ## Chat Loop Flow ``` setup → waiting_for_user → [user sends message] → ready → llmTurn → waiting_for_user (loop) ``` 1. **Initial transition** — Create system message (hidden from UI) 2. Workflow enters `waiting_for_user` — UI shows the prompt-input widget 3. User sends message → `userMessage` fires, saves user message as document 4. `llmTurn` fires — calls the LLM with full message history, saves response 5. Workflow returns to `waiting_for_user` — loop continues ## Combining with Tool Calling Add tool calling to a chat flow by combining the patterns from [AI Tool Calling](./tool-calling.md): ```typescript @Transition({ from: 'ready', to: 'prompt_executed' }) async llmTurn(state: ChatState) { const result = await this.llmGenerateText.call( {}, { config: { provider: 'claude', model: 'claude-sonnet-4-6', tools: ['get_weather', 'search_database'] } }, ); this.assignState({ llmResult: result.data }); } @Transition({ from: 'prompt_executed', to: 'awaiting_tools', priority: 10 }) @Guard('hasToolCalls') async executeToolCalls(state: ChatState) { ... } @Transition({ from: 'prompt_executed', to: 'waiting_for_user' }) respond(state: ChatState) {} ``` ## Registry References - [Prompt Input Chat example](/docs/examples/hitl#prompt-input-chat) — Multi-turn chat loop with the prompt-input widget, without an LLM - [Custom Agent example](/docs/examples/agent#custom-agent) — Tool calling loop built from the delegate primitives --- > Source: https://loopstack.ai/llms/build/ai/llm-providers.md --- title: LLM Providers description: Using multiple LLM providers (Claude, OpenAI) through the runtime provider registry. Covers LlmProviderModule setup, provider selection per-call, switching providers without code changes, and which message history (meta.response, meta.provider, content blocks) and server tools carry over when a conversation switches provider. --- # LLM Providers Loopstack supports multiple LLM providers through a runtime registry. Provider modules self-register at startup. Workflows and tools resolve providers by name — swap or use multiple providers in parallel without changing workflow code. ## Quick Start Import `LlmProviderModule` for the adapter tools and a provider module (e.g. `ClaudeModule`) to register the LLM backend: ```typescript import { ClaudeModule } from '@loopstack/claude'; import { LlmProviderModule } from '@loopstack/llm-provider'; @Module({ imports: [LoopstackModule.forRoot(), LlmProviderModule, ClaudeModule], }) export class AppModule {} ``` > **`LlmProviderModule` is required, and must be imported before any provider module.** > > `LlmProviderModule` registers `LlmProviderRegistry` — the runtime registry that provider modules (`ClaudeModule`, `OpenAiModule`) inject to self-register their backends. Importing a provider module without `LlmProviderModule` fails at boot with `UnknownDependenciesException` on `LlmProviderRegistry` (and on `ClaudeLlmProvider` / `OpenAiLlmProvider`, which depend on it). > > Any of these forms registers the registry: bare `LlmProviderModule`, `LlmProviderModule.forRoot(config)`, or `LlmProviderModule.forFeature(config)` (the feature form imports the global root transitively). Pick `forRoot` when setting app-wide defaults, `forFeature` for per-module overrides, and the bare import when no defaults are needed. ## Module-Level Defaults Use `LlmProviderModule.forRoot()` to set a default model for all LLM calls in your app. Use `forFeature()` to override per-module: ```typescript // app.module.ts — global default model @Module({ imports: [LoopstackModule.forRoot(), LlmProviderModule.forRoot({ model: 'claude-sonnet-4-5' }), ClaudeModule], }) export class AppModule {} ``` ```typescript // premium-feature.module.ts — this module uses a stronger model @Module({ imports: [LlmProviderModule.forFeature({ model: 'claude-opus-4-6' })], providers: [PremiumWorkflow], }) export class PremiumFeatureModule {} ``` ## Per-Call Configuration Override provider and model at individual call sites via `options.config`. Per-call config always takes priority over module defaults. ```typescript export class MyWorkflow extends BaseWorkflow { constructor( private readonly llmGenerateText: LlmGenerateTextTool, private readonly llmDelegateToolCalls: LlmDelegateToolCallsTool, ) { super(); } } ``` ```typescript const result = await this.llmGenerateText.call( { prompt: 'Hello!' }, { config: { provider: 'claude', model: 'claude-opus-4-6', system: 'You are a helpful assistant.', messagesSearchTag: 'message', tools: ['get_weather'], }, }, ); ``` ### Args vs Config LLM tools separate **args** (per-request data) from **config** (provider/model/behavior settings). For `LlmGenerateTextTool`, the input args are `prompt` and `messages`; `outputSchema` applies only to `LlmGenerateObjectTool`. See [Text Generation](./text-generation.md) for full call examples. | Parameter | Location | Description | | ------------------- | -------- | ------------------------------------------ | | `prompt` | args | Simple prompt string | | `messages` | args | Explicit message array | | `outputSchema` | args | JSON Schema (`LlmGenerateObjectTool` only) | | `provider` | config | LLM provider name (e.g. `'claude'`) | | `model` | config | Model name (e.g. `'claude-sonnet-4-6'`) | | `system` | config | System prompt | | `messagesSearchTag` | config | Load messages from documents by tag | | `tools` | config | Tool names the LLM can call | ## Using Multiple Providers Import both modules and configure each call with its provider: ```typescript @Module({ imports: [LoopstackModule.forRoot(), ClaudeModule, OpenAiModule], }) export class AppModule {} ``` ```typescript // Use Claude for complex tasks const smartResult = await this.llmGenerateText.call( { prompt: 'Analyze this code...' }, { config: { provider: 'claude', model: 'claude-opus-4-6' } }, ); // Use OpenAI for simple tasks const fastResult = await this.llmGenerateText.call( { prompt: 'Summarize in one line...' }, { config: { provider: 'openai', model: 'gpt-4o-mini' } }, ); ``` ### Switching Provider Within a Conversation A conversation saved as `LlmMessageDocument`s can start on one provider and continue on another. Each assistant message saved by `LlmGenerateTextTool` keeps the native API response in `meta.response` and the id of the provider that wrote it in `meta.provider`. A provider replays the native response only when `meta.provider` is its own id. Every other message is rebuilt from its normalized `text` and `blocks`. What carries over to the other provider: | Content | Carries over | | ------------------------------------------------- | --------------------------------------------------------------------------------- | | `text` blocks | Yes | | `tool_call` and `tool_result` blocks | Yes — tool call ids, names and arguments are kept | | `thinking` blocks | No — the OpenAI provider leaves them out | | `server_tool_use` and `server_tool_result` blocks | No — the OpenAI provider leaves them out. The answer text after a search is kept. | Server tools such as `claude_native_web_search` produce one provider's native tool spec, so they run only on that provider. The OpenAI provider rejects a call that lists a server tool with `Server tool '' is not supported by the openai provider` — remove the server tool from `config.tools` when you move that call to OpenAI. ## Provider-Specific Configuration `config.providerConfig` is an opaque pass-through to the active provider — its shape depends on which provider handles the call. Use it for tuning behavior beyond the cross-provider config fields (system prompt, tools, etc.). Provider-specific config is per-call only. The cross-provider fields `provider` and `model` can also be set at module level via `LlmProviderModule.forRoot()` / `forFeature()` (see [Module-Level Defaults](#module-level-defaults)) — per-call config always takes priority. ```typescript await this.llmGenerateText.call( { prompt: 'Write a haiku about coffee' }, { config: { provider: 'claude', model: 'claude-sonnet-4-6', providerConfig: { maxTokens: 1024, temperature: 0.7, cache: true, }, }, }, ); ``` ### `ClaudeProviderConfig` | Field | Type | Description | | --------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `maxTokens` | `number` | Maximum tokens to generate | | `temperature` | `number` | Sampling temperature (0–1) | | `stopSequences` | `string[]` | Stop generation when any of these strings is produced | | `cache` | `boolean` | Enable Anthropic prompt caching. Places cache breakpoints on the system prompt, tool definitions, and the last message automatically — useful for multi-turn workflows where the prefix is reused. | | `envApiKey` | `string` | Env var name holding the API key (defaults to `ANTHROPIC_API_KEY`) | ### `OpenAiProviderConfig` | Field | Type | Description | | ------------------ | ---------- | --------------------------------------------------------------- | | `maxTokens` | `number` | Maximum tokens to generate | | `temperature` | `number` | Sampling temperature (0–2) | | `stopSequences` | `string[]` | Stop generation when any of these strings is produced | | `frequencyPenalty` | `number` | -2.0 to 2.0; reduces token repetition | | `presencePenalty` | `number` | -2.0 to 2.0; encourages topic diversity | | `envApiKey` | `string` | Env var name holding the API key (defaults to `OPENAI_API_KEY`) | ## Adapter Tools All LLM interactions go through adapter tools from `@loopstack/llm-provider`. This ensures validation, interceptors, and logging apply to every LLM call. | Tool | Purpose | | -------------------------- | --------------------------------------------- | | `LlmGenerateTextTool` | Text generation with optional tool calling | | `LlmGenerateObjectTool` | Structured output conforming to a JSON Schema | | `LlmDelegateToolCallsTool` | Execute tool calls from an LLM response | | `LlmUpdateToolResultTool` | Handle async tool completion callbacks | ## Message Documents All providers share a single `LlmMessageDocument` with normalized content. Native API responses are stored in `entity.meta.response`, and the provider that wrote them in `entity.meta.provider`, for provider-specific round-trips — see [Switching Provider Within a Conversation](#switching-provider-within-a-conversation). See [Chat Flows — Message Resolution](./chat-flows.md#message-resolution) for how documents are collected from the document store and become the LLM's conversation history. | Document | Content Format | Widget | | -------------------- | --------------------------------------------------- | ------------- | | `LlmMessageDocument` | Normalized (`text`, `thinking`, `tool_call` blocks) | `llm-message` | ### Response shape `LlmGenerateTextResult.data.message` is an `LlmNormalizedMessage` — two views of the same response: | Field | Type | Description | | ------------ | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `role` | `'user' \| 'assistant'` | Message role | | `text` | `string` | Plain-text projection — concatenated `text`-type blocks. Always populated by providers. Use this when you just want a string. | | `blocks` | `LlmContentBlock[]` (optional) | Structured content blocks. Use this to inspect tool calls, thinking output, or render block-by-block. | | `stopReason` | `'end_turn' \| 'tool_use' \| 'max_tokens' \| 'stop_sequence'` | Why generation stopped | | `id` | `string` (optional) | Provider-assigned message ID | `text` is derived from `blocks` (text-type blocks joined with `\n`; `thinking` and tool blocks excluded). Both fields are populated by every provider, so you can pick whichever fits the call site without checking for `undefined`. Content blocks are one of: - `{ type: 'text', text: string }` — text output - `{ type: 'thinking', text: string }` — reasoning/thinking output - `{ type: 'tool_call', id: string, name: string, args: Record }` — tool call - `{ type: 'tool_result', toolCallId: string, content: string, isError: boolean }` — tool result (user-side, fed back to the LLM next turn) ### Writing messages — `text` vs `blocks` Assistant messages (and the user-side `tool_result` turn) are saved automatically by `LlmGenerateTextTool` / `LlmDelegateToolCallsTool`. When you save an `LlmMessageDocument` manually — for user input, seed messages, or system primers — the same two fields are available, both optional. Provide whichever fits: ```typescript // Plain text message — most common case await this.documentStore.save(LlmMessageDocument, { role: 'user', text: 'Hello!' }); // Structured message — multi-block content await this.documentStore.save(LlmMessageDocument, { role: 'user', blocks: [{ type: 'text', text: 'See attached.' }], }); ``` You don't need to fill both. The renderer and downstream providers fall back gracefully: if only `text` is set, it's rendered as a single text bubble; if only `blocks` is set, the text projection is derived from text-type blocks on demand. See [Creating LLM Providers](../../extend/llm-providers.md) for the full interface. ## Environment Variables | Variable | Provider | Description | | ------------------- | -------- | ---------------------- | | `ANTHROPIC_API_KEY` | Claude | API key | | `OPENAI_API_KEY` | OpenAI | API key | | `CLAUDE_MODEL` | Claude | Default model fallback | | `OPENAI_MODEL` | OpenAI | Default model fallback | ## Available Providers | Provider | Module | ID | | ---------------- | ------------------- | ---------- | | Anthropic Claude | `@loopstack/claude` | `'claude'` | | OpenAI | `@loopstack/openai` | `'openai'` | To create a custom provider, see [Creating LLM Providers](../../extend/llm-providers.md). --- > Source: https://loopstack.ai/llms/build/ai/structured-output.md --- title: AI Structured Output description: Forcing LLMs to return structured JSON data using LlmGenerateObjectTool with Zod schemas. Provider-agnostic — works with Claude, OpenAI, and other providers. --- # AI Structured Output Use `LlmGenerateObjectTool` from `@loopstack/llm-provider` to generate structured data conforming to a JSON Schema. Provider-agnostic — works with Claude, OpenAI, and other providers. ## Define a Document ```typescript import { z } from 'zod'; import { Document } from '@loopstack/common'; export const FileDocumentSchema = z .object({ filename: z.string(), description: z.string(), code: z.string(), }) .strict(); export type FileDocumentType = z.infer; @Document({ schema: FileDocumentSchema, widget: './file-document.yaml', }) export class FileDocument { filename: string; description: string; code: string; } ``` ## Workflow Example ```typescript import { toJSONSchema, z } from 'zod'; import { BaseWorkflow, DocumentEntity, Transition, Workflow } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; import type { LlmGenerateObjectResult } from '@loopstack/llm-provider'; import { LlmGenerateObjectTool, LlmMessageDocument } from '@loopstack/llm-provider'; import { FileDocument, FileDocumentSchema, FileDocumentType } from './documents/file-document'; interface StructuredOutputState { language?: string; llmResult?: DocumentEntity; } const StructuredOutputSchema = z.object({ language: z.enum(['python', 'javascript', 'java', 'cpp', 'ruby', 'go', 'php']).default('python'), }); type StructuredOutputArgs = z.infer; @Workflow({ schema: StructuredOutputSchema, }) export class PromptStructuredOutputWorkflow extends BaseWorkflow { constructor(private readonly llmGenerateObject: LlmGenerateObjectTool) { super(); } @Transition({ to: 'ready' }) async greeting(state: StructuredOutputState, ctx: RunContext) { await this.documentStore.save( LlmMessageDocument, { role: 'assistant', text: `Creating a Hello World script in ${ctx.args.language}...` }, { key: 'status' }, ); this.assignState({ language: ctx.args.language }); } @Transition({ from: 'ready', to: 'prompt_executed' }) async prompt(state: StructuredOutputState) { const result = await this.llmGenerateObject.call( { outputSchema: toJSONSchema(FileDocumentSchema) as Record, prompt: this.render(join(__dirname, 'templates', 'prompt.md'), { language: state.language }), }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); const objectResult = result.data as LlmGenerateObjectResult; const llmResult = await this.documentStore.save(FileDocument, objectResult.data as FileDocumentType, { validate: 'skip', }); this.assignState({ llmResult }); } @Transition({ from: 'prompt_executed', to: 'end' }) async respond(state: StructuredOutputState) { await this.documentStore.save( LlmMessageDocument, { role: 'assistant', text: `Generated: ${state.llmResult?.content?.description ?? ''}` }, { key: 'status' }, ); } } ``` ## How It Works 1. Convert your Zod schema to JSON Schema using `toJSONSchema()` 2. Pass the JSON Schema as `outputSchema` to `llmGenerateObject.call()` 3. The provider forces the LLM to return data matching the schema 4. Save the result as a typed document using `this.documentStore.save()` ## Key Parameters ```typescript await this.llmGenerateObject.call( { outputSchema: toJSONSchema(MyDocumentSchema) as Record, prompt: 'Generate structured data.', }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); ``` ## Registry References - [Structured Output example](/docs/examples/llm#structured-output) — Generates structured code files using the LLM provider --- > Source: https://loopstack.ai/llms/build/ai/text-generation.md --- title: AI Text Generation description: Calling LLMs for text generation using LlmGenerateTextTool. Covers setup, system prompts, message history, provider selection, prompt caching, and streaming. --- # AI Text Generation Generate text from any configured LLM provider using `LlmGenerateTextTool`. Pass prompts, system instructions, and message history — the tool handles provider routing, token counting, and optional streaming. ## Setup ```typescript import { Module } from '@nestjs/common'; import { ClaudeModule } from '@loopstack/claude'; import { LlmProviderModule } from '@loopstack/llm-provider'; @Module({ imports: [LlmProviderModule, ClaudeModule], providers: [PromptWorkflow], exports: [PromptWorkflow], }) export class PromptModule {} ``` `LlmProviderModule` registers the global provider registry that adapter tools (`LlmGenerateTextTool`, `LlmGenerateObjectTool`) and provider implementations (`ClaudeLlmProvider`) depend on. Without it, NestJS throws `UnknownDependenciesException` for `LlmProviderRegistry` at boot. See [LLM Providers](./llm-providers.md) for details and module-level defaults. ## Example Workflow ```typescript import { z } from 'zod'; import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; import { LlmGenerateTextTool } from '@loopstack/llm-provider'; const PromptSchema = z.object({ subject: z.string().default('coffee'), }); type PromptArgs = z.infer; @Workflow({ schema: PromptSchema, }) export class PromptWorkflow extends BaseWorkflow { constructor(private readonly llmGenerateText: LlmGenerateTextTool) { super(); } @Transition({ to: 'end' }) async prompt(state: Record, ctx: RunContext) { await this.llmGenerateText.call( { prompt: this.render(join(__dirname, 'templates', 'prompt.md'), { subject: ctx.args.subject }), }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); } } ``` ## Reading the Response A normalized result has two views of the assistant's reply: - `result.data.message.text` — the plain-text projection (always populated). This is what you want in 95% of cases. - `result.data.message.blocks` — the structured content blocks (`text`, `thinking`, `tool_call`, etc.). Use these when you need to inspect tool calls, thinking output, or render block-by-block. ```typescript const result = await this.llmGenerateText.call({ prompt: 'Write a haiku about coffee' }); const text = result.data.message.text; ``` Both views are derived from the same underlying response — `text` is the concatenation of all `text`-type blocks, with `thinking` and tool blocks filtered out. ## Call Options ```typescript await this.llmGenerateText.call( { // Option 1: Simple prompt prompt: 'Write a haiku about coffee', // Option 2: Explicit messages — `text` for plain content, `blocks` for structured messages: [{ role: 'user', text: 'Write a haiku about coffee' }], }, { config: { provider: 'claude', model: 'claude-sonnet-4-6', system: 'You are a helpful assistant.', // Option 3: Collect documents by tag as conversation history messagesSearchTag: 'message', }, }, ); ``` ## Persisting the Response The tool saves the assistant message as an `LlmMessageDocument` automatically — no manual `documentStore.save()` is required. Two config knobs control this: - `config: { save: false }` — opt out entirely. Use this when you want to inspect, transform, or persist the response yourself (see [Multi-Provider example](/docs/examples/llm#multi-provider) for a worked case). - `config: { meta: {...} }` — merge extra metadata into the auto-saved document. Free-form payload that downstream readers can pick up off `document.meta`. To run a "silent" turn the LLM remembers but the user doesn't see, opt out of auto-save and persist the result as `LlmContextDocument` (declared `internal: true`, so Studio never sees it): ```typescript const result = await this.llmGenerateText.call( { prompt: 'Summarize the previous turn in one sentence for internal reasoning.' }, { config: { provider: 'claude', save: false } }, ); await this.documentStore.save(LlmContextDocument, { role: 'assistant', text: result.data.message.text ?? '', }); ``` Other documents (user inputs, seed system messages, structured outputs) stay manual — see [Chat Flows](./chat-flows.md) for the two halves side by side. ## Using Templates Render Handlebars templates for complex prompts (`this.render()` is available from `BaseWorkflow`): ```typescript const rendered = this.render(join(__dirname, 'templates', 'prompt.md'), { subject: ctx.args.subject, }); const result = await this.llmGenerateText.call( { prompt: rendered }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); ``` ## Streaming LLM responses stream to Studio automatically — no opt-in, no code changes. Whenever a workflow runs in a context that has a connected Studio client (`ctx.workflowId`, `ctx.userId`, and an active `ClientMessageService`), `LlmGenerateTextTool` assigns a `streamMessageId`, passes an `onStream` callback to the provider, and forwards each event to Studio as it arrives. The workflow itself still receives the complete `LlmGenerateTextResult` after the stream finishes — streaming is a side-effect for the UI, not a change to the return value. ### Lifecycle in Studio 1. Tool dispatches `llm.response.start` with a fresh `streamMessageId`. 2. Provider emits `text_delta`, `thinking_delta`, and `tool_call` events as content arrives. Studio renders an in-flight message keyed by `streamMessageId`. 3. Tool dispatches `llm.response.done` with the final normalized message; the result is returned to the workflow. 4. The tool persists an `LlmMessageDocument` for the assistant turn automatically. The saved document inherits `streamMessageId` as its `id`, so Studio **replaces** the in-flight streamed message with the final document — same ID, same slot. No duplicate bubble. Pass `config: { save: false }` if you want to handle persistence yourself. This is why you don't need to do anything special to "finalize" the stream: the document save naturally takes over from the stream because they share the same `id`. ### Custom providers If you're implementing a custom `LlmProviderInterface`, honor the `onStream` callback in `LlmGenerateTextArgs` — call it with `LlmStreamEvent`s (`start`, `text_delta`, `thinking_delta`, `tool_call`, `done`, `error`) as content arrives. Providers that don't stream can ignore it; the framework still returns the final result correctly. See [Creating LLM Providers](../../extend/llm-providers.md) for the full event union. ## Environment Variables | Variable | Description | | ------------------- | ----------------- | | `ANTHROPIC_API_KEY` | Anthropic API key | ## Registry References - [Prompt example](/docs/examples/llm#prompt) — Single-turn prompt with subject parameter and Handlebars template --- > Source: https://loopstack.ai/llms/build/ai/tool-calling.md --- title: AI Tool Calling description: Enabling LLMs to invoke workflow tools via function calling. Covers LlmDelegateToolCallsTool, tool descriptions, passing tools to LLM calls, and handling tool results. --- # AI Tool Calling Enable the LLM to call workflow tools (function calling). The LLM decides which tools to invoke, and `LlmDelegateToolCallsTool` executes them. ## Create a Tool for the LLM Tools exposed to the LLM need a `description` so the LLM knows when to use them: ```typescript import { z } from 'zod'; import { BaseTool, Tool, ToolEnvelope } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; @Tool({ name: 'get_weather', description: 'Retrieve weather information.', schema: z.object({ location: z.string().describe('City or location name'), }), }) export class GetWeather extends BaseTool<{ location: string }, object, string> { protected async handle(): Promise> { return Promise.resolve({ type: 'text', data: 'Mostly sunny, 14C, rain in the afternoon.' }); } } ``` ## Tool Calling Workflow `LlmDelegateToolCallsTool` always dispatches tools with a callback so sub-workflow / HITL / async tools work safely. A `wait: true` self-loop on `awaiting_tools` catches each completion via `LlmUpdateToolResultTool`. Synchronous tools complete immediately and the loop falls through to `toolsComplete`. ```typescript import { BaseWorkflow, Guard, Transition, Workflow } from '@loopstack/common'; import type { LlmDelegateResult, LlmGenerateTextResult } from '@loopstack/llm-provider'; import { LlmDelegateToolCallsTool, LlmGenerateTextTool, LlmMessageDocument, LlmUpdateToolResultTool, } from '@loopstack/llm-provider'; import { GetWeather } from './tools/get-weather.tool'; interface ToolCallState { llmResult?: LlmGenerateTextResult; delegateResult?: LlmDelegateResult; } @Workflow({}) export class ToolCallWorkflow extends BaseWorkflow { constructor( private readonly llmGenerateText: LlmGenerateTextTool, private readonly llmDelegateToolCalls: LlmDelegateToolCallsTool, private readonly llmUpdateToolResult: LlmUpdateToolResultTool, private readonly getWeather: GetWeather, ) { super(); } @Transition({ to: 'ready' }) async setup(state: ToolCallState) { await this.documentStore.save(LlmMessageDocument, { role: 'user', text: 'How is the weather in Berlin?', }); } @Transition({ from: 'ready', to: 'prompt_executed' }) async llmTurn(state: ToolCallState) { const result = await this.llmGenerateText.call( {}, { config: { provider: 'claude', model: 'claude-sonnet-4-6', tools: ['get_weather'] } }, ); this.assignState({ llmResult: result.data }); } @Transition({ from: 'prompt_executed', to: 'awaiting_tools', priority: 10 }) @Guard('hasToolCalls') async executeToolCalls(state: ToolCallState) { const result = await this.llmDelegateToolCalls.call({ message: state.llmResult!.message, tools: ['get_weather'], callback: { transition: 'toolResultReceived' }, }); this.assignState({ delegateResult: result.data }); } hasToolCalls(state: ToolCallState): boolean { return state.llmResult?.message.stopReason === 'tool_use'; } @Transition({ from: 'awaiting_tools', to: 'awaiting_tools', wait: true }) async toolResultReceived(state: ToolCallState, payload: unknown) { const result = await this.llmUpdateToolResult.call({ delegateResult: state.delegateResult!, completedTool: payload, }); this.assignState({ delegateResult: result.data }); } @Transition({ from: 'awaiting_tools', to: 'ready' }) @Guard('allToolsComplete') toolsComplete(state: ToolCallState) {} allToolsComplete(state: ToolCallState): boolean { return state.delegateResult?.allCompleted ?? false; } @Transition({ from: 'prompt_executed', to: 'end' }) respond(_state: ToolCallState) {} } ``` Both `LlmGenerateTextTool` and `LlmDelegateToolCallsTool` persist their messages automatically — the assistant turn and the `tool_result` user turn appear in the document store and conversation history without any explicit `documentStore.save()` call. Pass `config: { save: false }` on either tool if you need to handle persistence yourself. ## How the Loop Works ``` setup → llmTurn → [hasToolCalls?] ├─ yes → executeToolCalls → awaiting_tools │ ├─ toolResultReceived (wait, self-loop on async completions) │ └─ toolsComplete (@Guard allToolsComplete) → llmTurn (loop) └─ no → respond (done) ``` 1. `llmGenerateText` is called — the `tools` array in config lists available tools 2. If the LLM returns `stopReason: 'tool_use'`, the guard routes to `executeToolCalls` 3. `llmDelegateToolCalls` dispatches each tool with a callback. Synchronous tools complete immediately; async tools (sub-workflows, HITL) return `pending: true` and fire `toolResultReceived` once each 4. When `delegateResult.allCompleted` is true, the unguarded fall-through (`toolsComplete`) loops back to the LLM 5. When the LLM is done (no more tool calls), the fallback transition to `end` fires ## Key Concepts - **`tools` array in config** — Lists tool names the LLM can call. Names must match `@Tool({ name })` values. At startup, Loopstack auto-discovers every `@Tool()`-decorated provider in the module graph and indexes them by name. If a name doesn't match, you'll get an error listing all registered tools — useful for catching typos and missing module imports. - **`llmDelegateToolCalls`** — Dispatches tool calls from the LLM response message with a callback transition. Pass it the same `tools` list you gave `llmGenerateText`: only those tools are executed. Required for safety: sub-workflow / HITL / any tool that returns `pending: true` only completes once its callback fires - **`llmUpdateToolResult`** — Merges each async tool completion into the running `delegateResult`. The `wait: true` self-loop on `awaiting_tools` calls it once per completion - **`message.stopReason === 'tool_use'`** — The LLM wants to call a tool - **`allCompleted`** — All delegated tool calls have finished - **`@Guard` + `priority`** — Routes between tool calling and final response ## Under the Hood: How `llmDelegateToolCalls` Works `LlmDelegateToolCallsTool` is what makes a tool-calling workflow actually do work. Without it, the LLM's `tool_call` blocks would just sit in the message — nothing would be executed. The tool reads the most recent assistant message, runs every tool the LLM requested, and stores the outputs back as `tool_result` entries that the next LLM turn can read. Internally it delegates to `LlmDelegateService`, which: 1. **Refuses tools the LLM was not offered** — a tool call whose name is not in the `tools` arg is never executed; it becomes a `tool_result` with `isError: true` (`Tool "x" is not available to this agent`), so the LLM sees it and can correct itself. 2. **Resolves each allowed tool by name** from the global tool registry (the same one built by `@Tool()` auto-discovery). 3. **Dispatches all tool calls in parallel** with `Promise.all` — the LLM is free to request multiple tools in one turn, and they run concurrently. 4. **Catches errors per tool** so one failing tool doesn't crash the others. Failures show up as `tool_result` entries with `isError: true` and are also collected on `result.errors` for inspection. 5. **Tracks pending async tools** — tools that return `{ pending: true }` (typically [HITL](./agent-workflows.md#adding-user-interaction) or sub-workflow tools) don't produce a result immediately. The result includes a `pendingCount`, and `allCompleted` stays `false` until those tools fire their completion callbacks. `LlmUpdateToolResultTool` is the companion that processes those callbacks and updates the delegate result. The `callback` arg is required — it's how async tool completions find their way back to the workflow. For all-synchronous tool sets, `allCompleted` is already true when `executeToolCalls` returns and the `wait` transition is never entered; the callback is harmless overhead. For mixed or async-only sets, the `wait` transition is what keeps the workflow from silently hanging on pending tools. ## Registry References - [Agent example](/docs/examples/agent#agent) — Parent workflow that delegates to `AgentWorkflow` for tool-calling with weather and calculator tools - [Custom Agent example](/docs/examples/agent#custom-agent) — Reference for hand-rolling the tool loop when you need custom error policy or per-turn logic --- > Source: https://loopstack.ai/llms/build/ai/usage-tracking.md --- title: AI Token Usage Tracking description: Reading LlmUsage from LLM tool results. Every LLM tool (LlmGenerateTextTool, LlmGenerateObjectTool, document generation) returns LlmResultMeta with provider, model, and a usage breakdown — inputTokens, outputTokens, cacheCreationInputTokens, cacheReadInputTokens, reasoningTokens. --- # AI Token Usage Tracking Every LLM tool call returns token usage on `result.metadata`. The shape is the same regardless of which tool produced the result — `LlmGenerateTextTool`, `LlmGenerateObjectTool`, and any other LLM-backed tool all return `LlmResultMeta` with a `usage?: LlmUsage`. Read it to log costs, enforce budgets, or report consumption back to users. ## Result metadata shape ```typescript type LlmResultMeta = { provider: string; // e.g. 'claude', 'openai' model: string; // e.g. 'claude-sonnet-4-6' usage?: LlmUsage; }; interface LlmUsage { inputTokens: number; outputTokens: number; cacheCreationInputTokens?: number; cacheReadInputTokens?: number; reasoningTokens?: number; } ``` | Field | Description | | -------------------------- | ----------------------------------------------------------------- | | `inputTokens` | Prompt tokens sent to the model | | `outputTokens` | Completion tokens produced | | `cacheCreationInputTokens` | Tokens written to the prompt cache (provider-dependent) | | `cacheReadInputTokens` | Tokens served from the prompt cache | | `reasoningTokens` | Internal reasoning tokens (e.g. Claude thinking, OpenAI o-series) | `usage` is optional — providers that don't report token counts will omit it. ## Reading usage from a tool call ```typescript const result = await this.llmGenerateText.call( { prompt: 'Write a haiku about coffee' }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); const { provider, model, usage } = result.metadata; if (usage) { console.log( `${provider}/${model}:`, `in=${usage.inputTokens}`, `out=${usage.outputTokens}`, `cacheRead=${usage.cacheReadInputTokens ?? 0}`, ); } ``` The same access pattern works for `LlmGenerateObjectTool` and any other LLM-backed tool that returns `LlmResultMeta`. ## Persisting usage in workflow state If you need usage downstream (for billing, reporting, or aggregation across multiple calls), store `result.metadata` in the workflow state alongside the result: ```typescript interface PromptState { llmResult?: LlmGenerateTextResult; llmMeta?: LlmResultMeta; } @Transition({ to: 'prompt_executed' }) async prompt(state: PromptState, ctx: RunContext) { const result = await this.llmGenerateText.call( { prompt: 'Write a haiku' }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); this.assignState({ llmResult: result.data, llmMeta: result.metadata, }); } ``` ## See also - [Text Generation](./text-generation.md) — `LlmGenerateTextTool` call signature - [Structured Output](./structured-output.md) — `LlmGenerateObjectTool` call signature ---