# [Deprecated] Reset the latest workflow run Source: https://docs.output.ai/api-reference/[deprecated]-reset-the-latest-workflow-run /openapi.json post /workflow/{id}/reset Resets the latest run. Deprecated; use `POST /workflow/{id}/runs/{rid}/reset` to target a specific run. Scheduled for removal after 2026-07-16. # [Deprecated] Stop the latest workflow run Source: https://docs.output.ai/api-reference/[deprecated]-stop-the-latest-workflow-run /openapi.json patch /workflow/{id}/stop Stops the latest run of the given workflow. The returned `runId` reflects the run at describe-time and may differ from the cancelled run if a new execution started concurrently. Deprecated; use `PATCH /workflow/{id}/runs/{rid}/stop` to pin a specific run. Scheduled for removal after 2026-07-16. # [Deprecated] Terminate the latest workflow run Source: https://docs.output.ai/api-reference/[deprecated]-terminate-the-latest-workflow-run /openapi.json post /workflow/{id}/terminate Force terminates the latest run. Deprecated; use `POST /workflow/{id}/runs/{rid}/terminate` to target a specific run. Scheduled for removal after 2026-07-16. # A dummy post endpoint for test only Source: https://docs.output.ai/api-reference/a-dummy-post-endpoint-for-test-only /openapi.json post /heartbeat # Check if the API is ready to answer requests Source: https://docs.output.ai/api-reference/check-if-the-api-is-ready-to-answer-requests /openapi.json get /ready # Execute a workflow synchronously Source: https://docs.output.ai/api-reference/execute-a-workflow-synchronously /openapi.json post /workflow/run Executes a workflow and waits for it to complete before returning the result # Execute an update on an workflow Source: https://docs.output.ai/api-reference/execute-an-update-on-an-workflow /openapi.json post /workflow/{id}/update/{update} Always targets the latest run; `runId` cannot be pinned for Temporal update operations. # Get a specific workflow catalog by ID Source: https://docs.output.ai/api-reference/get-a-specific-workflow-catalog-by-id /openapi.json get /workflow/catalog/{id} # Get paginated workflow execution history Source: https://docs.output.ai/api-reference/get-paginated-workflow-execution-history /openapi.json get /workflow/{id}/history Returns decoded Temporal history events with optional payload inclusion. First page includes workflow metadata; subsequent pages return events only. # Get paginated workflow execution history for a specific run Source: https://docs.output.ai/api-reference/get-paginated-workflow-execution-history-for-a-specific-run /openapi.json get /workflow/{id}/runs/{rid}/history # Get the default workflow catalog Source: https://docs.output.ai/api-reference/get-the-default-workflow-catalog /openapi.json get /workflow/catalog # Get workflow execution status for a specific run Source: https://docs.output.ai/api-reference/get-workflow-execution-status-for-a-specific-run /openapi.json get /workflow/{id}/runs/{rid}/status # Get workflow execution status (latest run) Source: https://docs.output.ai/api-reference/get-workflow-execution-status-latest-run /openapi.json get /workflow/{id}/status Returns the status of the latest run for the given workflow. To pin a specific run, use `/workflow/{id}/runs/{rid}/status`. # Get workflow trace log data for a specific run Source: https://docs.output.ai/api-reference/get-workflow-trace-log-data-for-a-specific-run /openapi.json get /workflow/{id}/runs/{rid}/trace-log Returns trace data for a pinned workflow run. If trace is stored remotely (S3), fetches and returns the data inline. If trace is local only, returns the local path. # Get workflow trace log data (latest run) Source: https://docs.output.ai/api-reference/get-workflow-trace-log-data-latest-run /openapi.json get /workflow/{id}/trace-log Returns trace data for the latest run of the given workflow. If trace is stored remotely (S3), fetches and returns the data inline. If trace is local only, returns the local path. To pin a specific run, use `/workflow/{id}/runs/{rid}/trace-log`. # Health check the API Source: https://docs.output.ai/api-reference/health-check-the-api /openapi.json get /health # List workflow runs Source: https://docs.output.ai/api-reference/list-workflow-runs /openapi.json get /workflow/runs Returns a list of workflow runs with optional filtering by workflow type # Reset a specific workflow run to re-run from after a completed step Source: https://docs.output.ai/api-reference/reset-a-specific-workflow-run-to-re-run-from-after-a-completed-step /openapi.json post /workflow/{id}/runs/{rid}/reset Resets a pinned workflow run to the point after a completed step, creating a new run that replays from that point. The current execution is terminated. # Return the original input of a specific workflow run Source: https://docs.output.ai/api-reference/return-the-original-input-of-a-specific-workflow-run /openapi.json get /workflow/{id}/runs/{rid}/input # Return the original input of a workflow (latest run) Source: https://docs.output.ai/api-reference/return-the-original-input-of-a-workflow-latest-run /openapi.json get /workflow/{id}/input Returns the original input passed to the latest run of the given workflow. Works for workflows in any state, including running. To pin a specific run, use `/workflow/{id}/runs/{rid}/input`. # Return the result of a specific workflow run Source: https://docs.output.ai/api-reference/return-the-result-of-a-specific-workflow-run /openapi.json get /workflow/{id}/runs/{rid}/result # Return the result of a workflow (latest run) Source: https://docs.output.ai/api-reference/return-the-result-of-a-workflow-latest-run /openapi.json get /workflow/{id}/result Returns the result of the latest run for the given workflow. To pin a specific run, use `/workflow/{id}/runs/{rid}/result`. # Send a query to an workflow Source: https://docs.output.ai/api-reference/send-a-query-to-an-workflow /openapi.json post /workflow/{id}/query/{query} Always targets the latest run; `runId` cannot be pinned for Temporal query operations. # Send a signal to an workflow Source: https://docs.output.ai/api-reference/send-a-signal-to-an-workflow /openapi.json post /workflow/{id}/signal/{signal} Always targets the latest run; `runId` cannot be pinned for Temporal signal operations. # Send feedback to a workflow Source: https://docs.output.ai/api-reference/send-feedback-to-a-workflow /openapi.json post /workflow/{id}/feedback Always targets the latest run; `runId` cannot be pinned for Temporal signal operations. # Start a workflow asynchronously Source: https://docs.output.ai/api-reference/start-a-workflow-asynchronously /openapi.json post /workflow/start # Stop a specific workflow run Source: https://docs.output.ai/api-reference/stop-a-specific-workflow-run /openapi.json patch /workflow/{id}/runs/{rid}/stop # Stream pinned-run workflow history events via Server-Sent Events Source: https://docs.output.ai/api-reference/stream-pinned-run-workflow-history-events-via-server-sent-events /openapi.json get /workflow/{id}/runs/{rid}/history/stream Same as /workflow/{id}/history/stream but targets a specific run ID. # Stream workflow history events via Server-Sent Events Source: https://docs.output.ai/api-reference/stream-workflow-history-events-via-server-sent-events /openapi.json get /workflow/{id}/history/stream Opens a persistent SSE connection that delivers Temporal workflow history events in real time. Emits named events: `workflow` (metadata, once), `history` (event batches), `done` (terminal state), `server_error` (post-flush errors). The `done` event carries `{ reason, newRunId? }` where `reason` is the terminal Temporal event type (`WORKFLOW_EXECUTION_COMPLETED`, `WORKFLOW_EXECUTION_FAILED`, `WORKFLOW_EXECUTION_TIMED_OUT`, `WORKFLOW_EXECUTION_CANCELED`, `WORKFLOW_EXECUTION_TERMINATED`, `WORKFLOW_EXECUTION_CONTINUED_AS_NEW`) and `newRunId` is present only when the terminal event chains a follow-on run. `server_error` carries `{ error, message, workflowId, runId }`. Errors before the stream opens are returned as JSON HTTP responses (400/404); once open, failures arrive as a `server_error` event. Supports reconnect via `Last-Event-ID` header or `lastEventId` query param. # Terminate a specific workflow run (force stop) Source: https://docs.output.ai/api-reference/terminate-a-specific-workflow-run-force-stop /openapi.json post /workflow/{id}/runs/{rid}/terminate Force terminates a workflow run. Unlike stop/cancel, terminate immediately stops the run without allowing cleanup. # Authentication Source: https://docs.output.ai/api/authentication How authentication works for the Output API In development, all endpoints are open. In production (`NODE_ENV=production`), requests require Basic auth using the `OUTPUT_API_AUTH_TOKEN` environment variable: ```bash theme={null} curl -H "Authorization: Basic $OUTPUT_API_AUTH_TOKEN" \ https://api.example.com/workflow/run ``` The `/health` endpoint is always accessible without authentication. # Configuration Source: https://docs.output.ai/api/configuration Base URL and environment variables for the Output API server ## Base URL ``` http://localhost:3001 ``` In production, set the `OUTPUT_API_PORT` environment variable to change the port. ## Environment Variables The API server reads these environment variables: | Variable | Default | Description | | - | - | - | | `NODE_ENV` | `development` | Set to `production` to enable auth and production behavior | | `OUTPUT_API_PORT` | `3000` | HTTP port (e.g. `output dev` often uses 3001) | | `OUTPUT_API_SERVICE_NAME` | `output-api` | Service name for logging | | `OUTPUT_API_AUTH_TOKEN` | — | **Required in production.** Basic auth token for all endpoints except `/health` | | `OUTPUT_CATALOG_ID` | — | **Required.** Task queue and catalog workflow ID (must match worker) | | `TEMPORAL_ADDRESS` | `localhost:7233` | Temporal server address | | `TEMPORAL_NAMESPACE` | `default` | Temporal namespace | | `TEMPORAL_API_KEY` | — | Temporal Cloud API key (optional for local) | | `TEMPORAL_WORKFLOW_EXECUTION_TIMEOUT` | `24h` | Max workflow execution duration | | `TEMPORAL_WORKFLOW_EXECUTION_MAX_WAITING` | `300000` | Max wait for workflow result (ms, 5 min) | | `TEMPORAL_GRPC_MAX_MESSAGE_SIZE_BYTES` | `33554432` (32 MiB) | Max gRPC message size (send + receive) for the Temporal client. Raise if large workflow results hit `RESOURCE_EXHAUSTED`. | | `OUTPUT_TRACE_REMOTE_S3_BUCKET` | — | S3 bucket holding remote traces. Required for the API to serve traces from S3 | | `OUTPUT_AWS_REGION` | `us-west-1` | AWS region for the trace bucket | | `OUTPUT_AWS_ACCESS_KEY_ID` | — | AWS access key for reading remote traces | | `OUTPUT_AWS_SECRET_ACCESS_KEY` | — | AWS secret key for reading remote traces | ### AWS Credential Permissions The API only reads traces — the worker is what uploads them (see [Tracing](/operations/tracing#aws-credential-permissions) for the write-side policy). The credentials in `OUTPUT_AWS_ACCESS_KEY_ID` / `OUTPUT_AWS_SECRET_ACCESS_KEY` must allow **read** access to the trace bucket: | Action | Resource | Why | | - | - | - | | `s3:GetObject` | `arn:aws:s3:::/*` | Fetch individual trace objects | | `s3:ListBucket` | `arn:aws:s3:::` | List traces for a workflow | ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::my-traces", "arn:aws:s3:::my-traces/*" ] } ] } ``` > [!WARNING] > > If these read permissions are missing, trace fetches fail with a generic download error. A misconfigured bucket policy — granting the worker write access but not granting the API identity `s3:GetObject` / `s3:ListBucket` — is the most common cause of `output workflow debug` and `dataset generate --download` failing against production runs. # Error Responses Source: https://docs.output.ai/api/errors Error codes and response format for the Output API Error responses are JSON. The body includes: * **error** — Error type name (e.g. `WorkflowNotFoundError`). * **message** — Human-readable description. * **issues** — (400 only) Array of validation details from the schema. * **workflowId** — (when applicable) Workflow ID tied to the error. For `503`, the server may send a `Retry-After` header suggesting when to retry. Workflow execution failures are different from API request errors. `POST /workflow/run` and `GET /workflow/:id/result` return the standard workflow result payload with `status: "failed"`, `output: null`, and an `error` message. When available, that failed result also includes trace metadata. | Code | Error | Cause | | - | - | - | | 400 | ValidationError | Invalid request body or query. | | 404 | WorkflowNotFoundError | Workflow execution ID, workflow type, or catalog not found. | | 408 | WorkflowExecutionTimedOutError | Synchronous run timed out before the workflow completed. | | 424 | WorkflowNotCompletedError | Result or trace requested but the workflow is still running. | | 503 | CatalogNotAvailableError | Catalog workflow unavailable; retry after a short delay. | | 500 | (varies) | Server or Temporal connection error. | **400 ValidationError** — Request body or query parameters failed schema validation (e.g. missing required fields, wrong types). The `issues` array lists each validation failure. A 400 is also returned when Temporal rejects a request's `searchAttributes`: the attribute is not registered on the namespace, its value does not match the registered type, or the name is reserved. The `message` names the attribute and the reason, and never includes the submitted value. The workflow is not started. See [Search attributes](/operations/deployment#search-attributes). **404 WorkflowNotFoundError** — The given workflow execution ID does not exist, the workflow type is not in the catalog for the task queue, or the catalog workflow itself was not found. **408 WorkflowExecutionTimedOutError** — Returned only by `POST /workflow/run` when the workflow did not complete within the request timeout (or the configured max waiting time). **424 WorkflowNotCompletedError** — Returned by `GET /workflow/:id/result` and `GET /workflow/:id/trace-log` when the workflow is still running and has no final result or trace yet. **503 CatalogNotAvailableError** — The catalog workflow is not reachable (e.g. worker not running or still starting). Retry after a few seconds; the response may include a `Retry-After` header. **500** — Unexpected server or Temporal backend error (e.g. connection failure). Check logs for details. # Overview Source: https://docs.output.ai/api/index How your application communicates with Output workflows over HTTP Your application talks to Output through a REST API. When you deploy Output, the API server exposes HTTP endpoints for running workflows, checking their status, and retrieving results. Your backend sends a request, Output orchestrates the workflow, and you get structured results back. During development, the API server starts automatically on port 3001 when you run `output dev`. ## Two Ways to Run Workflows Choose based on how long your workflow takes and how your application handles responses. ### Run and Wait (Synchronous) `POST /workflow/run` blocks until the workflow completes and returns the result in the response body. Use this when workflows complete quickly (seconds) and your client can wait. ```bash theme={null} curl -X POST http://localhost:3001/workflow/run \ -H "Content-Type: application/json" \ -d '{"workflowName": "summarize_url", "input": {"url": "https://example.com/article"}}' ``` To attach Temporal search attributes to the run, add a `searchAttributes` map next to `input`. The same field works on `/workflow/start`. See [Search attributes](/operations/deployment#search-attributes) for registration and behavior. ```bash theme={null} curl -X POST http://localhost:3001/workflow/run \ -H "Content-Type: application/json" \ -d '{"workflowName": "summarize_url", "input": {"url": "https://example.com/article"}, "searchAttributes": {"ClientId": "acme"}}' ``` ### Start and Poll (Asynchronous) `POST /workflow/start` returns the workflow ID immediately. Poll for status and retrieve the result when ready. Use this for longer workflows — minutes or more — where blocking a request isn't practical. ```bash theme={null} # Start the workflow curl -X POST http://localhost:3001/workflow/start \ -H "Content-Type: application/json" \ -d '{"workflowName": "company_research", "input": {"domain": "example.com"}}' # Check status curl http://localhost:3001/workflow//status # Get result when completed curl http://localhost:3001/workflow//result ``` ## Workflow Result Payload `POST /workflow/run` and `GET /workflow/:id/result` return the same structured workflow result: ```json theme={null} { "v": "2", "workflowId": "lead_enrichment-a1b2c3d4-5678-90ab-cdef-1234567890ab", "runId": "b5c6d7e8-9012-3456-7890-abcdef123456", "status": "completed", "input": { "companyDomain": "acme.com" }, "output": { "company": "Acme Corp", "summary": "Enterprise software company focused on..." }, "trace": { "local": "/path/to/trace.json", "remote": "s3://trace-bucket/path/to/trace.json" }, "error": null } ``` | Field | Description | | - | - | | `v` | Workflow result payload version. Current responses use `"2"`. | | `workflowId` | Workflow execution ID. | | `runId` | Specific Temporal run ID. | | `status` | Current or final execution status. | | `input` | Original workflow input. | | `output` | Value returned by the workflow on success, or `null` on failure. | | `trace` | Trace metadata for the run, or `null` when unavailable. | | `error` | Serialized error object on failure, otherwise `null`. It includes `name` and `message` and may include `activityType`, `cause`, and additional diagnostic properties. | When a workflow fails, the result includes `status: "failed"`, `output: null`, and a structured `error`. Trace metadata may still be present when available. Results from workflows started by older workers retain the legacy unversioned response shape until those executions leave Temporal retention. ## Interacting with Running Workflows Output supports sending data to running workflows and reading their state via signals, queries, and updates. The workflow must define handlers for these — see [External Integration](/workflows/external-integration) for how to set them up. | Method | What it does | Use case | | - | - | - | | **Signal** `POST /workflow/:id/signal/:name` | Push data into a workflow | Human approval, external events | | **Query** `POST /workflow/:id/query/:name` | Read workflow state without changing it | Progress checks, status dashboards | | **Update** `POST /workflow/:id/update/:name` | Change state and get confirmation | Configuration changes, priority updates | ## Stopping Workflows * `PATCH /workflow/:id/stop` — Graceful stop. Allows cleanup handlers to run. * `POST /workflow/:id/terminate` — Force terminate. Immediate, no cleanup. ## Workflow Discovery `GET /workflow/catalog` returns all available workflows with their input and output schemas. Use this to build dynamic UIs or validate inputs before submitting. ## Streaming Workflow Progress `GET /workflow/:id/history/stream` opens a persistent [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) connection that delivers Temporal history events in real time as the workflow executes. Use this to build live progress UIs without polling. ```js theme={null} const es = new EventSource(`http://localhost:3001/workflow/${workflowId}/history/stream`); es.addEventListener('workflow', e => { const { status, historyLength, taskQueue } = JSON.parse(e.data); // initial metadata, emitted once on connect }); es.addEventListener('history', e => { const events = JSON.parse(e.data); // array of new Temporal history events (same shape as REST endpoint) }); es.addEventListener('done', e => { const { reason, newRunId } = JSON.parse(e.data); es.close(); }); es.addEventListener('server_error', e => { // server-side error after stream started }); ``` The stream emits four named events: | Event | When | Data | | - | - | - | | `workflow` | Once on connect | `{ workflowId, runId, status, startTime, closeTime, historyLength, taskQueue }` | | `history` | Each batch of new events | Array of serialized history events | | `done` | Workflow reaches terminal state | `{ reason, newRunId? }` | | `server_error` | Post-connect server error | `{ error, message, workflowId, runId }` | `reason` is the terminal Temporal event type, one of: `WORKFLOW_EXECUTION_COMPLETED`, `WORKFLOW_EXECUTION_FAILED`, `WORKFLOW_EXECUTION_TIMED_OUT`, `WORKFLOW_EXECUTION_CANCELED`, `WORKFLOW_EXECUTION_TERMINATED`, `WORKFLOW_EXECUTION_CONTINUED_AS_NEW`. `newRunId` is present only when the terminal event carries a follow-on run (continue-as-new, and the completed/failed/timed-out cases that chain a new run). Errors raised before the stream starts (invalid `lastEventId`, unknown workflow) are returned as normal JSON HTTP responses (`400`/`404`). Once the stream is open, failures arrive as a `server_error` event instead — the connection has already committed to `200 text/event-stream`. `EventSource` reconnects automatically after network drops. On reconnect it sends `Last-Event-ID` and the server replays only events the client hasn't seen. To target a specific run, use `GET /workflow/:id/runs/:rid/history/stream`. Pass `?includePayloads=true` to include decoded activity input/output in the events. ## Debugging `GET /workflow/:id/trace-log` returns the full execution trace for a completed workflow. See [Tracing](/operations/tracing) for the trace format. > [!NOTE] > > For remote traces, the API server needs AWS credentials (`OUTPUT_AWS_ACCESS_KEY_ID`, `OUTPUT_AWS_SECRET_ACCESS_KEY`, `OUTPUT_AWS_REGION`). ## What's Next > [card] [Configuration](/api/configuration) > > **Configuration.** Base URL, ports, and environment variables for the API server. > [card] [Authentication](/api/authentication) > > **Authentication.** How auth works in development vs production. > [card] [Error Responses](/api/errors) > > **Error Responses.** Error codes, response format, and how to handle failures. # Changelog Source: https://docs.output.ai/changelog/index Release notes for the Output framework. Every change to @outputai/* packages and output-api shows up here. The Output framework uses a fixed version group: `@outputai/core`, `@outputai/cli`, and `output-api` all share one version number and release together. Releases with breaking changes link to a matching section on the [Migrations](/migrations) page. If you're upgrading across several versions, apply each section in order. **v0.16.0** 2026-11-02 - minor release See the [v0.15.0 - v0.16.0 migration guide](/migrations/v0.15.0-to-v0.16.0). ### `@outputai/cli`, `@outputai/core` Folded `@outputai/llm` as a feature of `@outputai/core`, under the `@outputai/core/llm` entry point. Usage is the same: replace `@outputai/llm` imports with `@outputai/core/llm`. The `@outputai/llm` package is no longer published. Other changes are: * Added `ai` as a peer dependency of `@outputai/core`, and the built-in AI SDK providers (`@ai-sdk/amazon-bedrock`, `@ai-sdk/anthropic`, `@ai-sdk/azure`, `@ai-sdk/google-vertex`, `@ai-sdk/openai` and `@ai-sdk/perplexity`) as optional peer dependencies. Install the providers your prompts use; using a provider whose package is not installed throws a `FatalError` naming the package to install. * Changed `getProviderNames()` to list only the built-in providers whose package is installed, plus registered ones. * Updated the CLI project templates and agent instructions to use `@outputai/core/llm`, and added `@ai-sdk/anthropic` and `@ai-sdk/openai` to the project template. The `llm:generation:metering` and `cost:llm:request` events and the LLM trace attributes are unchanged. Stopped publishing the `@outputai/output` umbrella package. Projects depend on `@outputai/core` and, as a dev dependency, `@outputai/cli` instead. Other changes are: * Changed the project template to depend on `@outputai/core` and `@outputai/cli` instead of `@outputai/output`. * Changed `output fix` to replace an `@outputai/output` dependency with `@outputai/core` in `dependencies` and `@outputai/cli` in `devDependencies`, at the same version. * Changed the `output update` warning about a version range that holds back the CLI so it no longer refers to `@outputai/output`. * Removed the internal `@outputai/core/sdk/helpers` and `@outputai/core/sdk/runtime` entry points. * Removed support for the `output-workflow-bundle` package export condition when bundling workflows. Folded `@outputai/http` as a feature of `@outputai/core`, under the `@outputai/core/http` entry point. Usage is the same: replace `@outputai/http` imports with `@outputai/core/http`. The `@outputai/http` package is no longer published. Other changes are: * Added `ky` and `undici` as peer dependencies of `@outputai/core`, and removed `undici` from its regular dependencies. * Added `HTTPRequestCount` and `HTTPRequestCost` to `@outputai/core/http`. * Updated the CLI project templates and agent instructions to use `@outputai/core/http`. * Changed verbose HTTP tracing (`OUTPUT_TRACE_HTTP_VERBOSE`) to record request and response bodies with the same parsing as `sendHttpRequest()`, so multipart bodies are now stored as base64. Changed `sendHttpRequest()` response body parsing when `responseOptions.includeBody` is `true`: * Changed XML, form-urlencoded and JavaScript content types to be returned as text instead of base64. * Changed empty or invalid JSON bodies to be returned as raw text instead of throwing. Folded `@outputai/evals` as a feature of `@outputai/core`, under the `@outputai/core/evals` entry point. Replace `@outputai/evals` imports with `@outputai/core/evals`, except for the LLM judges, which moved to `@outputai/core/llm`. The `@outputai/evals` package is no longer published. Other changes are: * Moved `judgeVerdict`, `judgeScore`, `judgeBoolean`, `judgeLabel` and the `JudgeArgs` type to `@outputai/core/llm`. Their arguments and results are unchanged. * Removed `interpretResult`, `aggregateCaseVerdict`, `renderEvalOutput`, `computeExitCode`, `getEvalWorkflowName`, `isEvalWorkflow` and `getParentWorkflowName` from the public API. They were used internally by the eval workflow and the CLI. * Removed the internal Zod schemas from the public API. `DatasetSchema` and `EvalOutputSchema` are still exported, along with the `VERDICT` and `CRITICALITY` values and the eval types. * Changed the workflow bundler to replace steps and evaluators that are referenced as values in workflow files, rather than called, with their activity names, and to strip their imports. Previously their modules were bundled into the workflow sandbox when the file had no activity calls. * Removed `@outputai/evals` from `@outputai/cli`. ### `@outputai/core`, `output-api` Removed the duplicated cause from step and workflow failures. The `ApplicationFailure` cause is now the error's own `.cause` instead of the error itself, so its message and stack are no longer encoded twice. As a result, wherever a failure's cause chain is exposed, such as API error responses, traces and logs, it is now one redundant level shorter. ### `@outputai/core` Added public type exports for HTTP fetch, workflow definitions, credential provider contexts, LLM calls and eval verification. Added per-request context-tier pricing for LLM models, including tier-specific input, output, cache-read and cache-write rates. Applied tiers are exposed on normalized cost items, and multi-step calls are priced separately per provider request. Added usage and cost tracking for Anthropic and OpenAI provider-native web search, plus Google Search grounding pricing for Gemini 4. Each billed search is recorded as a `tools` item, priced separately from tokens, and included in the normalized generation cost total. Reduce worker memory usage by loading only the invoked workflow module into each cached Temporal workflow execution. Added worker memory sizing diagnostics and deferred the workflow concurrency defaults to `@temporalio/worker`. **Worker sizing startup log** Added a `Worker sizing` record, logged once at startup with the thread pool size, `reuseV8Context`, the isolate count, the per-isolate heap limit, the heap all isolates could commit together, the host's memory limit, the resolved cache size, and the workflow task slot count. Warns when the projected heap exceeds the host's memory limit, and when there are more workflow task slots than cache entries, which causes tasks to evict each other's workflows and forces history replays. Accounts for `NODE_OPTIONS` heap caps applying per isolate rather than per process: a worker runs one V8 isolate on its main thread plus one per workflow thread, so the heap it can commit is a multiple of the cap. **Periodic telemetry** * Added `memory.nonMainHeap` (`rss - heapUsed`): resident memory outside the main isolate's live objects, including workflow thread heaps, Rust core allocations, and heap pages V8 has committed but not filled. Cached workflow memory is counted here. * Added `memory.heapSizeLimit`, the per-isolate heap ceiling, to each sample. * Renamed `memory.constrainedMemory` to `memory.memoryLimit` and changed what it reports. `process.constrainedMemory()` returns a sentinel near 2^64 rather than `0` when the process is unconstrained, so the old field was not usable outside a memory-capped container. `memoryLimit` falls back to the machine's total memory. Anything parsing the old field needs updating. **Environment variables** * Added `TEMPORAL_WORKFLOW_THREAD_POOL_SIZE`, the number of threads running workflow sandboxes, which sets the number of isolates. Unset by default. * Removed the `TEMPORAL_MAX_CACHED_WORKFLOWS` default of `1000`. When unset, the cache is sized from the isolate's heap limit instead of a fixed value. That formula assumes roughly 600 cached workflows per GB, so deployments with heavier payloads should set it explicitly. * Removed the `TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS` default of `200`. When unset, it falls back to the upstream default of `40`. ### `@outputai/cli`, `@outputai/core`, `output-api` Dependency updates: * `@hono/node-server`: `2.0.10` -> `2.1.3`, reached through `@modelcontextprotocol/sdk` * `@modelcontextprotocol/sdk`: `1.31.0` -> `1.32.0`, reached through `@anthropic-ai/claude-agent-sdk` * `body-parser`: `2.3.0` -> `2.4.0`, reached through `express` * `fast-uri`: `3.1.8` -> `3.1.9`, reached through `ajv` * `hono`: `4.13.10` -> `4.13.11`, reached through `@modelcontextprotocol/sdk` * `ip-address`: `10.7.2` -> `10.7.4`, reached through `@modelcontextprotocol/sdk` * `qs`: `6.16.0` -> `6.16.1`, reached through `express` and `body-parser` * `undici`: `7.29.1` -> `7.30.1`, reached through `@ai-sdk/provider-utils` * `undici`: `8.11.0` -> `8.12.3`, fixing Node's built-in `fetch` returning gzip response bodies undecoded after Undici is imported * `zod`: `4.6.5` -> `4.6.6` Peer dependency ranges: * `undici` min supported peer dependency version for `@outputai/core` is now `8.12.2`. * `zod` min supported peer dependency version for `@outputai/core` is now `4.6.6`. ### `@outputai/cli` Patching handlebars version from 4.7.9 to 4.7.10 to fix vulnerabilities. **v0.15.0** 2026-10-08 - minor release See the [v0.14.0 - v0.15.0 migration guide](/migrations/v0.14.0-to-v0.15.0). ### `output-api` **Dependencies updates** **API runtime** * @grpc/grpc-js: `1.14.4` -> `1.14.5`, reached through `@temporalio/client` * proxy-addr: `2.0.7` -> `2.0.8`, reached through `express` ### `@outputai/cli` * Updated the CLI to use `@outputai/core` for credentials features. * Updated `output fix` to remove the now-unused `outputai.hookFiles` entry pointing to `@outputai/credentials`. * Updated the scaffolding of new projects to no longer include the credentials entry in `outputai.hookFiles`. ### `@outputai/core` Folded `@outputai/credentials` as a feature of `@outputai/core`, under the `@outputai/core/credentials` entry point. Usage is the same, and credentials are still loaded during worker startup (after workflows are loaded). The `outputai.hookFiles` config is no longer necessary. Other changes are: * Updated the worker to fail startup when there are errors loading credentials. * Removed the `onBeforeWorkerStart` hook. The original `/credentials` behavior and interface were kept, with the exception of these changes: * Updated to use the encrypted YAML provider as the default. * Removed unused exports: * `getProvider` * `encryptedYamlProvider` * `GlobalContext` * `WorkflowContext` * Updated all typed errors to inherit from `FatalError`, so when thrown, they fail the workflow execution. This includes: * `MissingKeyError` * `MissingCredentialError` * `InvalidCredentialsKeyError` * `MalformedCredentialsKeyError` ### `@outputai/cli`, `@outputai/core`, `output-api` Added support for Temporal search attributes on workflow runs: * Added an optional `searchAttributes` map to `/workflow/run` and `/workflow/start`. Unregistered attributes or mistyped values return 400 and the workflow is not started. * Added a `--search-attributes` flag to `output workflow run` and `output workflow start`. * Added `workflowDetails.searchAttributes` to hook payloads, with `Datetime` values as ISO strings. * Updated child workflows to inherit their parent's search attributes, excluding Temporal system attributes. **v0.14.0** 2026-09-22 - minor release See the [v0.13.0 - v0.14.0 migration guide](/migrations/v0.13.0-to-v0.14.0). ### `@outputai/llm` Added usage and cost reporting for generations that fail after the model ran. Usage is now collected from the AI SDK lifecycle events as the call progresses, so billing no longer depends on the call returning a response. Attribute and event shapes are unchanged - failed calls simply stop being free, which raises reported cost for unchanged traffic. Failures before the first completed step still report nothing, because nothing was spent or reported: authentication, rejected requests, unknown models, connection errors, aborts before the first step, and every `generateImage` error. * Added billing for `generateText` and `Agent.generate` failures that follow a completed step: output or schema validation (`NoObjectGeneratedError`, `NoOutputGeneratedError`), a tool loop that breaks mid-run, an abort, and post-response code such as an `Agent.generate` message store failure. * Added billing for `generateTextWithStreaming` and `Agent.generateWithStreaming` failures: a provider error part mid stream, an abort after a completed step, a structured output that never validates, and a message store failure after the stream finished. * Added billing for `streamText` and `Agent.stream` runs that end on an error part or on an abort with steps already collected. * Added the abort reason and the structured output rejection to the LLM trace event, so a cancelled stream and an output that never validated are no longer traced as clean calls. * Updated streamed generations to consume the whole stream after a failure before rethrowing, since step usage is only reported while something keeps reading. A stream that goes quiet for 250 ms after failing is abandoned, and the original error is thrown anyway. * Updated billing to run once per call, so a generation reporting several lifecycle events is metered a single time. Activity retries continue to bill per attempt, because each attempt calls the provider. * Updated response sources to be filtered before they are returned: entries carrying neither a url nor an id are dropped, and a malformed `sources` payload is logged and yields no sources instead of failing the call. Every source that survives is returned exactly as the AI SDK produced it. * Updated a failure in the SDK's own response handling to throw a non-retryable `FatalError` wrapping the original error, since such a failure is deterministic and a retry pays for the model call again. Generic streaming error messages were normalized to `Streaming aborted.`, `Streaming failed.` and `Streaming completed without a response.`. ### `@outputai/core` Changed the worker to exit `1` on any shutdown failure, including in-flight work that did not finish before `TEMPORAL_SHUTDOWN_FORCE_TIME`. v0.13.0 exempted an abandoned drain from the failure exit code, which never took effect in practice. Updated error serialization to keep only `name`, `message`, `code` and `stack` for `DOMException` values, instead of also projecting the 25 legacy numeric constants their prototype carries. Aborted operations, whose reason is usually a `DOMException`, now read like any other error in traces and logs. Fixed two defects that made trace trees merge or drop nodes. * Fixed activity trace event ids colliding across attempts and across workflows. Temporal numbers activity ids per workflow run and reuses them on retry, so every attempt of an activity shared one id, and a parent and its child workflow both produced an `act-1`. The tree builder merged the colliding entries: only the last attempt's input, error and timing survived, the LLM and HTTP calls of every attempt were listed as children of that one node, and a nested workflow's step surfaced a second time as a phantom node directly under the root. Activities are now traced as `::`, so each attempt in each run is its own node with its own input, output or error, timing and children. * Fixed webhook trace events being parented on the parent workflow's run id. In a root workflow the event had no parent and was dropped from the trace file; in a child workflow it landed beside the child instead of inside it. These events now parent on the running workflow. A wait whose `resume` signal never arrives is traced as a `webhook` node with a null `endedAt`. ### `@outputai/cli` Updated the scaffolded `CLAUDE.md`'s HTTP client convention to point agents at `addRequestCost` from an `afterResponse` hook for paid APIs, and at forwarding cost events via `output-dev-cost-hooks`. **v0.13.0** 2026-09-14 - minor release See the [v0.12.0 - v0.13.0 migration guide](/migrations/v0.12.0-to-v0.13.0). ### `@outputai/core` Hardened worker startup and shutdown around the catalog workflow. * Changed catalog reconciliation to terminate a stale catalog instead of asking it to complete, so a catalog that stopped processing workflow tasks no longer fails every deploy that follows it. * Increased the catalog workflow task timeout to 30s, enough for a cold worker bundle to activate. * Added two retries when publishing the catalog before failing the worker. * Added a startup gate so a worker never starts unless its catalog matches its own source code. * Changed the worker to always exit explicitly: `0` for a signal shutdown, `1` for a startup failure, a lost connection, an uncaught error, or a worker that failed to stop. A drain the worker had to abandon is not a failure - it is the bound working as intended - so it exits `0` and records a `Stopping Worker error` warning carrying the `GracefulShutdownPeriodExpiredError`. * Added graceful draining for uncaught exceptions and unhandled rejections, with a force quit if the drain stalls. * Fixed kill signals during startup killing the process abruptly, since the handler was only installed once the worker was built. * Added defaults for `TEMPORAL_SHUTDOWN_GRACE_TIME` (`15s`) and `TEMPORAL_SHUTDOWN_FORCE_TIME` (`20s`), so a wedged drain now ends under the worker's own control instead of waiting for the platform to `SIGKILL` it. Both were previously unset, which left the drain unbounded and meant the hook flush was never reached on a deploy that caught in-flight work. Raise them together with your platform's shutdown delay if your activities need longer. * Added `OUTPUT_HOOK_FLUSH_TIMEOUT_MS` (`5000`) for the hook flush allowance, previously hardcoded at `30000`. The flush runs after the drain, so force time plus flush timeout is the worst-case shutdown and has to fit your platform's window: the defaults total 25s against the 30s most platforms allow. At the old 30s the flush could not complete on a default window. ### `@outputai/llm` Added a static subset of the models pricing table, so costs for the six shipped providers can be calculated even when the live models pricing provider is down. * Added `pricingFreshness` to `LLMGenerationCost`, reporting whether the rates were fetched during the call (`live`), served from the 24 hour cache (`cached`), kept past that cache's expiry because a refresh failed (`stale`), or read from the bundled snapshot (`snapshot`). * Changed `LLMGenerationCost.status` to `imprecise` when rates come from the bundled snapshot, since it is a point-in-time copy that can lag the live catalog by an unbounded amount. A stale cache does not downgrade the status, because those rates were accurate when they were fetched. * Changed pricing lookups to pause live requests for 10 minutes after a failure, instead of retrying the unreachable catalog on every call. * Changed `cost` to stay non-null while the pricing catalog is unreachable, since the snapshot always provides rates. Code that read `cost === null` as an outage signal should read `pricingFreshness` or `status` instead. `cost` is still `null` when usage cannot be normalized. * Added a periodic refresh of the bundled snapshot, so upgrading to a newer release picks up a more recent table. Added `GCP_CREDENTIALS_JSON` support to the built-in `google-vertex` provider. Set it to the contents of a service account key file, either raw JSON or base64 encoded, to authenticate Vertex AI without deploying a credentials file. When the variable is unset the provider keeps using Application Default Credentials, so existing `GOOGLE_APPLICATION_CREDENTIALS`, `gcloud` and metadata server setups are unchanged. ### `@outputai/cli`, `@outputai/llm` Added support for pricing Gemini grounded search, which providers bill per request rather than per token. `LLMGenerationUsage` and `LLMGenerationCost` items gain a `tools` group alongside `input` and `output`, and `LLMGenerationCost` gains a matching `tools` aggregate that is included in `total`. The legacy `cost:llm:request` payload is unchanged and does not carry grounding charges - its shape is frozen, so grounding costs are only visible on the new normalized attribute. `output workflow cost` prices these tool charges and marks any call with an unpriced charge (grounding or otherwise) with a `*` and a "cost incomplete" footnote, since the reported total understates the actual bill. ### `@outputai/cli`, `@outputai/credentials`, `output-api` **Dependencies updates** **Published dependency ranges** * js-yaml: `4.3.1` -> `4.3.2` (catalog), shipped by `@outputai/cli` and `@outputai/credentials` **API runtime** * qs: `6.15.2` -> `6.16.0`, reached through `express`, which also moves `side-channel` from `1.1.0` to `1.1.1` **v0.12.0** 2026-09-02 - minor release See the [v0.11.0 - v0.12.0 migration guide](/migrations/v0.11.0-to-v0.12.0). ### `@outputai/llm` * Updated `@outputai/llm` to AI SDK 7 and its compatible provider majors: `ai` 7.x; OpenAI, Anthropic, Azure, and Perplexity 4.x; and Amazon Bedrock and Google Vertex 5.x. * Renamed stream completion callbacks and their exported wrapped types from `onFinish` to `onEnd` in `streamText()` and `Agent.stream()`. * Updated the `aiSdk` namespace to expose the AI SDK 7 API, including `isStepCount()` instead of `stepCountIs()`. * Updated `onChunk` to receive every AI SDK 7 stream part, including start, finish, error, step-boundary, text-boundary, and reasoning-boundary parts. Handlers should ignore part types they do not use. * Updated `Agent` so it no longer inherits from the AI SDK `ToolLoopAgent`. Its public methods remain `generate()`, `generateWithStreaming()`, and `stream()`. * Updated cache-read, cache-write, text-output, and reasoning token cost calculation to use AI SDK 7 usage breakdowns, with aggregate input or output usage as the fallback for incomplete breakdowns. * Added normalized usage and cost items with `group` (`input` or `output`) and optional labels (`no_cache`, `cache_read`, `cache_write`, `text`, or `reasoning`). The existing `llm:usage` trace attribute and `cost:llm:request` event remain available with their legacy payload for compatibility. * Fixed legacy `llm:usage` output accounting: when reasoning tokens are provided as a discrete item, they are no longer included in the item for output tokens, removing the double counting problem. * Added normalized `LLMGenerationUsage` and `LLMGenerationCost` trace attributes with provider/model identity, aggregate totals, detailed items, and completeness/pricing statuses. * Added the `llm:generation:metering` event. It is emitted with normalized usage even when cost is unavailable: ```json theme={null} { "usage": { "type": "llm:generation:usage", "providerId": "openai", "modelId": "gpt-4o", "status": "complete", "input": 217, "output": 9, "total": 226, "items": [ { "group": "input", "label": "no_cache", "amount": 217 }, { "group": "output", "label": "text", "amount": 9 } ] }, "cost": { "type": "llm:generation:cost", "providerId": "openai", "modelId": "gpt-4o", "status": "precise", "input": 0.001085, "output": 0.000135, "total": 0.00122, "items": [ { "group": "input", "label": "no_cache", "amount": 217, "ppm": 5, "total": 0.001085, "status": "ok" }, { "group": "output", "label": "text", "amount": 9, "ppm": 15, "total": 0.000135, "status": "ok" } ] } } ``` Added support for passing a loaded or custom `Prompt` object directly to `generateText()`, `generateTextWithStreaming()`, `streamText()`, `generateImage()`, and the `Agent` constructor. Prompt filename strings remain supported; `variables` and `promptDir` apply only when loading a prompt by filename. **Skills** * Fixed implicit and inconsistent skill loading by making prompt frontmatter the only skills definition: * Removed the `skills` argument from `generateText()`, `streamText()`, `generateTextWithStreaming()`, and `Agent`. * Removed the `skills/` auto-discovery. * Removed the `skill()` helper and the `Skill` and `SkillsArg` types. * Fixed configured skill directories silently omitting Markdown files in nested folders. Directory loading is recursive and sorted. * Fixed skill discovery following symbolic links. Symbolic links are ignored. **Call signatures and validation** * Fixed unrestricted native AI SDK call arguments bypassing validation and overriding prompt-owned model/configuration. Generation and Agent APIs now reject unsupported or misplaced arguments before provider I/O. Removed native AI SDK call arguments from `generateText()`, `generateTextWithStreaming()`, `streamText()`, `generateImage()`, and `Agent`, as well as `skills` and `maxSteps`. These are the supported arguments: | Argument | `generateText` | `generateTextWithStreaming` | `streamText` | `generateImage` | | - | - | - | - | - | | `prompt` | required | required | required | required | | `promptDir` | optional | optional | optional | optional | | `variables` | optional | optional | optional | optional | | `tools` | optional | optional | optional | - | | `output` | optional | optional | optional | - | | `toolChoice` | optional | optional | optional | - | | `stopWhen` | optional | optional | optional | - | | `abortSignal` | optional | optional | optional | optional | | `onChunk` | - | optional | optional | - | | `onEnd` | - | - | optional | - | | `onError` | - | - | optional | - | | `images` | - | - | - | optional | | `mask` | - | - | - | optional | | Argument | `new Agent` | `.generate` | `.generateWithStreaming` | `.stream` | | - | - | - | - | - | | `prompt` | required | - | - | - | | `promptDir` | optional | - | - | - | | `variables` | optional | - | - | - | | `tools` | optional | - | - | - | | `output` | optional | - | - | - | | `stopWhen` | optional | - | - | - | | `messageStore` | optional | - | - | - | | `messages` | - | optional | optional | optional | | `abortSignal` | - | optional | optional | optional | | `toolChoice` | - | optional | optional | optional | | `onChunk` | - | - | optional | optional | | `onEnd` | - | - | - | optional | | `onError` | - | - | - | optional | * Fixed callers being able to replace the prompt model while traces and cost used the prompt provider/model. * Fixed unsupported callbacks on completion APIs being silently overwritten by internal callbacks. * Fixed Agent using AI SDK's two automatic retries while other Output generation APIs disabled them. Agent now uses `maxRetries: 0`. * Added the public `GenerateImageInput` type for `generateImage()` `images` and `mask` values. * Fixed `GenerateImageParameters` allowing `mask` without `images`; the public type now matches runtime validation. * Fixed invalid Agent constructor and method arguments being forwarded for late failure by validating messages, callbacks, tool choices, and `MessageStore` implementations at the public boundary. **Tools and tool loops** * Fixed tool handling: * Fixed call-argument tools overriding prompt tools. They now merge (caller wins on the same key; `load_skill` is last). * Fixed prompt-only native tools missing the tool-loop limit. They now use `stopWhen: isStepCount(maxSteps)` from the prompt (default 10). * Fixed non-callable provider tool entries failing later with an opaque `TypeError`. They now fail provider-tool validation. **Prompt files** * Fixed loaded prompt shape inconsistencies: * Renamed `Prompt.promptFileDir` to `Prompt.fileDir`. * Added `PromptVariables` (`Record`, including nested objects and arrays) and `Prompt.variables` (default `{}`). LLM API `variables` arguments use the same type. * Fixed `Prompt.config.skills` varying between missing, a string, and a string array. It is always a `string[]` after load. * Added `Prompt.config.maxSteps` (positive integer, default 10). It replaces the old argument and is required on the public type. * Fixed `Prompt.instructions` allowing `undefined` in its public contract. It is always `string | null` after load (chat prompts are `null`). * Narrowed `PromptMessage.role` from `string` to `'system' | 'user' | 'assistant'`, matching authored prompt blocks. * Fixed per-message options remaining unresolved until generation. `options=""` is resolved during `loadPrompt` against `config.messageOptions` into optional `PromptMessage.providerOptions`; `PromptMessage.attributes` is removed. * Fixed prompt body scanning silently dropping text, accepting malformed structure, or truncating messages by replacing it with explicit instruction and message modes: * Fixed mode detection so plain text as the first meaningful body token selects instruction mode and preserves the complete body, while a tag selects message mode. * Clarified that text generation APIs require message mode, while `generateImage()` requires instruction mode. * Restricted message mode to top-level `system`, `user`, and `assistant` blocks, with no root text between blocks. * Fixed prompt files accepting authored `` blocks as string messages even though AI SDK requires structured tool-result parts. They now fail at load; structured tool messages remain supported through Agent `messages` and `messageStore`. * Added explicit errors for invalid roles, root self-closing or unmatched closing tags, unclosed blocks, and malformed attributes. * Fixed nested non-self-closing tags with the same name closing the outer block early. They now throw with an `<tag>` escape hint; different-name tags remain message content. * Fixed closing tags inside HTML comments prematurely terminating and truncating messages. * Fixed role-tag casing and closing-tag whitespace being misclassified as instructions. Role tags are case-insensitive and allow whitespace inside closing tags. * Added support for spaces around attribute `=` and `>` inside quoted values. Bare `options`, unknown option names, and invalid quote pairs throw at load. * Fixed empty or whitespace-only `options` values invalidating templated prompts. They now behave as no per-message options. * Fixed prompt file `config` accepting ignored or invalid values: * Unknown top-level keys throw. * `model` must be a non-empty string. * Added support for the native AI SDK generation properties `maxOutputTokens`, `topP`, `topK`, `presencePenalty`, `frequencyPenalty`, `stopSequences`, and text-generation `seed`. * Deprecated `maxTokens` in favor of `maxOutputTokens`. Existing prompts remain compatible: `loadPrompt` retains `maxTokens` and copies its value to `maxOutputTokens` when the canonical key is absent. When both keys are set, `maxOutputTokens` takes precedence. Each key must be a positive integer when provided. **Streaming and Agent message store** * Fixed stream observer failures escaping or disappearing silently. `streamText()` and `Agent.stream()` `onError` and `onEnd` callbacks are fire-and-forget observers. Output maps and forwards provider errors, and logs and ignores observer exceptions and rejected promises. * Added logging for internal stream finalization failures before AI SDK suppresses the callback rejection. * Updated Agent message store: * Renamed `conversationStore` to `messageStore` and `ConversationStore` to `MessageStore`. * Removed `createMemoryConversationStore()`. The caller supplies a `MessageStore` (`getMessages` / `addMessages`). * Fixed `Agent.generate()`, `Agent.generateWithStreaming()`, and `Agent.stream()` to persist to `messageStore` only when `finishReason` is not `'error'`. * Fixed stream message-store failures suppressing the user `onEnd`. Failures are logged and stream finalization continues. * Fixed Agent store failures producing success-then-error trace sequences. Store persistence completes before a successful trace end. **Tracing, sources, and response types** * Fixed inconsistent and incomplete LLM trace payloads across `generateText()`, `streamText()`, `generateTextWithStreaming()`, `generateImage()`, and `Agent`: * Updated start `input` to `{ prompt }` (the loaded object). Removed the v0.11 filename `prompt`, sibling `variables`, and `loadedPrompt`. * Renamed `sourcesFromTools` to `sources` (merged tool + provider sources). * Fixed source merge dropping provider document sources that have `id` but no `url`. * Fixed blank or untrimmed search URLs producing invalid citations or unstable source IDs. URLs are trimmed and blank values are dropped. * Fixed wrapped text responses not consistently exposing `sources` as an array. * Updated `ExtractedSource` to the AI SDK `generateText` sources item type (url and document). * Fixed concurrent same-name LLM calls started in the same millisecond sharing trace IDs. * Fixed aborted `streamText()` and `Agent.stream()` calls leaving their LLM trace open. Aborts now conclude the trace with an error. * Fixed public cost, source, and stream callback types to match wrapped runtime values. `response.cost` and stream `onEnd` `cost` use `LLMGenerationCost`, or `null` when pricing data is unavailable. Stream `onEnd` types also include wrapped `result` and merged `sources`. **AI SDK exports and public parameter types** * Renamed the AI SDK namespace re-export from `ai` to `aiSdk` (both code and types). * Removed named AI SDK re-exports (`tool`, `Output`, `smoothStream`, `stepCountIs`, `hasToolCall`, `jsonSchema`) and AI SDK type re-exports (`ToolSet`, `FinishReason`, `ModelMessage`, and others). Use the `aiSdk` namespace (or import from `ai`) for those. * Removed the Output-owned `GenerateTextAiSdkOptions`, `StreamTextAiSdkOptions`, and `GenerateImageAiSdkOptions` aliases. Use `GenerateTextParameters`, `StreamTextParameters`, and `GenerateImageParameters`. * Updated `OutputAgentGenerateWithStreamingParameters` to no longer accept an output type argument. * Removed test specs and fixtures from the published package tarball. Fixed `Agent.stream()` and `Agent.generate()` to map AI SDK failures to framework errors consistently with `generateText()`. Non-retryable AI SDK failures now become `TransparentFatalError`, so affected activities fail without retrying. `Agent.stream()` now also awaits asynchronous stream setup failures. Added `generateTextWithStreaming()` and `Agent.generateWithStreaming()`, which return complete results like `generateText()` and `Agent.generate()` while using streaming internally. Callers can observe progress through `onChunk`. Failures reject the returned promise. ### `@outputai/evals` Judge evaluators now accept nested objects and arrays as prompt variables. ### `@outputai/core` Moved LLM-specific trace attributes out of `@outputai/core`. Removed `Attribute.LLMUsage` and `Attribute.Usage`, and exposed the generic `Attribute.BaseAttribute` used by package-owned attributes. Import `LLMGenerationUsage`, `LLMGenerationCost`, and the deprecated legacy `LLMUsageEvent` from `@outputai/llm`. ### `@outputai/cli` Updated `output workflow cost` to read the normalized `llm:generation:cost` and `llm:generation:usage` trace attributes while retaining support for legacy `llm:usage` traces. Cost overrides now reprice cache-read, cache-write, text, and reasoning usage, and model prefix matching selects the most specific configured price. **v0.11.0** 2026-08-12 - minor release See the [v0.10.0 - v0.11.0 migration guide](/migrations/v0.10.0-to-v0.11.0). ### `@outputai/cli` CLI env loading now uses Node's `process.loadEnvFile` instead of the `dotenv` package. * Added support for legacy and V2 workflow results from the API, including structured errors; Restore the terminal on abnormal `output dev` exit. Uncaught exceptions and unhandled rejections now leave the alternate-screen buffer and unmount the TUI before exiting, so scrollback and the error stack stay readable. **`workflow start --monitor`** Added a `--monitor` (`-m`) flag to `output workflow start` that attaches and streams step updates as soon as the workflow is started, so you no longer have to copy the workflow ID into a separate `workflow monitor` call. ```bash theme={null} output workflow start lead_enrichment --input ./test_input.json --monitor ``` * Monitoring is pinned to the run id returned by `start`, so a rapid re-start can't leave you watching a different execution. * Behavior matches `workflow monitor`: Ctrl+C detaches without stopping the workflow (exit `130`), and a failed workflow exits `1`. * If the stream itself drops after the workflow was started, the command reports that the workflow is still running and exits `3` — distinct from `1`, so retry logic keyed on a failed workflow can't re-submit one that is already in flight. * `--interval`, `--include-payloads`, and `--color` tune the stream and require `--monitor`. * `--monitor` cannot be combined with `--json`, which suppresses progress output and prints a single object at the end — that would swallow the whole stream. Use `workflow run --json` to wait for a result, or `workflow monitor --format json` for streaming NDJSON. The polling loop moved to a shared module so `workflow monitor` and `workflow start --monitor` run the same code path. Two fixes fall out of that for `workflow monitor` as well: a transient failure on the *first* poll is now retried like any other (it used to abort immediately), and Ctrl+C waits for output to flush before exiting, so a piped session can't lose its last lines. Detaching now also names `workflow status`/`workflow result` for the run you left behind. Fix `--json` output on the `workflow start` and `workflow run` commands. `workflow start` did not support `--json` at all and errored on the flag; it now emits the workflow result as JSON. `workflow run --json` corrupted its JSON output when given a scenario argument, because the "Using scenario:" notice was written to stdout. That notice now goes to stderr, and is suppressed entirely under `--json` so that on success both commands write exactly one JSON object to stdout and nothing else. Renamed the workflow eval CLI command to `output workflow test` (was `output workflow test_eval`). The short `test` name is now the only command id; the `test_eval` name is removed. * Removed install from hot-reload when developing workflows (`output dev`): nodemon no longer runs `npm install` on every reload, and `package.json` is no longer watched. After dependency changes, run `npm install`, bring the stack down (`output dev down` if it is still running), and start `output dev` again. * `npm run output:worker` also no longer installs first — run `npm run output:worker:install` (or rely on `output dev`, which still installs on worker start) before build/start. `npx output fix` rewrites `output:worker` in existing projects when you apply it. fix `output dev` memory leak in TUI where workflow run details grew unbounded Add TUI attaching and re-attaching and `dev down` teardown command `output dev` now detects an existing stack with `docker compose ps` instead of an unconditional host-port probe, so a re-run attaches to a running project stack rather than aborting on a collision with its own containers. Attached sessions leave the stack up on quit; `output dev down` stops it. A stack whose containers are all stopped counts as a fresh start, not an attach — `output dev` restarts it in the foreground and still tears it down on quit. `output dev -d` gained the pre-flight port probe the foreground path has. This matters on Docker Desktop, where a non-container process holding a published port does not fail `compose up -d`: the container starts and the port keeps answering the other process, with no error from Docker. Note: `-d` now pipes Docker's output rather than inheriting the terminal, so Docker drops its redrawing progress bars for plain scrolling lines. ### `output-api` * Added support for new workflow results without wrappers and with trace information in `memo`; * Added support for the new structured error format, including error details; * Added the new workflow result format V2 while preserving support for legacy results: ```json theme={null} { "v": "2", "workflowId": "xxx", "runId": "xxx", "status": "failed", "input": null, "output": null, "trace": { "local": "...", "remote": "..." }, "error": { "name": "TypeError", "message": "fetch failed", "cause": { "name": "Error", "message": "getaddrinfo ENOTFOUND coolbeans.sofax", "errno": -3008, "code": "ENOTFOUND", "syscall": "getaddrinfo", "hostname": "coolbeans.sofax" } } } ``` Updated `nanoid` from `5.1.9` to `5.1.16` Removed morgan library, refactored logs to include more information in the message, and renamed the request-log field from `status` to `statusCode`. Upgraded Temporal (`temporalio/*`) libs from v1.17.0 to v1.20.3 ### `@outputai/llm` Added stricter LiquidJs settings for prompt files parsing. The following configurations were added: ```js theme={null} { strictFilters: true, strictVariables: true, lenientIf: true } ``` * Upgraded `liquidJS` from v10.25.7 to v10.27.2 (`.prompt` files template parser). * Permanent AI SDK failures now surface in logs, traces, hooks, and workflow results as the original AI SDK error (for example `AI_APICallError`) instead of a wrapping `FatalError` whose message started with `AI-SDK fatal error`. * Schema-mismatch `NoObjectGeneratedError` messages are no longer rewritten to append `First issue is "…" at path […]`. The AI SDK error (and its Zod cause chain) is returned unchanged. * Added `'google-vertex'` provider name support to use the `@ai-sdk/google-vertex` provider, the previous `'vertex'` is still supported as an alias, and it is deprecated; * Added `'amazon-bedrock'` provider name support to use the `@ai-sdk/amazon-bedrock` provider, the previous `'bedrock'` is still supported as an alias, and it is deprecated; * `registerProvider('vertex', …)` and `registerProvider('bedrock', …)` now throw — register under `'google-vertex'` or `'amazon-bedrock'` instead (see the v0.10 → v0.11 migration guide); * Fixed a bug causing the wrong model to be used to calculate LLM costs when the model name was referenced by another provider. Cost lookup is now `provider` + `model` against the [models.dev](https://models.dev) catalog, so custom `registerProvider` names that are not models.dev ids correctly get `null` cost instead of an arbitrary provider's rates. ### `@outputai/core` * Removed workflow and activity wrappers, so both return their original output; * Moved trace information to the root workflow's `memo`, in a new format: ```json theme={null} { "trace": { "local": "...", "remote": "..." } } ``` * Removed `aggregations` from activity lifecycle and error hook payloads. * Added `TransparentFatalError`, a non-retryable wrapper that surfaces its cause as the original error in logs, traces, hooks and workflow results. * Refactored workflow and activity error handling: * Workflow * `ContinueAsNew`, throw; * Cancellation, throw; * `FatalError`/`ValidationError`, create an `ApplicationFailure` and serialize the original error in `.details[0].error`; * `TemporalFailure`, throw; * Other errors, throw; * Activity * `CompleteAsyncError`, throw; * `TemporalFailure`, throw; * Other errors, create an `ApplicationFailure`, serialize the original error in `.details[0].error`, and determine whether it is non-retryable from the error class name and `activityInfo.retryPolicy.nonRetryableErrorTypes`; * `ValidationError` now extends from `FatalError`. * `FatalError` is now always handled as non retryable, user configurable `activityOptions.retry.nonRetryableErrorTypes` will not overwrite it anymore. * Forwarded Temporal SDK and native Core logs through Output's logger for consistent production/development formatting, omitted redundant failure logs (workflow/activity failures), and added `OUTPUT_TEMPORAL_LOG_LEVEL` to configure verbosity; * Refactored workflow and activity error logs: * Workflow * `ContinueAsNew`, log a successful workflow end instead of an error; * Cancellation, log the serialized error chain without `stack` or Temporal's internal `.failure`; * `FatalError`/`ValidationError`, log the serialized original error without `stack`; * `TemporalFailure`, log the serialized Temporal error chain without `stack` or `.failure`; * Other errors, do not log because Temporal retries the Workflow Task; * Activity * `CompleteAsyncError`, do not log an error and close the trace node as an asynchronous handoff; * `TemporalFailure`, log the serialized error without `stack`; * Other errors, log the serialized original error without `stack` before converting it to an `ApplicationFailure`. **Workflow Activity Invocation** * Refactored workflow activity invocation so steps, evaluators, and shared activities use the same runtime dispatcher instead of `this`-based handler dispatch. Workflow handlers no longer need to be rewritten from arrow functions into regular functions for activity dispatch, reducing AST rewrite complexity during worker startup and making bundling more predictable. * Step and evaluator calls can now be placed in helper functions and imported helper modules used by a workflow. Helpers no longer need to pass a workflow-bound `this` value through their call chain. **Child Workflow Activity Options** * A child workflow's definition-level `options.activityOptions` now override activity options inherited from its parent. Invocation-level `activityOptions` still override both, and a step or evaluator's own `options.activityOptions` remain the most specific. * If a parent must override a child's retry or timeout configuration, pass `activityOptions` explicitly when invoking the child workflow. **Shared Activity Namespaces** * Removed the previous `"$shared"` activity namespace by registering shared activities into each workflow namespace. This means workflows can call local and shared activities through the same activity resolution path. * Shared activity types now use `"#"` instead of `"$shared#"`. * Added validation that prevents workflow-scoped activities from using the same activity name as a shared activity. If a workflow defines an activity with the same name as a shared activity, worker startup now fails validation instead of allowing ambiguous activity resolution. **Workflow Code Validation** * Added fail-fast validation for default exports and `export *` declarations in steps/evaluators files. Steps and evaluators already needed to be exposed through named exports for workflow rewriting. The worker now reports these unsupported forms directly during startup. ```js theme={null} // valid export const foo = step( { name: 'foo' } ); // invalid export default step( { name: 'foo' } ); export * from './other_steps.js'; ``` * Added fail-fast validation for unsupported steps/evaluators import shapes. Imports from steps/evaluators files already needed to use named imports or destructured requires for workflow rewriting. The worker now fails fast with a validation error for unsupported import shapes like default imports, namespace imports, or non-destructured requires. ```js theme={null} // valid import { foo } from './steps.js'; const { bar } = require( './evaluators.js' ); // invalid import foo from './steps.js'; import * as steps from './steps.js'; const steps = require( './steps.js' ); ``` * Added validation that activity calls must happen inside functions. Calling a step or evaluator at module top level now fails validation. ```js theme={null} import { foo } from './steps.js'; // invalid foo(); ``` * Workflow errors passed to `onWorkflowError` and workflow-sourced `onError` are rehydrated to `Error` instances after crossing the Temporal sandbox (preserving `name`, `message`, `cause`, and other enumerable properties). **Global proxy** * Removed Core worker’s automatic global Undici proxy setup. Starting a worker no longer calls `setGlobalDispatcher()` when proxy environment variables are detected. `@outputai/http` and `@outputai/llm` continue configuring their own proxy-aware dispatchers. * This affects direct and third-party Fetch/Undici calls that relied on Core’s global dispatcher; calls through @outputai/http or @outputai/llm retain proxy support. Added `hasErrorType()` workflow tool. It allows detecting if an error has a given Error class in its error chain, either in `.name`, `.type` or `instanceof`. It can be used to test typed errors thrown from activities. * Upgraded Temporal (`temporalio/*`) libs from v1.17.0 to v1.20.3 * Upgraded `undici` from v8.5.0 to v8.9.0 Added a mechanism to await for all hook callbacks to complete before shutting down the worker. Max awaiting period is 30s. * `workflow()`, `step()`, and `evaluator()` now pass the value returned by the Zod `inputSchema` parser to their handler. Workflows and steps also return the value produced by their `outputSchema` parser. Zod transforms, coercions, defaults, and object-key stripping therefore affect the values handled and returned by these components instead of only validating them. * Added `@outputai/core/temporal` for worker-side Temporal access that shares the running worker's connection and namespace; * Added `createTemporalClient()`, which returns a Temporal `Client` for operations on any workflow; do not close `client.connection` — the worker owns it; * Added `getCurrentWorkflowHandle()`, which returns a handle pinned to the invoking workflow's `workflowId` + `runId` (Temporal Activities only); * Both helpers throw a non-retryable `FatalError` outside the worker runtime (and outside an activity context for `getCurrentWorkflowHandle()`); never import `@outputai/core/temporal` from `workflow.ts`. * Added `emit()` to `/hooks` entrypoint to emit custom events. Emitted events can be listened using `on()` and will have their payload wrapped in an envelope: ```js theme={null} { eventId: string, eventDate: number, outputActivityKind?: string, workflowDetails?: {}, activityInfo?: {}, payload: } ``` Events emitted outside an activity context omit `outputActivityKind`, `workflowDetails`, and `activityInfo`. * Added the same wrapping envelope to all other events listened to with `on()`: `http:request`, `cost:llm:request`, `cost:http:request`; * Added internal activity events to activity lifecycle: `onActivityStart`, `onActivityEnd`, `onActivityError`; * Updated internal triggers so `onError()` no longer receives errors from the internal `$catalog` workflow. ### `@outputai/cli`, `output-api` Add workflow monitor command, update workflow history API to be resumable ### `@outputai/http` **HTTP clients** * Replaced `fetch` with `outputFetch`, the explicitly named Fetch-compatible API for traced HTTP requests. * Uses Undici as its canonical internal implementation while accepting Node and Undici `Request` inputs and request options containing either realm's `Headers` or `FormData` objects. * Normalizes Node request objects at the API boundary instead of replacing Node's global Fetch classes with `undici.install()`. * Rejects mixed request families, such as a Node `Request` combined with Undici `FormData`. * Removed the top-level `RequestInfo` and `RequestInit` type exports. ```ts theme={null} import { outputFetch } from '@outputai/http'; const response = await outputFetch( 'https://api.example.com/status' ); ``` * Replaced `httpClient` with `createKyClient`, which returns a standard Ky client configured to use `outputFetch`. * Upgraded Ky from 1.14.3 to 2.0.2. Public Ky behavior now follows Ky 2, including the `prefix` option, state-object hook arguments, empty-response JSON parsing, `searchParams` merging, and pre-parsed `HTTPError.data`. * Removed the top-level `HTTPError`, `TimeoutError`, `HttpClientOptions` exports. * Added the complete Ky namespace as a named export `ky`. ```ts theme={null} import { createKyClient, type ky } from '@outputai/http'; const options: ky.Options = { prefix: 'https://api.example.com', timeout: 30_000 }; const client: ky.KyInstance = createKyClient( options ); ``` * Changed Ky and Undici from bundled dependencies to peer dependencies. ### `@outputai/cli`, `@outputai/credentials` Updated `js-yaml` from `4.3.0` to `4.3.1` **v0.10.0** 2026-07-09 - minor release See the [v0.9.0 - v0.10.0 migration guide](/migrations/v0.9.0-to-v0.10.0). ### `output-api` Workflow result endpoints no longer include unavailable trace destinations instead of returning them as `null`. This affects: * `POST /workflow/run` * `GET /workflow/{id}/result` * `GET /workflow/{id}/runs/{rid}/result` *Before:* ```json theme={null} { ... "trace": { "destinations": { "local": null, "remote": null } } } ``` *After:* ```json theme={null} { ... "trace": { "destinations": {} } } ``` ### `@outputai/cli`, `output-api` Add API endpoint and CLI command to get input from a workflow run ### `@outputai/cli` The JSON output for workflow result commands no longer includes unavailable trace destinations as `null`. This affects: * `output workflow run ... --json` * `output workflow result --json` *Before:* ```json theme={null} { "trace": { "destinations": { "local": null, "remote": null } } } ``` *After:* ```json theme={null} { "trace": { "destinations": {} } } ``` ### `@outputai/llm` Refactored Anthropic's error `"Grammar compilation timed out."` handling not to throw `FatalError` as this is transient and `FatalError`s terminate the workflow execution without retries. It seems that the Anthropic API throws this error (HTTP status code 400) when grammar compilation times out for a structured output schema, but after some investigation it was assessed that this error is indeed transient. ### `@outputai/core` **Trace Changes** * Internal Activity `getTraceDestinations` is no longer invoked when workflow has `disableTrace: true` configuration. * Workflow trace destinations now omit unavailable destinations instead of returning them as `null`: *Before:* ```json theme={null} { "output": "foo", "trace": { "destinations": { "local": null, "remote": null } } } ``` *After:* ```json theme={null} { "output": "foo", "trace": { "destinations": {} } } ``` * Internal activities like `getTraceDestinations` and `sendHttpRequest` are no longer omitted in the trace files. **HTTP helper header changes** * Both `sendHttpRequest` and `sendPostRequestAndAwaitWebhook` can now interpolate environment variable values in header values: ```js theme={null} sendHttpRequest( { url, headers: { Authorization: 'Bearer $TOKEN' } } ); ``` When executing this request, `$TOKEN` will be replaced by the value of `process.env.TOKEN`. **sendHttpRequest output changes** * The response of `sendHttpRequest` no longer includes body or headers by default. Use the `responseOptions` argument to configure this: ```js theme={null} sendHttpRequest( { url, responseOptions: { includeHeaders: true, includeBody: true } } ); ``` * Response headers included via `responseOptions.includeHeaders` are redacted by header name. This covers common sensitive header names such as authorization, token, secret, password, cookie, and key, but it is a best-effort heuristic. Removing support for non-wrapped activity results and legacy child workflow executions (pre v0.8.0). Workflow executions from those versions can no longer be replayed. Add support to Temporal worker tuner options. This can be set using a new environment variable `TEMPORAL_WORKER_TUNER` that accepts a JSON value. **v0.9.2** 2026-07-03 - patch release ### `@outputai/cli`, `@outputai/core`, `@outputai/credentials`, `@outputai/evals`, `@outputai/http`, `@outputai/llm`, `@outputai/output`, `output-api` Pinning v24.15.0 as the minimal supported Node version ### `@outputai/core` Improving catalog startup performance by storing and reading hash from memo. Storing workflow names in memo. ### `output-api` Improving start/run workflows performance by not querying an workflow to validate `workflowName` argument. **v0.9.1** 2026-07-01 - patch release ### `@outputai/cli` Add `output workflow history ` — renders a run's step timeline as a terminal waterfall (each step's start offset and duration), mirroring the Agents HQ Timeline view. It pages the `GET /workflow/{id}/history` endpoint and correlates the Temporal events into per-step spans (numbering parallel fan-outs `#1..#N`). `--format json` emits the structured spans, `--raw` prints the endpoint's verbatim response, and `--run-id`, `--include-payloads`, `--width`, and `--no-color` are supported. Failed steps list their error reason beneath the chart (when payloads are included), and `FORCE_COLOR` forces ANSI output through a pipe. The same waterfall is available in the `output dev` TUI: from the Recent Runs tab, press `g` on any run to open its step graph as a full-width overlay. The overlay shows the run's status, start time, and duration, and live-updates while the run is in progress (the time axis tracks elapsed wall-clock and running bars grow). Select a step with `↑/↓` to inspect its input, output, and timing (start/end/duration) in the detail pane; `←/→` switches tabs and `e` expands a field full-screen. ### `@outputai/http` * Added a custom dispatcher that disables HTTP/2 (`allowH2: false`) on fetch, it uses `EnvHttpProxyAgent`; * Added support for dispatcher in the init argument of fetch; it has precedence over the custom dispatcher. ### `@outputai/core` * Disabled HTTP/2 (`allowH2: false`) in the global fetch dispatcher configured by `setGlobalDispatcher` when proxy env vars are detected; * Disabled HTTP/2 (`allowH2: false`) in the webhook functions `sendHttpRequest` and `sendPostRequestAndAwaitWebhook` by using a dispatcher (`EnvHttpProxyAgent`). ### `@outputai/llm` * Disabled HTTP/2 (`allowH2: false`) in the dispatcher of the fetch client used when consuming the AI SDK and fetching model pricing; * Replaced the `Agent` dispatcher in favor of `EnvHttpProxyAgent` to respect the proxy env vars. \[OUT-506]. **v0.9.0** 2026-06-26 - minor release See the [v0.8.0 - v0.9.0 migration guide](/migrations/v0.8.0-to-v0.9.0). ### `@outputai/core` Added activity lifecycle hooks: `onActivityStart`, `onActivityEnd`, `onActivityError`. Payload: ```ts theme={null} { eventId: string, eventDate: number, workflowDetails: object, // Serialized and simplified Temporal's workflowInfo() return activityInfo: object, // Temporal's activityInfo() return outputActivityKind: string, // Kind of activity: step, evaluator, etc aggregations: object // Total cost, http calls and tokens used in the activity (only present in End/Error events) } ``` Added a new `Logger` export for structured logging from both workflows and steps. Logs use the same `message` plus `metadata` shape as the internal worker logger and are routed through the worker's Winston logger. All log messages are enriched with execution metadata: * Workflow logs include `workflowType`, `workflowId`, and `runId`. * Step logs include the same workflow fields, plus `activityType` and `activityId`. ```ts theme={null} import { Logger } from '@outputai/core'; Logger.info( 'I am a log', { extraInfo: 'none' } ); // workflows inside workflow and steps ``` Supported levels are: * error * warn * info * http * verbose * debug * silly The default displayed level is debug in development and info in production. Override it with `OUTPUT_LOG_LEVEL` env var. This setting also affects internal worker logs. Including /dist when calculating catalog hash to define if catalog workflow needs restart. Excluding /temp. ### `@outputai/cli`, `@outputai/core`, `@outputai/http`, `@outputai/llm`, `output-api` Updating libraries to fix vulnerabilities ### `@outputai/cli` Replace the custom `--format json` option with oclif's built-in `--json` flag across all workflow commands (OUT-419). `--json` suppresses informational logs (e.g. `Fetching result for workflow...`) and emits clean, machine-readable JSON to stdout, fixing output that previously mixed status text into JSON. **Breaking change:** `--format json` is no longer accepted. Use `--json` instead. * `workflow result`, `workflow status`, `workflow run`, `workflow cost`, `workflow debug`, `workflow test`: the `--format` flag is removed; pass `--json` for JSON output (text remains the default). * `workflow list`, `workflow runs list`, `workflow dataset list`: `--format` keeps its non-JSON options (`list`/`table`/`text`); use `--json` for JSON output. The "update available" banner no longer prints to stdout: it now goes to stderr (keeping stdout clean for piping in every mode) and is suppressed entirely under `--json`. CLI `start`/`run`/`test`/`dataset generate` now resolve scenarios and route execution against `--catalog`/`OUTPUT_CATALOG_ID` instead of the API server's default catalog. This removes the \~30s scenario-resolution stall in worktrees where the default catalog has no worker polling it. `workflow test` and `workflow dataset generate` also gain a `--catalog` flag (env: `OUTPUT_CATALOG_ID`), matching `list`/`start`/`run`. Add an "Enter input" option to the `output dev` run pane. Edit a payload and press ctrl+r to run it as-is without saving, or ctrl+s to save it as a scenario first. Previously every ad-hoc run forced you to name and save a scenario file. ### `@outputai/cli`, `output-api` Add new endpoint for workflow history with server side events **v0.8.1** 2026-06-22 - patch release ### `@outputai/core` * Updating connection monitor strategy to ping workflowService instead of healthService. * Adding new env vars to configure Temporal worker shutdownForceTime and shutdownGraceTime: * TEMPORAL_SHUTDOWN_FORCE_TIME * TEMPORAL_SHUTDOWN_GRACE_TIME ### `@outputai/cli` Resolve datasets and evals for nested workflow folders by the workflow's registered name (via the worker catalog), keeping the flat-path lookup as an offline fast path. `output workflow test`, `dataset generate`, and `dataset list` now work for workflows in nested directories (e.g. `src/workflows/a/b/c` registered as `a_b_c`) without a symlink. `output workflow test` also fails fast with an actionable message when a `_eval` workflow's source exists but didn't compile to `dist`. ### `output-api` Updating connection monitor strategy to ping workflowService instead of healthService. **v0.8.0** 2026-06-22 - minor release See the [v0.7.0 - v0.8.0 migration guide](/migrations/v0.7.0-to-v0.8.0). ### `output-api` `getWorkflowResult` now fetches only the first history event (`WorkflowExecutionStarted`) to extract the workflow input, instead of paging through the full event history. Makes input extraction on the result endpoints (`/workflow/:id/result` and `/workflow/:id/runs/:rid/result`) O(1) regardless of history size. Added new `/ready` endpoint to report if API is ready to answer to requests. Added Temporal connection monitoring. When unhealthy, `/ready` return 503; if lost the API shuts down. Expose structured workflow failure details (`failure` object with `message`, `type`, `retryable`, and a sanitized `cause` chain) in `/workflow/run` and `/workflow/:id/result` responses, alongside the existing `error` string. Also log Temporal/gRPC client errors with full nested context (cause chain, gRPC `code`/`details`, redacted metadata keys, `workflowId`/`runId`/`taskQueue`/query) while keeping client-facing HTTP responses sanitized. The `continued` workflow status was renamed to `continued_as_new` in API responses. **Explicit Status Fields** | Endpoint | HTTP response JSON path | Generated client path | | - | - | - | | `POST /workflow/run` | `status` | `response.data.status` | | `GET /workflow/{id}/result` | `status` | `response.data.status` | | `GET /workflow/{id}/runs/{rid}/result` | `status` | `response.data.status` | | `GET /workflow/{id}/status` | `status` | `response.data.status` | | `GET /workflow/{id}/runs/{rid}/status` | `status` | `response.data.status` | | `GET /workflow/runs` | `runs[].status` | `response.data.runs[].status` | **History Metadata Status Fields** These endpoints also return workflow status in the history metadata object. The OpenAPI schema currently leaves this nested object unexpanded. | Endpoint | HTTP response JSON path | Generated client path | | - | - | - | | `GET /workflow/{id}/history` | `workflow.status` | `response.data.workflow.status` | | `GET /workflow/{id}/runs/{rid}/history` | `workflow.status` | `response.data.workflow.status` | **Backwards support** In the CLI, the old value is still supported. ### `@outputai/core` improve worker startup time by only calculating workflow sources Added Temporal connection monitoring. When connection is lost, graceful shuts down the worker. Fixed missing eventDate fields on hook types. Add an opt-in `output-worker --check` workflow bundle check that reproduces the worker's webpack bundling without a Temporal server, catching bad workflow imports — e.g. a transitive `node:` built-in — before they crash-loop the worker at startup. `tsc` cannot detect these; only the Temporal bundle can. * `output-worker --check` bundles workflows via the same `bundleWorkflowCode` path `Worker.create` uses, exits non-zero with the offending module named, and needs no Temporal connection or worker env. * Scaffolded projects gain an opt-in `output:worker:check` script plus README/CI guidance (not wired into any build). * Removed workflow-level usage aggregation from `@outputai/core`; workflows no longer collect activity attributes into final `aggregations` totals or expose those totals in workflow run results. * Reworked workflow-to-workflow invocation so direct workflow calls made from workflow code now consistently execute as Temporal child workflows, including calls made through helper functions outside the parent workflow handler. * Removed workflow call rewriting from the workflow webpack loader while preserving activity, step, and evaluator call rewriting. * Renamed workflow invocation configuration types from `WorkflowInvocationConfiguration` to `WorkflowInvocationOptions`. * Updated workflow invocation options so activity overrides are passed as top-level `activityOptions` instead of the previous `options` property. * Refactored workflow validation internals around centralized schemas and explicit validator classes for workflows, steps, and evaluators. * Hardened Zod schema detection for multi-package or multi-realm Zod v4 environments. ### `@outputai/cli`, `output-api` * Updated workflow result API responses to return workflow output and trace metadata without workflow-level `aggregations`. * Regenerated CLI API types to match the workflow result response shape. ### `@outputai/cli` Faster CLI startup: ship `oclif.manifest.json` in the published package so only the invoked command module is loaded (instead of importing every command on every invocation), move the update check off the critical path (the init hook now only reads the local cache and refreshes it via a detached background process with a 5s registry timeout, instead of awaiting an unbounded `npm view` subprocess), and load `undici` only when a proxy env var is configured. `workflow cost` now calculates costs from the trace events themselves (the as-charged "Original" cost) and applies `costs.yml` as an override layer (the "Adjusted" cost), displaying both per model and per host. This fixes models with no `costs.yml` entry (e.g. `gpt-5.5`) and HTTP hosts (e.g. `api.exa.ai`, `api.firecrawl.dev`) previously reporting \$0, and surfaces where the configured `costs.yml` rate diverges from what was actually charged. The bottom line shows the adjusted total with the as-charged total alongside. Costs come exclusively from trace cost attributes: LLM nodes with an `llm:usage` event and HTTP calls with an `http:request:cost` event are counted as-charged (even on error responses — the event proves a charge); calls without events are not priced. Traces from SDK versions that predate cost attributes (\< 0.5) report no costs. Only exact (`computed`) recomputes override an event cost — estimates and failed recomputes never do, and a configured `$0` price is now honored. Body-dependent `costs.yml` service rules require traces recorded with `OUTPUT_TRACE_HTTP_VERBOSE=true` (the dev default). **`--format json` field changes** (the report shape changed; update any scripts parsing it): `llmTotalCost` → `llmOriginalCost`/`llmAdjustedCost`; `services[]`/`serviceTotalCost` → `httpCosts[]` (grouped by `host`) with `httpOriginalCost`/`httpAdjustedCost`; `unknownModels` removed; per-call `cost`/`warning` → `originalCost`/`adjustedCost`; new `originalTotalCost`; `totalCost` is now the adjusted total. Surface workflow aliases and honor `OUTPUT_CATALOG_ID` in `output workflow list`. * The default list output now appends `(aliases: ...)` to workflows that have registered aliases, which previously only appeared in `--format table`/`--format json` (OUT-444). * Add a `--catalog` flag (env `OUTPUT_CATALOG_ID`) that resolves workflows from a specific catalog, falling back to the server-default catalog — matching the existing behavior of `run` and `start` (OUT-489). ### `@outputai/llm` Route `` blocks to the AI SDK `system` option instead of leaving them in the `messages` array. * `loadAiSdkTextOptions` now splits resolved messages: system blocks go to the top-level `system` option (as `SystemModelMessage[]`, so per-message `cacheControl`/`providerOptions` are preserved); only user/assistant/tool messages stay in `messages`. `Agent` consumes the split `system` directly as its `instructions`. * Silences the AI SDK warning that system messages in `messages` are a prompt-injection risk; `generateText`/`streamText`/`Agent` also set `allowSystemInMessages: true` as defense-in-depth for caller-supplied message histories. Add per-message provider options to `.prompt` files via `messageOptions`. * Define named `messageOptions` sets in front matter and attach them to message blocks with `options=""` (e.g. ``); each set is a provider-namespaced `providerOptions` object merged onto that message. * Enables Anthropic prompt caching (`{ anthropic: { cacheControl: { type: ephemeral } } }`) and any other per-message provider option, on any provider. * Cost tracking now reports cached input tokens (`input_cached`) even for models whose pricing record lacks a `cache_read` rate, so cache savings are visible in usage aggregations instead of silently disappearing. **v0.7.0** 2026-06-10 - minor release See the [v0.6.0 - v0.7.0 migration guide](/migrations/v0.6.0-to-v0.7.0). ### `@outputai/core` **Workflow hooks** Updated `onWorkflowStart()`, `onWorkflowEnd()`, `onWorkflowError()` hooks payload: ```js theme={null} { eventId, eventDate, workflowDetails, error? } ``` Where `eventDate` is the event timestamp in milliseconds. Where `workflowDetails` is an abstraction over [Temporal's `workflowInfo()`](https://typescript.temporal.io/api/interfaces/workflow.WorkflowInfo): ```ts theme={null} { attempt: number, continuedFromExecutionRunId?: string | undefined, firstExecutionRunId: string, parent?: { runId: string, workflowId: string, namespace: string } | undefined, root?: { runId: string, workflowId: string } | undefined, runId: string, runStartTime: number, // epoch startTime: number, // epoch workflowId: string, workflowType: string } ``` **Error hook** Updated `onError()` hooks payload. The fields change according to the `source`: **Source is "workflow"** ```js theme={null} { eventId, eventDate, source, workflowDetails, error } ``` Where `workflowDetails` is the same as in workflow hooks. **Source is "activity"** ```js theme={null} { eventId, eventDate, source, workflowDetails, activityInfo, outputActivityKind, error } ``` Where `activityInfo` is Temporal's `activityInfo()` [function return](https://typescript.temporal.io/api/interfaces/activity.Info). And `outputActivityKind` is the framework flavor of the Temporal Activity: `step`, `evaluator` or `internal_step`. **Source is "runtime"** ```js theme={null} { eventId, eventDate, source, error } ``` **"on()" hook** Updated `on()` hooks with better typing and a new envelope. **Envelope** All events have these fields: * `eventId` * `eventDate` * `workflowDetails`: Same from other hooks * `activityInfo`: From Temporal * `outputActivityKind` **Typing** Besides the envelope fields, each event also has its own fields, their types are specified by the event emitter: * `on( 'http:request', handler )` from `@outputai/http`; * `on( 'cost:http:request', handler )` from `@outputai/http`; * `on( 'cost:llm:request', handler )` from `@outputai/llm` **Execution Context** Updated `getExecutionContext()` from `core/sdk_activity_integration` to return: ```js theme={null} { activityInfo, workflowFilename } ``` **Trace File** Updated trace workflow node ids to use Temporal `runId`, instead of `workflowId`. This helps to create trees when child workflows "continued as new". Added worker telemetry logs: print Temporal worker status and node memory every X ms, configured by `OUTPUT_WORKER_TELEMETRY_INTERVAL_MS` env var. Default `0` - off. Message examples: **Dev** ``` [info] Telemetry: Worker { status: { runState: "RUNNING", numHeartbeatingActivities: 0, workflowPollerState: "POLLING", activityPollerState: "POLLING", hasOutstandingWorkflowPoll: true, hasOutstandingActivityPoll: true, numCachedWorkflows: 1, numInFlightWorkflowActivations: 0, numInFlightActivities: 0, numInFlightNonLocalActivities: 0, numInFlightLocalActivities: 0 }, memory: { availableMemory: 7500000000, constrainedMemory: 20000000000000000000, memoryUsage: { rss: 582348800, heapTotal: 400000000, heapUsed: 200000000, external: 800000000, arrayBuffers: 300000000 } } } ``` **Prod** ```json theme={null} { "environment": "production", "level": "info", "memory": { "availableMemory": 7500000000, "constrainedMemory": 20000000000000000000, "memoryUsage": { "arrayBuffers": 1445268, "external": 800000000, "heapTotal": 400000000, "heapUsed": 200000000, "rss": 300000000 } }, "message": "Worker", "namespace": "Telemetry", "service": "output-worker", "status": { "activityPollerState": "POLLING", "hasOutstandingActivityPoll": true, "hasOutstandingWorkflowPoll": true, "numCachedWorkflows": 1, "numHeartbeatingActivities": 0, "numInFlightActivities": 0, "numInFlightLocalActivities": 0, "numInFlightNonLocalActivities": 0, "numInFlightWorkflowActivations": 0, "runState": "RUNNING", "workflowPollerState": "POLLING" }, "timestamp": "2026-06-02T21:54:29.261+00:00" } ``` Improve trace error serialization to preserve nested error causes. Error entries in trace files now include the error `name`, `message`, `stack`, and recursively serialized `cause` values up to 10 levels deep, including JSON-safe non-Error causes where present. ```js theme={null} { name: "from error.constructor.name", message: "from error.message", stack: "from error.stack", cause: { // from .cause name: "from error.constructor.name", message: "from error.message", stack: "from error.stack", cause: { ... // up to 10 levels } } } ``` ### `@outputai/llm` * Added the `generateImage()` function for image generation, including image model loading, image prompt options, and wrapped image responses; * Improved public TS types by deriving AI SDK options and results from the upstream `ai` package; * Removed unused TS types; * Added validation for prompt skills, text generation arguments, and image prompt options; * Updated `streamText()` to support prompt skills and tools consistently with `generateText()`. * Added runtime image inputs to `generateImage()`, including image-to-image generation and optional masks for image editing; * Added validation and TypeScript types for `generateImage()` `images` and `mask` arguments; * Added conversion of AI SDK non-retryable API errors to `FatalError` across `generateText()`, `streamText()`, and `generateImage()` so permanent provider failures do not trigger workflow/activity retries: * APICallError (when `.isRetriable() === false` ) * InvalidArgumentError * InvalidDataContentError * InvalidPromptError * LoadAPIKeyError * LoadSettingError * NoImageGeneratedError * NoSuchModelError * NoSuchProviderError * UnsupportedFunctionalityError Recreate AI SDK `NoObjectGeneratedError` schema validation failures as new `NoObjectGeneratedError` instances with a clearer message: ```txt theme={null} No object generated: response did not match schema. First issue is "Invalid input: expected string, received number" at path [name]. ``` * Updated `@ai-sdk/*` providers and `ai` itself to peer dependencies, with these supported ranges: * `ai`: `>=6 <7` * `@ai-sdk/amazon-bedrock`: `>=4 <5` * `@ai-sdk/anthropic`: `>=3 <4` * `@ai-sdk/azure`: `>=3 <4` * `@ai-sdk/google-vertex`: `>=4 <5` * `@ai-sdk/openai`: `>=3 <4` * `@ai-sdk/perplexity`: `>=3 <4` * Built-in providers are now initialized lazily. Provider packages are imported when `@outputai/llm` is loaded, but provider instances are created only when first requested by a prompt. * No longer re-exports Tavily, Exa, or Perplexity search tool factories. * `getRegisteredProviders()` was renamed to `getProviderNames()`. ### `@outputai/llm`, `output-api` Fixing vulnerabilities by updating `qs` and `liquidjs` dependencies. ### `@outputai/http`, `@outputai/llm` Exported event payload types for hook consumers. * `@outputai/http` now exports `HttpRequestEvent` for `http:request` and `HttpRequestCostEvent` for `cost:http:request`. * `@outputai/llm` now exports `LLMUsageEvent` for `cost:llm:request`. Use these with `@outputai/core/hooks` as `on( 'http:request', handler )`, so applications can type event-specific fields without redefining the payload shapes locally. ### `@outputai/cli` `credentials set` and `credentials edit` now check whether the current key can decrypt the existing credentials file before re-encrypting. On a key mismatch they abort with a clear warning that the wrong key may be in use and the file would be re-encrypted under a different key. Pass `--force` / `-f` to proceed anyway (re-encrypts from empty, discarding the undecryptable values). **v0.6.0** 2026-05-29 - minor release See the [v0.5.2 - v0.6.0 migration guide](/migrations/v0.5.2-to-v0.6.0). ### `output-api` Removed `.attributes` field from workflow results (both `/run` and `/results` endpoints) ### `@outputai/core` Rewriting the catalog workflow startup logic to better handle multiple instances of the worker and avoiding restarting the workflow unnecessarily. * Removed property `.attributes` from workflow result wrapper object: Workflows will no longer accumulate or expose attributes; * Added `__output_workflow_wrapper_version=1` field on workflow wrapper object to better version it; * Removed Signals-based communication between Activities and Workflows to share individual attributes: * Each activity now aggregates all attributes of the events that happened within it. This is returned in a new wrapper around the activity: ```js theme={null} { __output_activity_wrapper_version: 1, // internal flag to indicate this wrapper's version output: ..., // the raw output from the activity aggregations: { // aggregation object with total llm/http usage and cost from all requests of this activity cost: { total: 1 // total cost from all http and llm requests }, tokens: { // breakdown of all llm tokens used total: 10, input: 3, cached_input: 1, output: 4, reasoning: 2 }, httpRequests: { // total number of http calls made total: 3 } } } ``` * Workflows now read these aggregations and merge them to create the final `.aggregations` object returned in its result, which is unchanged; * When Activities fail, a fallback Signal is sent with the aggregations so workflows can still compute them, avoiding data loss. ### `@outputai/cli` Removed "Attributes" tab from Recent Runs > \[Workflow view]. **v0.5.2** 2026-05-27 - patch release ### `@outputai/http` Propagate the per-request id across `Response.clone()` so cost emission works from inside ky `afterResponse` hooks. ky clones the response before invoking the hook, which stripped the symbol property `addRequestCost` reads to correlate the request — every hook calling `addRequestCost(response, value)` silently dropped its cost. Patches `clone()` on the original response so each clone re-runs `addRequestIdToResponse`, propagating the tag through any depth of clones. Header-based fallback isn't viable — undici responses are immutable on the received side. Also tightens the `addRequestIdToResponse` signature to `: void` (was `: Response`). The function mutates in place; the return-the-input pattern was misleading. The one external call site already discarded the return, so no consumer code needs to change. ### `@outputai/core` Every payload emitted through the framework's `messageBus` now carries a UUID v4 `eventId` and millisecond epoch `eventDate` — stamped at the bus layer, so events emitted via `emitEvent` *and* lifecycle hook payloads (`onWorkflowStart`, `onWorkflowEnd`, `onWorkflowError`, `onError`) both receive them. Consumers can rely on `eventId` as a stable per-emit idempotency key — e.g., for webhook retry handling, ClickHouse `ReplacingMergeTree` dedup, audit logs. The previously emitted `requestId` is not safe for this purpose because `cost:http:request` and `http:request` for the same fetch share a `requestId`. Callers may pre-set `eventId` or `eventDate` on the payload to override the generated values (intended for deterministic retry scenarios). Additive — existing consumers ignoring these fields continue to work. ### `@outputai/cli` Bump default local Temporal namespace retention from 24h to 720h (30 days) so workflow runs aren't garbage-collected within a day during local development. Support multiple `npx output dev` stacks side-by-side: * Expose `OUTPUT_TEMPORAL_HOST_PORT` (default 7233) so dev Temporal can be relocated off 7233. * Document the multi-stack recipe (`DOCKER_SERVICE_NAME`, `OUTPUT_CATALOG_ID`, and the three `OUTPUT_*_HOST_PORT` knobs) in `cli.mdx`. * Surface an actionable hint when docker compose fails to bind a host port, naming the conflicting port and the env var that overrides it. ### `@outputai/cli`, `@outputai/core` Attribute signal emission is now opt-in via `OUTPUT_ENABLE_ATTRIBUTE_SIGNAL_EMISSION=true`. Each LLM call and HTTP request previously fired a Temporal signal back to the workflow, bloating workflow history on runs with many calls. With emission off (the new default), workflow results still expose `attributes` and `aggregations` keys but they are empty/zeroed, and the `cost:llm:request` / `cost:http:request` hooks do not fire. Set the env var on the worker process to opt back in. The CLI's dev docker-compose forwards the flag from the host shell, so `OUTPUT_ENABLE_ATTRIBUTE_SIGNAL_EMISSION=true output dev` opts in without editing compose. ### `output-api` Raise gRPC's default 4 MiB message-size cap on the API server's Temporal connection so workflow result envelopes larger than 4 MiB no longer fail with `RESOURCE_EXHAUSTED`. Configurable via the new `TEMPORAL_GRPC_MAX_MESSAGE_SIZE_BYTES` env var (default 32 MiB). **v0.5.1** 2026-05-22 - patch release ### `@outputai/core` Fix worker activity Temporal client to use the configured namespace when signaling workflows. This resolves unauthorized signal errors in Temporal Cloud production namespaces. Improve reliability of workflow usage and cost metadata collection. Transient Temporal signal failures while recording activity attributes are now handled gracefully, reducing the chance of worker interruptions during workflow runs. **v0.5.0** 2026-05-20 - minor release See the [v0.4.0 - v0.5.0 migration guide](/migrations/v0.4.0-to-v0.5.0). ### `@outputai/core`, `@outputai/http`, `@outputai/llm`, `output-api` Workflow runs now return durable usage and cost metadata alongside the workflow output. Each completed or failed run can include raw `attributes` plus convenient `aggregations` for total cost, token usage, and HTTP request counts. For example, API and CLI JSON results can now include: ```json theme={null} { "attributes": [ { "type": "llm:usage", "modelId": "gpt-4o", "total": 0.00122, "tokensUsed": 226 }, { "type": "http:request:cost", "url": "https://api.vendor.com/search", "total": 0.42 } ], "aggregations": { "cost": { "total": 0.42122 }, "tokens": { "total": 226 }, "httpRequests": { "total": 1 } } } ``` Cost events now emit the same attribute-shaped payloads used in workflow results, making hook handlers and saved run metadata easier to reconcile. This also updates `@outputai/http` request cost tracking and `@outputai/llm` response cost data to use the new attribute format. Learn more in the [workflow result docs](/api), [CLI result format](/packages/cli#workflow-result-json-format), and [cost events guide](/costs/cost-events). ### `@outputai/cli` Improved the dev TUI experience with clearer workflow run views, expanded full-screen modals, and more consistent layout and interaction patterns across screens. Workflow run details now show result attributes and aggregations alongside input/output data. For scaffolded projects running `output dev`, the local Docker Compose API service now uses the documented `OUTPUT_AWS_*` variables for remote S3 trace access. If you use remote trace storage locally, set `OUTPUT_AWS_REGION`, `OUTPUT_AWS_ACCESS_KEY_ID`, and `OUTPUT_AWS_SECRET_ACCESS_KEY` in your project environment; the accidental `AWS_*` passthrough is no longer used. ### `@outputai/http` Emit a new `http:request` event on every HTTP call made via `@outputai/http`'s `fetch`. The event fires on success, non-2xx responses, and network failures, with payload: ``` { requestId: string, method: string, url: string, status: number | undefined, durationMs: number, outcome: 'success' | 'error' | 'failure' } ``` Subscribers (`on('http:request', handler)`) also receive `workflowId`, `runId`, and `activityId` auto-attached by `emitEvent`. The existing `cost:http:request` event is unchanged — it continues to fire only when a consumer attaches a cost via `addRequestCost()`. Additive — no existing consumer breaks. ### `@outputai/core` Stream trace JSON when writing local files and uploading to S3, avoiding Node.js string length limits for large trace outputs. Added `runId` to the workflow context and the workflow-lifecycle hook payloads. `context.info.runId` exposes the Temporal run id for the current execution attempt; `onWorkflowStart`, `onWorkflowEnd`, and `onWorkflowError` payloads now include `runId` alongside `id` (workflow id). `executionContext` also carries `runId`, so any consumer subscribed via `on(...)` to an `emitEvent`-emitted event (e.g., `cost:llm:request`) receives `runId` automatically. Additive — existing consumers ignoring the field continue to work. ### `@outputai/llm` Increase built-in LLM provider fetch timeouts for long-running responses. Default AI SDK `maxRetries` to 0 so workflow retries are handled by Temporal. **v0.4.0** 2026-05-12 - minor release See the [v0.3.0 - v0.4.0 migration guide](/migrations/v0.3.0-to-v0.4.0). ### `@outputai/cli` Fixed `output credentials edit` modifying the encrypted credentials file on disk even when the user made no changes in their editor. Because AES-GCM uses a fresh nonce per encryption, the unconditional re-write produced new ciphertext bytes and left the file dirty in git on every invocation. The command now skips the write when the post-editor plaintext is identical to the original. Fixed `output dev` hanging until the health timeout when `docker compose up` exited before creating containers. The CLI now drains and captures recent Compose output, reports early Compose exits immediately, polls status with the same project directory used to start the stack, and only treats running containers as healthy. * Bumped scaffold prompt template default from `claude-haiku-4-5` to `claude-sonnet-4-6` and added a dated `current as of` comment pointing at the new `output-dev-model-selection` skill (workflow scaffold, blog_evaluator example, workflow README example). * No CLI behavior change beyond the new default model in generated `.prompt` files. Fix scenario loading in `output dev` for workflows whose name differs from their local folder path. For example, a workflow named `writing_editor` stored in `src/workflows/writing/editor` now shows and runs its scenarios correctly. ### `@outputai/llm` Bump `entities` dependency from v6 to v8. The API surface used (`encodeXML` / `decodeXML`) is unchanged, and v8's ESM-only / Node ≥ 20.19 requirements are already satisfied by this package. ### `@outputai/core` * Fix TypeScript declaration emit for exported workflows that use Zod schemas. * Allow TypeScript to generate `.d.ts` files for these workflows without non-portable Zod references. * Treat Zod as a peer dependency and avoid leaking schema-specific workflow context types through the invocation config. Fixed workflows having the status 'failed' when cancelled via the API/UI. Now they are correctly marked as 'cancelled'. Add support for discovering and running workflows from installed npm packages. Rename the Output.ai settings property in `package.json` from `output` to `outputai`. **v0.3.2** 2026-05-05 - patch release ### `@outputai/cli` Rebuild `output dev` as a full-featured INK TUI. Tabbed UI for Workflows, Recent Runs, Services, and Help with arrow-key navigation, an in-TUI scenario picker and JSON editor for running workflows, an expanded JSON modal for input/output, and a live `docker compose logs` tail with restart hotkeys. **v0.3.1** 2026-05-05 - patch release ### `@outputai/llm` Prevent template variables from injecting message blocks into rendered prompts. Variable content containing tag-shaped substrings (e.g. `` or `...`, common when evaluating webpages or chat transcripts) was being tokenized by `parsePrompt` as real message blocks, producing duplicate `system` messages that providers like Anthropic reject. `loadPrompt` now arms every `{{ ... }}` interpolation with an internal escape filter so variable output stays inert at parse time. **v0.3.0** 2026-05-05 - minor release See the [v0.2.0 - v0.3.0 migration guide](/migrations/v0.2.0-to-v0.3.0). ### `@outputai/cli`, `output-api` Use `catalog` as the public name for the routing/filtering target across the CLI and HTTP API: * `output workflow runs list` gains `--catalog`/`-c` (with `OUTPUT_CATALOG_ID` env fallback) and `GET /workflow/runs` accepts `?catalog=...`, scoping listed runs to a single worker's catalog/session. * `output workflow run` and `output workflow start` rename the routing flag to `--catalog`/`-c`. The previous `--task-queue` and `-q` are kept as deprecated aliases (oclif emits a warning when used). * `POST /workflow/run` and `POST /workflow/start` accept a `catalog` body field; the previous `taskQueue` field is still accepted as a deprecated alias and the API logs a deprecation warning when it is used. Internally the value is still a Temporal task queue — only the user-facing name changes. Fix the workflow runs pane in the CLI so the detail view reflects the highlighted run instead of always showing the latest run. `GET /workflow/runs` now includes `runId` per row, and the CLI fetches results via the pinned `GET /workflow/{id}/runs/{rid}/result` endpoint. Add new workflow history endpoint ### `@outputai/core` Optimizing local trace to use less memory and avoid "RangeError: Invalid string length" ### `@outputai/cli`, `@outputai/core`, `@outputai/credentials`, `@outputai/evals`, `@outputai/http`, `@outputai/llm`, `@outputai/output`, `output-api` **Dependencies updates** **Vulnerabilities fixed:** * uuid: Missing buffer bounds check in v3/v5/v6 when buf: (bump to `>=14.0.0`) * postcss: PostCSS has XSS via Unescaped \ in its CSS Stringify Output (bump to `>=8.5.10`) * @anthropic-ai/sdk: Claude SDK for TypeScript has Insecure Default File Permissions in Local Filesystem Memory Tool (bump to `>=0.91.1`) **Root package.json updates** * @changesets/cli: `2.30.0` -> `2.31.0` * eslint: `10.2.0` -> `10.2.1` * mintlify: `4.2.520` -> `4.2.536` * typescript-eslint: `8.58.2` -> `8.59.1` * vitest: `4.1.4` -> `4.1.5` **pnpm-workspace.yaml (catalog) updates** * @aws-sdk/client-s3: `3.1031.0` -> `3.1038.0` **sdk/cli/package.json updates** * @inquirer/prompts: `8.4.1` -> `8.4.2` * @oclif/core: `4.10.5` -> `4.10.6` * @oclif/plugin-help: `6.2.44` -> `6.2.45` * undici: `8.0.2` -> `catalog:` * orval: `8.8.0` -> `8.9.0` **sdk/llm/package.json updates** * @ai-sdk/amazon-bedrock: `4.0.95` -> `4.0.96` * liquidjs: `10.25.5` -> `10.25.7` ### `@outputai/http`, `@outputai/llm` * HTTP: Added a new event `cost:http:request` that is dispatched after calling `addRequestCost()`: the event's payload is `requestId`, `cost` and `url`; * LLM: Renamed `llm:call_cost` event to `cost:llm:request`; * LLM: Updated the format of the `.cost` property on `.generateText()` response and on the cost hook payload: `components` is now an array; * LLM: Updated `.streamText()` `onFinish()` callback to have the `.cost` property: contains the calculated cost for the stream. ### `@outputai/llm` Update perplexity-ai/ai-sdk to v0.1.3 re-export ai.jsonSchema for downstream use ### `@outputai/cli`, `@outputai/credentials` Improve encrypted credentials loading: add clearer errors when keys are missing or invalid and ensure the CLI exits gracefully instead of printing stack traces. ### `@outputai/cli` * Offer to initialize a git repository when running `output init`. Adds a `--skip-git` flag to opt out in non-interactive / scripted use. * Fix `--yes` / `--non-interactive` being rejected as "Nonexistent flag" by oclif's per-command parser when passed to any command. Add non-interactive mode with `--yes`/`--non-interactive` flags and TTY auto-detection for sandbox environments Enable multiple instance of Output to run locally simultaneously in Docker by enabling dynamic port mapping Shadow the worker container's `/app/node_modules` (root pnpm store) with a named Docker volume and run an explicit `output:worker:install` before `output:worker:watch`, so Linux-native packages installed in the container no longer leak into the host's `node_modules/`. Fix issue where values in .env files were silently ignored ### `@outputai/core`, `@outputai/credentials` * Added new hook functions `onWorkflowStart`, `onWorkflowEnd`, `onWorkflowError`: * `onWorkflowStart()`: Triggers when a workflow starts, receives the run id and workflow name; * `onWorkflowEnd()`: Triggers when a workflow ends (no error), receives the run id, workflow name and duration (elapsed time); * `onWorkflowError()`: Triggers when a workflow throws an error, receives the run id, workflow name, duration and error thrown; * Important: These three hooks are not triggered by the internal "\$catalog" workflow lifecycle; * Renamed `onBeforeStart()` hook to `onBeforeWorkerStart()`; * Fixed possible issue where a broken handler attached to `onBeforeStart()` could interrupt the worker process; * Added `activityId` and `workflowId` to `onError()` hook handler payload when source is `'activity'`; * Added `workflowId` to `onError()` hook handler payload when source is `'workflow'`. ### `@outputai/core`, `output-api` Updating Temporal libraries from `v1.15.0` to `v1.17.0`: * @temporalio/activity; * @temporalio/client; * @temporalio/common; * @temporalio/proto (dev dependency for tests); * @temporalio/worker; * @temporalio/workflow ### `@outputai/cli`, `@outputai/core` Add HTTP and gRPC proxy support for sandbox environments via HTTPS_PROXY and TEMPORAL_GRPC_PROXY env vars ### `@outputai/core`, `@outputai/http`, `@outputai/llm` Adding trace event attributes and adding method `addRequestCost` to attach cost related info to an HTTP call made with the http module ### `@outputai/http` **Custom fetch** Added a `fetch` function export to the "http" module: * Fully compliant with the fetch [spec](https://fetch.spec.whatwg.org/); * Integrates with Traces, tracking requests, responses, errors and failures; **Updated http client** Refactored `httpClient` exported by "http" to use the custom *fetch* internally instead of *ky* hooks. **v0.2.0** 2026-04-22 - minor release See the [v0.1.12 - v0.2.0 migration guide](/migrations/v0.1.12-to-v0.2.0). ### `@outputai/cli` Fix `workflow generate` success message to show actual workflow ID and scenario name Add `credentials set` command for programmatic credential updates by dot-notation path. Prompts for confirmation when the write would change a value's shape (primitive → object or object → primitive); pass `--yes` to skip in non-interactive environments. Add interactive workflow run panel to `output dev` with live status polling, keyboard navigation, and Temporal UI integration Update plugin command invocations to match renamed `output-plan-workflow`, `output-build-workflow`, and `output-debug-workflow` skills. Add Docker Compose version check to prevent silent hangs on versions older than v2.24.0 Add `output migrate` command for upgrading projects between versions of the Output framework. The command reads the project's current `@outputai/*` version, fetches the matching migration guide from `docs.output.ai/migrations`, applies the steps, bumps dependencies, and runs the project's type checker. If the user is jumping multiple boundaries, it chains the guides covering the full range. Under the hood the CLI invokes `/output-migrate` — a Claude Code skill shipped via the `outputai` plugin marketplace. The skill carries the migration logic but no version-specific content; it fetches every guide at runtime so the docs remain the source of truth. Upgrading Docker Node image version from 24.13.0-slim to 24.15.0-slim Update the Claude plugin for Output to improve workflow code generation" Auto-forward OUTPUT_CATALOG_ID as default task queue for workflow run/start commands ### `output-api` * Fixed `/run` endpoint response to have the same format as `/result`; * Fixed `/status` endpoints `status` field format; Add pinned-run routes and deprecate mutation shortcuts. New routes: `GET /workflow/:id/runs/:rid/{status,result,trace-log}` and `PATCH/POST /workflow/:id/runs/:rid/{stop,terminate,reset}` allow targeting a specific Temporal run by ID. The following routes are deprecated (sunset 2026-07-16) and should be migrated to their pinned equivalents: * `PATCH /workflow/:id/stop` → `PATCH /workflow/:id/runs/:rid/stop` * `POST /workflow/:id/terminate` → `POST /workflow/:id/runs/:rid/terminate` * `POST /workflow/:id/reset` → `POST /workflow/:id/runs/:rid/reset` Deprecated routes emit `Deprecation`, `Sunset`, and `Link` response headers on every call. **Additive response-shape changes (backwards-compatible):** * `POST /workflow/run` now includes `runId` in the response * `POST /workflow/start` now includes `runId` in the response * `PATCH /workflow/:id/stop` now returns `{ workflowId, runId }` (previously no response body) * `POST /workflow/:id/terminate` response now includes `runId` * All status, result, and trace-log responses now include `runId` ### `@outputai/evals` Switch dataset files to multi-case format where each top-level YAML key is the case name. Allows grouping multiple test cases into a single file instead of one file per case. The old single-case format (with a top-level `name:` field) is no longer supported — existing files must be migrated to the new format. Treated as minor rather than major because adoption is still early and the migration is mechanical. ### `@outputai/cli`, `@outputai/core`, `@outputai/credentials`, `@outputai/evals`, `@outputai/http`, `@outputai/llm`, `@outputai/output`, `output-api` Updating dependencies: * @oclif/plugin-help * dotenv * json-schema-library * react * redis * undici * @noble/ciphers * @ai-sdk/amazon-bedrock * @ai-sdk/anthropic * @ai-sdk/azure * @ai-sdk/google-vertex * @ai-sdk/openai * @ai-sdk/perplexity * ai * liquidjs Adding version overrides to fix vulnerabilities: * vite@>=7.1.0 \<=7.3.1: `>=7.3.2` * hono@\<4.12.12: `>=4.12.12` * hono@>=4.0.0 \<=4.12.11: `>=4.12.12` * @hono/node-server@\<1.19.13: `>=1.19.13` * follow-redirects@\<=1.15.11: `>=1.16.0` * hono@\<4.12.14: `>=4.12.14` * axios@>=1.0.0 \<1.15.0: `>=1.15.0` * protobufjs@\<7.5.5: `>=7.5.5` ### `@outputai/cli`, `@outputai/core`, `@outputai/llm` Bumping dependency versions **v0.1.12** 2026-04-07 - patch release ### `@outputai/core`, `@outputai/llm` Add `agent()` and `skill()` abstractions to `@outputai/llm` for composing reusable LLM agents with structured output and a lazy-loaded skills system. Add `findContentDir()` to `@outputai/core` and fix skill path resolution to be relative to the prompt file rather than the calling module. Add `output-copy-assets` bin to `@outputai/core` to centralise worker asset copying. ### `@outputai/core`, `output-api` Add support for workflow alias names. ### `@outputai/cli` Add `output fix` command that realigns npm scripts in a host project's `package.json` with the canonical scripts from the CLI. Added `output:worker` and `output:worker:watch` commands to the scaffold. Pinned the dependency versions installed via the CLI-generated `package.json`. Pin `output` to a specific version in the scaffold `package.json` instead of a version range. Update CLI cost configuration for calculating cost of Claude Sonnet 4.6. Improve coding-assistant guidance for schema generation. **v0.1.11** 2026-04-02 - patch release ### `@outputai/cli` Fix worker health checks and add yarn/pnpm support in the dev container. Dev container worker now supports yarn and pnpm projects via corepack. Health check no longer reports success when containers exit or are unhealthy. Worker health-check detection time dropped from \~36s to \~9s. `start_period` extended from 30s to 60s to reduce false positives on cold start. Fix the `plan` and `generate` CLI commands. Suppressed Claude file writes and next-step suggestions during plan generation (the CLI owns those responsibilities). Validates plan-file existence before creating a workflow skeleton in `generate`. Rolls back created skeleton files if the workflow build step fails. Replace log-update / ANSI output in `output dev` with an Ink-based terminal UI, fixing a layout bug where text overlapped after a Docker service recovered from unhealthy. Ensure credential references are resolved when running CLI commands. **v0.1.10** 2026-03-27 - patch release ### All packages Update dependencies to latest and override versions to fix known vulnerabilities. **v0.1.9** 2026-03-27 - patch release ### `@outputai/cli` Fix best practices in the `output init` example. Move `blogContentSchema` from `steps.ts` to `types.ts`. Update the README template to use `npx output credentials` flow instead of `.env`. **v0.1.8** 2026-03-24 - patch release ### `@outputai/cli` Use encrypted credentials in the `output init` scaffold by default. API keys are now stored in `config/credentials.yml.enc` instead of `.env`, and `` markers are renamed to ``. ### `@outputai/llm` Update `@exalabs/ai-sdk` from 1.0.5 to 2.0.1. **v0.1.7** 2026-03-24 - patch release ### All packages Dependency bumps (minor and patch). **v0.1.6** 2026-03-23 - patch release ### `@outputai/cli` Fix null crash in `workflow cost` when the pricing config is empty or missing. **v0.1.5** 2026-03-22 - patch release ### `@outputai/cli` Fix prod publish to include the build step before publishing to npm. Previously, packages were published without compiling TypeScript, resulting in a missing `dist/` directory. Add `@next` dist-tag that auto-publishes from every merge to `main`, enabling `npx @outputai/cli@next` for tracking the latest changes. **v0.1.4** 2026-03-20 - patch release ### All packages Patch vulnerable dependencies. **v0.1.3** 2026-03-19 - patch release ### `@outputai/cli`, `@outputai/core`, `@outputai/credentials` Add `credential:` env var convention for automatic secret resolution at worker startup. * `@outputai/core`: add `WORKER_BEFORE_START` lifecycle event and `onBeforeStart` hook. * `@outputai/credentials`: add `resolveCredentialRefs()` that resolves `credential:` env vars from encrypted credentials, auto-registered via `onBeforeStart` on import. * `@outputai/cli`: scaffold build script now copies `*.key` files to `dist/` alongside `*.yml.enc`. **v0.1.2** 2026-03-19 - patch release ### `@outputai/cli` Update `@anthropic-ai/claude-agent-sdk` from 0.1.71 to 0.2.77. **v0.1.1** 2026-03-19 - patch release ### All packages Dependency updates (minor and patch). # Connecting to External APIs Source: https://docs.output.ai/clients/index Build typed, observable API clients for reliable third-party integrations AI workflows talk to external APIs constantly — search engines, content services, data providers, internal tools. You could install a dedicated SDK for each one, but that adds maintenance overhead. Writing raw `fetch` calls works, but you lose visibility into what's happening across your workflow, and it becomes tedious to maintain. Output ships `createKyClient` from `@outputai/core/http` as the standard way to write Ky API clients. Every request is automatically traced, so you see exactly what your workflow called in the same trace as the step that called it, what came back, and how long it took. You (or Claude Code) write thin, typed wrappers — one file per API — that your steps import. ## Your First Client Here's a simple client that searches the web using [Tavily](https://tavily.com). Create a file at `src/clients/tavily.ts`: ```typescript src/clients/tavily.ts theme={null} import { createKyClient } from '@outputai/core/http'; import { FatalError } from '@outputai/core'; const getApiKey = () => { const key = process.env.TAVILY_API_KEY; if (!key) { throw new FatalError('TAVILY_API_KEY environment variable is required'); } return key; }; const createClient = () => createKyClient({ prefix: 'https://api.tavily.com', timeout: 60000, }); export const tavilyClient = { search: async (query: string): Promise<{ title: string; url: string; content: string }[]> => { const client = createClient(); const data = await client .post('search', { json: { api_key: getApiKey(), query, max_results: 5 }, headers: { 'Content-Type': 'application/json' }, }) .json<{ results: Array<{ title: string; url: string; content: string }> }>(); return data.results; }, }; ``` That's a complete, working client. Let's break down what's happening: **`createClient()`** builds an HTTP client with a base URL and timeout. Every request through this client is automatically traced — you'll see the URL, status code, and timing in your workflow trace. The `prefix` means you only write relative paths like `'search'` instead of the full URL. **`getApiKey()`** reads the API key from an environment variable. It throws a `FatalError` if the key is missing — this tells Output "don't retry this step, it will never succeed without the key." More on this in [Error Handling](#error-handling). **The exported object** (`tavilyClient`) exposes typed methods that your steps call. Steps never see HTTP details — they call `tavilyClient.search('AI frameworks')` and get back an array of results. Use it from a step like this: ```typescript steps.ts theme={null} import { step, z } from '@outputai/core'; import { tavilyClient } from '../../clients/tavily.js'; export const searchWeb = step({ name: 'searchWeb', inputSchema: z.object({ query: z.string() }), outputSchema: z.array(z.object({ title: z.string(), url: z.string(), content: z.string(), })), fn: async (input) => { return tavilyClient.search(input.query); }, }); ``` ## Authentication Patterns Different APIs authenticate differently. The client above passes the API key in the request body, but most APIs use headers. Here are the common patterns. ### Bearer Token The most common pattern — pass a token in the `Authorization` header. Many internal APIs and services like OpenAI, Perplexity, and HubSpot use this: ```typescript src/clients/hubspot.ts theme={null} const createClient = () => createKyClient({ prefix: 'https://api.hubapi.com', timeout: 30000, headers: { Authorization: `Bearer ${process.env.HUBSPOT_API_KEY}`, 'Content-Type': 'application/json', }, }); ``` ### API Key in Headers Some APIs use a custom header name like `x-api-key` instead of the standard `Authorization` header: ```typescript src/clients/exa.ts theme={null} const createClient = () => createKyClient({ prefix: 'https://api.exa.ai', timeout: 60000, }); // Then pass the key per-request const response = await client.post('search', { json: { query }, headers: { 'x-api-key': process.env.EXA_API_KEY, 'Content-Type': 'application/json', }, }); ``` You can set this in `createClient()` instead if every request uses the same key. Per-request headers are useful when you want the base client to be reusable. ### Basic Auth Older APIs sometimes use HTTP Basic authentication, which encodes a username and password as a Base64 string. `Buffer.from()` is Node.js's built-in way to do this encoding: ```typescript src/clients/image_service.ts theme={null} const createClient = () => { const userId = process.env.SERVICE_USER_ID; const apiKey = process.env.SERVICE_API_KEY; return createKyClient({ prefix: 'https://api.example.com/v1', timeout: 120000, headers: { Authorization: `Basic ${Buffer.from(`${userId}:${apiKey}`).toString('base64')}`, }, }); }; ``` ## Validating Responses with Zod API responses can change without warning — a field gets renamed, a type changes, a new required field appears. If you pass unvalidated data through your workflow, these changes cause confusing errors far from the source. Zod schemas catch this at the boundary. Define what the API should return, and parse the response immediately: ```typescript src/clients/clearbit.ts theme={null} import { createKyClient } from '@outputai/core/http'; import { z } from '@outputai/core'; const createClient = () => createKyClient({ prefix: 'https://company.clearbit.com/v2', timeout: 30000, headers: { Authorization: `Bearer ${process.env.CLEARBIT_API_KEY}`, }, }); const CompanySchema = z.object({ name: z.string(), domain: z.string(), description: z.string().nullable(), category: z.object({ industry: z.string().nullable(), sector: z.string().nullable(), }), metrics: z.object({ employees: z.number().nullable(), estimatedAnnualRevenue: z.string().nullable(), }), }); export type Company = z.infer; export const clearbitClient = { lookupCompany: async (domain: string): Promise => { const client = createClient(); try { const data = await client .get(`companies/find`, { searchParams: { domain } }) .json(); return CompanySchema.parse(data); } catch { return null; } }, }; ``` If Clearbit changes `estimatedAnnualRevenue` from a string to a number, `CompanySchema.parse()` throws immediately with a clear message like `Expected string, received number at "metrics.estimatedAnnualRevenue"`. You'll know exactly what broke and where. The `z.infer` line generates a TypeScript type from the schema, so you get autocomplete and type checking throughout your workflow without writing the type separately. ## Error Handling When an API call fails, you need to decide: should Output retry the step, or is the error permanent? Ky clients throw two common error types: * **`ky.HTTPError`** — The server responded with a non-2xx status code (like 404, 429, or 500) * **`ky.TimeoutError`** — The request took longer than the timeout you set By default, Output retries failed steps automatically. This is great for transient errors (server hiccups, network blips), but you don't want to retry when the API key is missing or the resource doesn't exist. Here's how to handle the common cases: ```typescript src/clients/search.ts theme={null} import { createKyClient, ky } from '@outputai/core/http'; import { FatalError } from '@outputai/core'; const getApiKey = () => { const key = process.env.SEARCH_API_KEY; if (!key) { // FatalError tells Output: "stop retrying, this will never work" throw new FatalError('SEARCH_API_KEY environment variable is required'); } return key; }; export const searchClient = { query: async (q: string): Promise => { const client = createClient(); try { const response = await client .get('search', { searchParams: { q, api_key: getApiKey() } }) .json(); return response.results ?? []; } catch (error) { if (error instanceof ky.HTTPError) { // 429: Rate limited. Let the step retry with backoff. if (error.response.status === 429) throw error; // 404: Not found. Return empty results instead of failing. if (error.response.status === 404) return []; } // Everything else (5xx, ky.TimeoutError): let it propagate. // Output will retry the step automatically. throw error; } }, }; ``` The key insight: **throw errors you want retried, return gracefully for expected failures, and use `FatalError` for configuration problems.** Output's retry policy handles the rest — you set the retry count and backoff in your [step options](/steps#options) or [workflow options](/workflows#activity-options). ## Adding More Methods As you integrate deeper with an API, you'll need more than one method. Group related operations in a single client object. Here's what a multi-method client looks like: ```typescript src/clients/web_search.ts theme={null} export const webSearchClient = { search: async (query: string, maxResults = 10): Promise => { const client = createClient(); return client .post('search', { json: { api_key: getApiKey(), query, max_results: maxResults } }) .json(); }, extract: async (urls: string[]): Promise => { const client = createClient(); return client .post('extract', { json: { api_key: getApiKey(), urls } }) .json(); }, crawl: async (url: string, maxDepth = 1): Promise => { const client = createClient(); return client .post('crawl', { json: { api_key: getApiKey(), url, max_depth: maxDepth } }) .json(); }, }; ``` Each method creates a fresh client instance, keeping things stateless. Your steps call whichever method they need — `webSearchClient.search(...)`, `webSearchClient.extract(...)` — without knowing the HTTP details. ## Async Task Polling Some APIs don't return results immediately. Instead, they give you a task ID and you poll until the work is done. Research APIs and batch processing services commonly work this way: ```typescript src/clients/research.ts theme={null} import { createKyClient } from '@outputai/core/http'; import { FatalError } from '@outputai/core'; // Clients run inside steps (activities), not workflows. // Use setTimeout-based sleep here — Output's sleep() is only for workflow code. const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); export const researchClient = { run: async (instructions: string): Promise => { const client = createClient(); const headers = { 'x-api-key': getApiKey(), 'Content-Type': 'application/json' }; // Start the task const { taskId } = await client .post('research/v1', { json: { instructions }, headers }) .json<{ taskId: string }>(); // Poll every 2 seconds until it's done for (let i = 0; i < 600; i++) { await sleep(2000); const task = await client .get(`research/v1/${taskId}`, { headers }) .json<{ status: string; output?: ResearchResult; error?: string }>(); if (task.status === 'completed') return task.output!; if (task.status === 'failed') throw new Error(`Research failed: ${task.error}`); } throw new Error('Research timed out after 20 minutes'); }, }; ``` > [!WARNING] > > When using polling, set the step's `startToCloseTimeout` high enough to cover the maximum polling duration. If the API might take 20 minutes, your step timeout needs to be longer than that. See [step options](/steps#options) for timeout configuration. ## Project Organization Put clients in `src/clients/`, one file per external API: ``` src/ ├── clients/ │ ├── clearbit.ts # Company data API │ ├── hubspot.ts # CRM API │ └── tavily.ts # Web search API └── workflows/ └── lead_enrichment/ ├── workflow.ts └── steps.ts # Imports from ../../clients/ ``` Steps import from client files — they never create `createKyClient` instances directly. When an API changes its auth or base URL, you update one file and every workflow that uses it picks up the change. ## Debugging When an API call isn't returning what you expect, turn on verbose logging to see the full request and response bodies in your traces: ```bash theme={null} OUTPUT_TRACE_HTTP_VERBOSE=1 output dev ``` This captures everything flowing through `outputFetch` and `createKyClient` — request bodies, response bodies, headers, and timing. Sensitive headers like `authorization` and `api-key` are automatically redacted so you can safely share traces. Turn this off in production. Response bodies from search APIs and content services can be large, and you don't want that in every trace. ## Complete Example: Tavily Client Here's the full Tavily client with search, extract, and crawl methods. This is a production-ready example you can copy and adapt — it demonstrates environment variable validation, typed interfaces, multiple methods, and transforming the API's `snake_case` responses into `camelCase` for your TypeScript code: ```typescript src/clients/tavily.ts theme={null} import { createKyClient } from '@outputai/core/http'; import { FatalError } from '@outputai/core'; const TAVILY_API_URL = 'https://api.tavily.com'; const getApiKey = () => { const key = process.env.TAVILY_API_KEY; if (!key) { throw new FatalError('TAVILY_API_KEY environment variable is required'); } return key; }; const createClient = () => createKyClient({ prefix: TAVILY_API_URL, timeout: 60000, }); // --- Types --- export interface TavilySearchParams { query: string; maxResults?: number; searchDepth?: 'basic' | 'advanced'; includeAnswer?: boolean; includeRawContent?: boolean; topic?: 'general' | 'news'; includeDomains?: string[]; excludeDomains?: string[]; } export interface TavilySearchResult { title: string; url: string; content: string; rawContent?: string; score: number; publishedDate?: string; } export interface TavilySearchResponse { query: string; answer?: string; results: TavilySearchResult[]; } export interface TavilyExtractResult { url: string; rawContent: string; } export interface TavilyExtractResponse { results: TavilyExtractResult[]; failedResults?: Array<{ url: string; error: string }>; } export interface TavilyCrawlResult { url: string; rawContent: string; } export interface TavilyCrawlResponse { baseUrl: string; results: TavilyCrawlResult[]; } // --- Client --- export const tavilyClient = { search: async (params: TavilySearchParams): Promise => { const client = createClient(); const data = await client .post('search', { json: { api_key: getApiKey(), query: params.query, max_results: params.maxResults ?? 10, search_depth: params.searchDepth ?? 'basic', include_answer: params.includeAnswer ?? true, include_raw_content: params.includeRawContent ?? false, topic: params.topic ?? 'general', ...(params.includeDomains && { include_domains: params.includeDomains }), ...(params.excludeDomains && { exclude_domains: params.excludeDomains }), }, headers: { 'Content-Type': 'application/json' }, }) .json<{ query: string; answer?: string; results: Array<{ title: string; url: string; content: string; raw_content?: string; score: number; published_date?: string; }>; }>(); return { query: data.query, answer: data.answer, results: data.results.map((r) => ({ title: r.title, url: r.url, content: r.content, rawContent: r.raw_content, score: r.score, publishedDate: r.published_date, })), }; }, extract: async (urls: string[]): Promise => { const client = createClient(); const data = await client .post('extract', { json: { api_key: getApiKey(), urls, extract_depth: 'basic', format: 'markdown', }, headers: { 'Content-Type': 'application/json' }, }) .json<{ results: Array<{ url: string; raw_content: string }>; failed_results?: Array<{ url: string; error: string }>; }>(); return { results: data.results.map((r) => ({ url: r.url, rawContent: r.raw_content })), failedResults: data.failed_results, }; }, crawl: async (url: string, options?: { maxDepth?: number; limit?: number }): Promise => { const client = createClient(); const data = await client .post('crawl', { json: { api_key: getApiKey(), url, max_depth: options?.maxDepth ?? 1, limit: options?.limit ?? 50, format: 'markdown', }, headers: { 'Content-Type': 'application/json' }, }) .json<{ base_url: string; results: Array<{ url: string; raw_content: string }>; }>(); return { baseUrl: data.base_url, results: data.results.map((r) => ({ url: r.url, rawContent: r.raw_content })), }; }, }; ``` ## What's Next * [@outputai/core/http API reference](/packages/core/http) — `outputFetch`, `createKyClient`, and configuration options * [Steps](/steps) — Where clients get used: wrapping API calls in retryable steps * [Tracing](/operations/tracing) — How request traces appear in the Temporal UI * [Error Handling](/operations/error-handling) — `FatalError`, `ValidationError`, and retry policies # Overview Source: https://docs.output.ai/cookbook/overview Recipes, best practices and integrations for building with Output. A curated collection of workflow patterns with clean, copy-paste code examples for real use cases. ## Integrations * **[Zapier SDK](/cookbook/zapier-sdk)** — Post an LLM-drafted message to Slack through a user's Zapier connection. # Zapier SDK Source: https://docs.output.ai/cookbook/zapier-sdk Call Zapier-managed app connections from inside Output steps — no OAuth plumbing, full traces, automatic retries. Output workflows can invoke any app a user has authorized in their Zapier account without writing OAuth or refresh-token code. The Zapier SDK resolves the user's existing connection and exposes typed actions; Output wraps each call in a `step()` so it's traced, retried, and safe to replay. ## What it enables * Access hundreds of third-party apps (Slack, Gmail, Airtable, HubSpot, …) through a single SDK. * Zero OAuth code — Zapier injects tokens from the user's stored connection. * Two ways to execute actions: a unified `runAction()` entry point, or dot notation to access app-specific methods. * Machine credentials that run from a headless worker, not a browser. ## When to use * You need to send, read, or update data in an app a user has already authorized in Zapier. * You want to skip managing OAuth tokens and refresh flows yourself. * Your workflow should tolerate transient 5xxs and retry without double-posting. * You need the Zapier call traced alongside LLM and other steps in the same Output execution. ## Install & authenticate Visit [https://zapier.com/app/assets/connections](https://zapier.com/app/assets/connections) and create connections to the apps you want to use. ![Zapier App Connections page listing authorized Slack workspaces](https://mintcdn.com/growthx/r36hRux8GCNtd-u8/cookbook/assets/zapier-app-connections.png?fit=max\&auto=format\&n=r36hRux8GCNtd-u8\&q=85\&s=a68e8383f6e8d19da2e57029228bbe05) Then install the Zapier SDK: ```bash theme={null} npm install @zapier/zapier-sdk npm install -D @zapier/zapier-sdk-cli @types/node typescript ``` Your `package.json` must set `"type": "module"` — both SDKs are ESM. Authenticate once locally and register the apps you want to call: ```bash theme={null} npx zapier-sdk login # one-time browser OAuth npx zapier-sdk add slack # writes .zapier-manifest.json ``` Adding an app installs a typed system, so you can access it through dot notation with typed return values. ## Machine credentials for the worker The Output worker runs in Docker with no browser. Create machine credentials and store them in Output's encrypted credential store: ```bash theme={null} npx zapier-sdk create-client-credentials output-ai npx output credentials edit ``` ```credentials.key theme={null} zapier: client_id: zap_cc_xxxxxxxx client_secret: zap_cs_xxxxxxxx ``` You also need to update your `.env`: ```.env theme={null} # Zapier credentials ZAPIER_CLIENT_ID=credential:zapier.client_id ZAPIER_CLIENT_SECRET=credential:zapier.client_secret ``` ## Shared Zapier client Put the configured SDK in its own file under `src/clients/` so every step imports the same instance — matching the API client pattern used elsewhere in Output (e.g. `src/clients/jina.ts`): ```ts src/clients/zapier.ts theme={null} import { credentials } from '@outputai/core/credentials'; import { createZapierSdk } from '@zapier/zapier-sdk'; const clientId = credentials.require('zapier.client_id') as string; const clientSecret = credentials.require('zapier.client_secret') as string; export const zapier = createZapierSdk({ credentials: { clientId, clientSecret }, }); ``` ## Schemas Define every step and workflow boundary in `types.ts` so the same shapes are reused across files instead of being inlined into each `z.object(...)`: ```ts types.ts theme={null} import { z } from '@outputai/core'; export const WorkflowInputSchema = z.object({ topic: z.string(), channel: z.string(), }); export const WorkflowOutputSchema = z.object({ message: z.string(), channel: z.string(), ts: z.string(), }); export const PostToSlackInput = z.object({ channel: z.string(), message: z.string(), }); export const DraftAnnouncementInput = z.object({ topic: z.string(), }); export const DraftAnnouncementOutput = z.object({ message: z.string(), }); export type WorkflowInput = z.infer; export type WorkflowOutput = z.infer; export type PostToSlackInput = z.infer; export type DraftAnnouncementInput = z.infer; export type DraftAnnouncementOutput = z.infer; ``` ## Calling a Zapier action from a step Each authorized app shows up on the **App Connections** page in Zapier — that's what `findFirstConnection` queries under the hood: Put every Zapier call inside a `step()` so it's traced and retried. Resolve the user's connection, then invoke the action through the typed dot-notation API: ```ts steps.ts theme={null} import { step, FatalError } from '@outputai/core'; import { generateText } from '@outputai/core/llm'; import { zapier } from '../../clients/zapier.js'; import { DraftAnnouncementInput, DraftAnnouncementOutput, PostToSlackInput, WorkflowOutputSchema, } from './types.js'; export const postToSlackChannel = step( { name: 'post_to_slack_channel', description: 'Post message to Slack Channel', inputSchema: PostToSlackInput, outputSchema: WorkflowOutputSchema, fn: async ({ channel, message }) => { const { data: firstSlackConnection } = await zapier.findFirstConnection({ search: 'Slack Connection 2', // if you have more than one app it's better to provide the complete name appKey: 'slack', owner: 'me', isExpired: false, }); if (!firstSlackConnection) { throw new FatalError( 'No authorized Slack connection. Authorize Slack in Zapier, then retry.' ); } const slack = zapier.apps.slack({ connection: firstSlackConnection.id }); const { data } = await slack.write.direct_message({ inputs: { channel, text: message, as_bot: false } }); const [result] = data as Array<{ ts: string; channel: string }>; return { ts: result.ts, channel: result.channel, message: message }; }, }); export const draftAnnouncement = step({ name: 'draft_announcement', description: 'Draft a Slack announcement message for a given topic', inputSchema: DraftAnnouncementInput, outputSchema: DraftAnnouncementOutput, fn: async ({ topic }) => { const { text } = await generateText({ prompt: 'draft_announcement', variables: { topic }, }); return { message: text.trim() }; }, }); ``` Write the prompt to generate the message: ```draft_announcement.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-6 temperature: 0.7 --- You are a concise, friendly internal communications writer. You draft short Slack announcements (1–3 sentences) that are clear, warm, and skimmable. Use plain language, no buzzwords, and no hashtags. End with a single celebratory emoji when appropriate. Draft a Slack announcement for the team about the following topic: {{ topic }} Return only the message text — no preamble, no quotation marks. ``` A missing connection throws `FatalError` — retrying won't help until the user authorizes Slack in Zapier. Transient 5xxs from Slack or Zapier bubble up and Output's step retry policy handles them automatically. ### Other methods to call Zapier Actions You can also invoke the action using this syntax: ```ts theme={null} const { data } = await zapier.runAction( { appKey: 'slack', actionType: 'write', actionKey: 'send_channel_message', connectionId: firstSlackConnection.id, inputs: { channel, text: message }, } ); ``` Always destructure `{ data }` from the response — the Zapier SDK returns a wrapped envelope. > [!NOTE] > > For endpoints with no built-in action, fall back to `zapier.fetch()` — it injects the user's credentials and returns a standard `Response`: > > ```ts theme={null} > const response = await zapier.fetch('https://slack.com/api/users.list', { > method: 'GET', > connectionId: firstSlackConnection.id, > }); > const users = await response.json(); > ``` > > Direct API calls bypass your org's action restriction policies. See [Zapier's docs](https://docs.zapier.com/sdk/quickstart#step-8-make-custom-api-calls-with-fetch-optional). ## Orchestrating with a workflow Keep the workflow pure — it only sequences step calls. No SDK clients, no `fetch`, no `Date.now`: ```ts workflow.ts theme={null} import { workflow } from '@outputai/core'; import { draftAnnouncement, postToSlackChannel } from './steps.js'; import { WorkflowInputSchema, WorkflowOutputSchema } from './types.js'; export default workflow({ name: 'slack_broadcast', inputSchema: WorkflowInputSchema, outputSchema: WorkflowOutputSchema, fn: async ({ topic, channel }) => { const { message } = await draftAnnouncement({ topic }); const { ts } = await postToSlackChannel({ channel, message }); return { message, channel, ts }; }, }); ``` Define a scenario file so runs are reproducible and reviewable in PRs: ```json src/workflows/slack_broadcast/scenarios/happy_message.json theme={null} { "topic": "we shipped v1.2", "channel": "#test-zapier-sdk" } ``` Run the workflow against that scenario: ```bash theme={null} npx output workflow run slack_broadcast happy_message ``` The Output trace captures each step independently, including the full Zapier request and response inside `postToSlackChannel`. # Cost Events Source: https://docs.output.ai/costs/cost-events Monitor normalized LLM usage and cost plus HTTP request costs in real time The [cost estimation CLI](/costs) shows you costs after a workflow finishes. Metering and cost events expose similar data while a workflow runs: * **`llm:generation:metering`** - recommended for LLM integrations. It carries normalized usage and cost, including calls without available pricing. * **`cost:llm:request`** - the compatible legacy LLM cost event. Existing handlers can keep using it. * **`cost:http:request`** - emitted when you attach a dollar cost to an HTTP response with [`addRequestCost`](/packages/core/http#attaching-request-cost) from `@outputai/core/http`. Use them to log spend and usage to your observability stack, trigger alerts, or aggregate costs per workflow over time. ## Setup Cost events use the same [hooks system](/operations/error-hooks) as error hooks: 1. Create a hook file and import `on` from `@outputai/core/hooks`. 2. Register a handler for `llm:generation:metering`, `cost:llm:request`, `cost:http:request`, or a combination. 3. Add the file path to `outputai.hookFiles` in `package.json`. See [Error Hooks - Setup](/operations/error-hooks#setup) for the hook file registration pattern. ```typescript src/llm_metering_hooks.ts theme={null} import { on } from '@outputai/core/hooks'; import type { LLMGenerationMeteringEvent } from '@outputai/core/llm'; on( 'llm:generation:metering', async ( { eventId, eventDate, workflowDetails, activityInfo, payload } ) => { if (!workflowDetails || !activityInfo || !payload) { return; } console.log( 'LLM call', { eventId, eventDate, workflowId: workflowDetails.workflowId, activityId: activityInfo.activityId, providerId: payload.usage.providerId, modelId: payload.usage.modelId, promptName: payload.usage.promptName, durationMs: payload.usage.requestDetails?.duration, tokens: payload.usage.total, cost: payload.cost?.total } ); } ); ``` ```typescript src/http_cost_hooks.ts theme={null} import { on } from '@outputai/core/hooks'; import type { HttpRequestCostEvent } from '@outputai/core/http'; on( 'cost:http:request', async ( { eventId, eventDate, workflowDetails, activityInfo, payload } ) => { if (!workflowDetails || !activityInfo || !payload) { return; } console.log( 'HTTP request', { eventId, eventDate, workflowId: workflowDetails.workflowId, activityId: activityInfo.activityId, requestId: payload.requestId, url: payload.url, total: payload.total } ); } ); ``` Handler errors are caught and logged by the framework - they never affect the workflow or the request that triggered them. ## LLM generation metering ### When events fire `llm:generation:metering` is emitted after a generation ends for text, image, and Agent calls whenever usage is available. For direct `streamText()` and `Agent.stream()` usage, it fires when the stream finishes, not when it starts. A failed generation also emits. Usage is collected as the call progresses, so a call that throws or is aborted after completing at least one step reports what it spent - an output that never validated, a tool loop that broke mid-run, an aborted stream, or a failure in your own code after the model answered. An event is therefore not proof of a successful call; a trace event carrying both usage and an error is a failure that still cost money. Failures before the first step completes report nothing, because no usage exists yet. One event is emitted per call. Activity retries emit one per attempt, since each attempt calls the provider. ### Payload The handler receives the standard event envelope. `payload.usage` is always present, and unpriced models produce an incomplete `payload.cost`: ```json theme={null} { "eventId": "550e8400-e29b-41d4-a716-446655440000", "eventDate": 1780401600000, "activityInfo": { "activityId": "activity-1", "activityType": "generateSummary" }, "workflowDetails": { "workflowId": "workflow-123", "runId": "run-123", "workflowType": "lead_enrichment" }, "outputActivityKind": "step", "payload": { "usage": { "type": "llm:generation:usage", "providerId": "openai", "modelId": "gpt-4o", "promptName": "summarize@v1", "requestDetails": { "ids": ["req_8e1cf3899f254171855c866214eb5620"], "count": 1, "duration": 1240 }, "status": "complete", "input": 217, "output": 9, "total": 226, "items": [ { "group": "input", "label": "no_cache", "amount": 217 }, { "group": "output", "label": "text", "amount": 9 } ] }, "cost": { "type": "llm:generation:cost", "providerId": "openai", "modelId": "gpt-4o", "promptName": "summarize@v1", "requestDetails": { "ids": ["req_8e1cf3899f254171855c866214eb5620"], "count": 1, "duration": 1240 }, "status": "precise", "pricingFreshness": "cached", "input": 0.001085, "output": 0.000135, "tools": null, "total": 0.00122, "items": [ { "group": "input", "label": "no_cache", "amount": 217, "ppm": 5, "total": 0.001085, "status": "ok" }, { "group": "output", "label": "text", "amount": 9, "ppm": 15, "total": 0.000135, "status": "ok" } ] } } } ``` | Field | Type | Description | | - | - | - | | `eventId` | `string` | UUID v4 stamped per emit. Use it as an idempotency key. | | `eventDate` | `number` | Millisecond epoch timestamp for when the event was emitted. | | `activityInfo` | `object \| undefined` | Temporal [`activity.Info`](https://typescript.temporal.io/api/interfaces/activity.Info) when the call is made in an activity context. | | `workflowDetails` | `object \| undefined` | Output's serializable subset of Temporal [`workflow.WorkflowInfo`](https://typescript.temporal.io/api/interfaces/workflow.WorkflowInfo), when available. | | `outputActivityKind` | `string \| undefined` | Output activity kind when available. Possible values are `step`, `evaluator`, and `internal_step`. | | `payload.usage` | `LLMGenerationUsage` | Normalized provider-reported usage. | | `payload.cost` | `LLMGenerationCost \| null` | Cost calculated from that usage. A model or provider missing from the rate table gives an incomplete cost. | ### Normalized usage `LLMGenerationUsage` records usage independently from pricing. Aggregate `input`, `output`, and `total` fields make common reads direct; `items` preserve the provider breakdown. | Field | Type | Description | | - | - | - | | `type` | `"llm:generation:usage"` | Trace attribute type. | | `providerId` | `string` | Provider identifier from the loaded prompt. | | `modelId` | `string` | Model identifier from the loaded prompt. | | `promptName` | `string \| undefined` | Name of the prompt that made the call, such as `summarize@v1`. Use it to group usage by prompt. Always present on events; absent only on usage recorded in traces before this field existed. | | `requestDetails` | `LLMRequestDetails \| undefined` | Provider request IDs, request count and duration of the call. See [Request details](#request-details). Always present on events; absent only on usage recorded in traces before this field existed. | | `input` | `number \| null` | Total reported input usage. | | `output` | `number \| null` | Total reported output usage. | | `total` | `number \| null` | Sum of available input and output usage. | | `status` | `"complete" \| "incomplete"` | Whether both input and output usage were reported. | | `items` | `LLMGenerationUsageItem[]` | Detailed usage items. | | Field | Type | Description | | - | - | - | | `group` | `"input" \| "output" \| "tools"` | Aggregate category. `tools` covers per-request charges such as Google Search grounding and provider-native web search. | | `label` | `string \| null` | Input detail (`no_cache`, `cache_read`, `cache_write`), output detail (`text`, `reasoning`), tool detail (`grounding_query`, `grounding_prompt`, `grounding` when the rate is unknown, `web_search`, `web_search_preview`, or `web_search_unknown` when the OpenAI variant is ambiguous), or `null` for aggregate usage. | | `amount` | `number` | Count for this dimension: a token count for `input`/`output` items, and a query, grounded prompt, or web search count for `tools` items. | When the detailed counts do not reconcile with the aggregate count, Output keeps the aggregate input or output item instead of recording a misleading breakdown. Tool items are recorded independently from tokens and are excluded from the `input`, `output`, and `total` token aggregates above. ### Request details `payload.usage.requestDetails` and `payload.cost.requestDetails` hold the same values, so a consumer that reads only one of them can still correlate the call. | Field | Type | Description | | - | - | - | | `ids` | `string[]` | Provider request ID of every request that exposed one, in request order. A multi-step call keeps all of them. Output reads the `request-id` response header, then `x-request-id`. A provider that exposes neither, such as Google Vertex, gives an empty array, and no replacement ID is generated. | | `count` | `number` | Number of provider requests, one per step. It is greater than `ids.length` when some requests exposed no ID. | | `duration` | `number` | Milliseconds, rounded up, from the start of the call until billing starts. For a stream, that is until the stream ends. | The IDs match the ones in the provider's own logs and support tools. Requests that the AI SDK retries internally after a failure are not included, because only the attempt that succeeded returns a response. A call that throws before any step completes reports nothing, because no usage exists yet. ### Normalized cost `LLMGenerationCost` contains priced items for the normalized usage. Token rates come from the built-in pricing source and are cached for 24 hours; provider-specific tool rates are maintained locally. Each item total is `(amount / 1_000_000) * ppm`. When the token pricing source is unreachable, its rates come from the last cached copy or from a snapshot bundled with the package, and `pricingFreshness` records which. For models priced by context size, Output selects the tier separately for every provider request. The request's complete input count, including cache reads and writes, determines the tier; output does not count toward the threshold. A tier applies only when input is greater than its threshold, and its rates price the entire request. Multi-step calls can therefore contain multiple cost items with the same `group` and `label` but different `ppm` and `tier` values. When any step usage is incomplete, Output uses aggregate usage with base pricing and marks token items `uncertain`; this may understate the cost when an individual request crossed a higher-priced tier. | Field | Type | Description | | - | - | - | | `promptName`, `requestDetails` | `string`, `LLMRequestDetails` | Same values as on the usage, with the same absence on older traces. | | `input`, `output`, `tools`, `total` | `number \| null` | Aggregate dollar costs for available priced items. `tools` holds charges such as grounding and provider-native web search, and `total` is the sum of `input`, `output`, and `tools`. | | `status` | `"precise" \| "imprecise" \| "incomplete"` | Whether all rates were exact, a fallback or uncertain rate was used or the rates came from the bundled snapshot, or usage/pricing was incomplete. A tool charge with no known rate lands `incomplete`. | | `pricingFreshness` | `"live" \| "cached" \| "stale" \| "snapshot"` | How current the rate table was: fetched during this call, served from the 24-hour cache, kept past its TTL because a refresh failed, or read from the point-in-time snapshot bundled with the package. Only `snapshot` downgrades `status` to `imprecise`. | | `items[].ppm` | `number \| null` | Applied price per million units, such as tokens, requests, prompts, or queries. | | `items[].total` | `number \| null` | Calculated item cost. | | `items[].status` | `"ok" \| "fallback" \| "uncertain" \| "missing"` | Whether the exact rate was used, a cache rate fell back to the input rate, the context tier is uncertain, or no rate was available. Reasoning without a listed rate uses the output rate and is `ok`. | | `items[].tier` | `{ type: "context", size: number } \| undefined` | Context pricing tier applied to this item. Absent for base pricing and tool charges. | ## Legacy LLM request cost `cost:llm:request` is emitted on the same completion path when a legacy-priced payload can be calculated. The same payload is retained on the LLM trace as `attributes["llm:usage"]`. Both remain supported with the same payload shape, so existing event handlers and trace readers do not need to migrate immediately. Its `LLMUsageEvent` type is deprecated only to steer new integrations toward the normalized event and attributes. ```typescript src/legacy_llm_cost_hooks.ts theme={null} import { on } from '@outputai/core/hooks'; import type { LLMUsageEvent } from '@outputai/core/llm'; on( 'cost:llm:request', event => { if (!event.payload) { return; } console.log( event.payload.modelId, event.payload.total, event.payload.usage ); } ); ``` ```json theme={null} { "type": "llm:usage", "modelId": "gpt-4o", "usage": [ { "type": "input", "ppm": 5, "amount": 217, "total": 0.001085 }, { "type": "output", "ppm": 15, "amount": 9, "total": 0.000135 } ], "total": 0.00122, "tokensUsed": 226 } ``` The legacy payload represents priced usage through the historical `input`, `input_cached`, `output`, and `reasoning` line types only. It intentionally retains the old aggregate pricing, cache-write folding, and reasoning fallback behavior, and its shape is frozen: context tiers and per-request charges such as grounding and provider-native web search are not exposed. Tier and tool costs are only available on the normalized `llm:generation:cost` attribute and `llm:generation:metering` event described above. The `cost:llm:request` payload and `llm:usage` trace attribute are generated from the same object. Use `llm:generation:metering` for new integrations. It is more faithful to the provider response because usage is independent from pricing, cache writes and reasoning remain explicit, provider identity is included, and fallback or missing prices are represented rather than hidden. ## HTTP request cost Events fire only when your code calls [`addRequestCost( response, total )`](/packages/core/http#attaching-request-cost) with a response returned by `outputFetch` or `createKyClient`. The SDK attaches the cost to the existing HTTP trace event and emits `cost:http:request`. If the response did not originate from this package, `addRequestCost` no-ops (with a console warning) and **no** hook event is emitted. ### Payload The handler receives an event envelope. The HTTP request cost attribute is available under `payload`: ```json theme={null} { "eventId": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "eventDate": 1780401600000, "activityInfo": { "activityId": "activity-1", "activityType": "searchVendors" }, "workflowDetails": { "workflowId": "workflow-123", "runId": "run-123", "workflowType": "lead_enrichment" }, "outputActivityKind": "step", "payload": { "type": "http:request:cost", "requestId": "req-123", "url": "https://api.vendor.com/search", "total": 0.42 } } ``` | Field | Type | Description | | - | - | - | | `eventId` | `string` | UUID v4 stamped per emit. Use as an idempotency key — `cost:http:request` and `http:request` for the same fetch get distinct `eventId`s, so consumers keying by `eventId` won't collapse the two. | | `eventDate` | `number` | Millisecond epoch timestamp for when the event was emitted. | | `activityInfo` | `object \| undefined` | Temporal [`activity.Info`](https://typescript.temporal.io/api/interfaces/activity.Info) when the request is made in an activity context. | | `workflowDetails` | `object \| undefined` | Output's serializable subset of Temporal [`workflow.WorkflowInfo`](https://typescript.temporal.io/api/interfaces/workflow.WorkflowInfo), when available. | | `outputActivityKind` | `string \| undefined` | Output activity kind when available. Possible values are `step`, `evaluator`, and `internal_step`. | | `payload.type` | `"http:request:cost"` | Attribute type. | | `payload.requestId` | `string` | Internal id linking this payload to the HTTP trace event for that request. | | `payload.url` | `string` | Final response URL (same as `response.url`). | | `payload.total` | `number` | Dollar cost passed to `addRequestCost`. | # Cost Estimation Source: https://docs.output.ai/costs/index See what your workflows cost — LLM tokens, API calls, and external services — with a single CLI command Every LLM call and API request costs money. Output tracks costs automatically from your [trace files](/operations/tracing), so you can see exactly what a workflow run costs before it ever hits production. ## Quick start Make sure [tracing is enabled](/operations/tracing#enabling-tracing), run a workflow, then check what it cost: ```bash theme={null} # Run a workflow (produces a trace file) output workflow run lead_enrichment acme # Calculate cost from the latest trace output workflow cost lead_enrichment ``` That's it. The command reads recorded trace cost attributes, applies any configured pricing overrides, and prints a breakdown: ``` Trace: logs/runs/lead_enrichment/2026-03-01_lead_enrichment-abc123.json Workflow: lead_enrichment Duration: 12.4s LLM Costs: Model Calls Cost ────────────────────────────────────────── claude-sonnet-4 3 calls $0.0842 gpt-4o-mini 1 call $0.0012 ────────────────────────────────────────── Subtotal 4 calls $0.0854 API Costs: Service Calls Cost ────────────────────────────────────────── tavily 2 calls $0.02 jina 1 call $0.0001 ────────────────────────────────────────── Subtotal 3 calls $0.0201 ══════════════════════════════════════════════ TOTAL ESTIMATED COST $0.11 ══════════════════════════════════════════════ ``` Use `--verbose` for a per-call breakdown showing individual steps, token counts, and usage details: ```bash theme={null} output workflow cost lead_enrichment --verbose ``` You can also point at a specific trace file: ```bash theme={null} output workflow cost lead_enrichment logs/runs/lead_enrichment/2026-03-01_lead_enrichment-abc123.json ``` ## How it works The cost calculator walks the trace tree and extracts two kinds of billable events: 1. **LLM calls** - Prefers the recorded `llm:generation:cost` attribute for the original cost, including provider context-pricing tiers applied per request. It can reprice `llm:generation:usage` with `costs.yml`, and still reads the retained legacy `llm:usage` attribute for compatibility with old and new traces. 2. **HTTP calls** - Matches the request URL against known service patterns in the pricing config. Calculates cost from token usage, API units, per-request pricing, or a cost field in the response body, depending on the service type. Failed HTTP calls (status >= 400) are excluded - most APIs don't charge for errors. ## Pricing configuration Output ships with built-in pricing for common LLM models (Anthropic, OpenAI, Google, Perplexity) and API services (Jina, Tavily, Semrush, Exa, DataForSEO). For most workflows, this works out of the box. To add or override pricing, create `config/costs.yml` in your project root: ``` your-project/ ├── config/ │ └── costs.yml # Your overrides — merged on top of built-in pricing ├── src/ │ └── workflows/ └── .env ``` The CLI loads the built-in config first, then merges your file on top. You only need to include entries you want to add or change. ### Model pricing Each entry under `models` maps a model identifier to its per-million-token prices: ```yaml costs.yml theme={null} models: # Override pricing for a model claude-sonnet-4: provider: anthropic input: 3.00 # $ per 1M input tokens output: 15.00 # $ per 1M output tokens cached_input: 0.30 # $ per 1M cached input tokens # Add a model the CLI doesn't know about my-fine-tuned-model: provider: openai input: 6.00 output: 12.00 ``` | Field | Required | Description | | - | - | - | | `provider` | Yes | Provider name (informational) | | `input` | Yes | Price per 1M input tokens | | `output` | Yes | Price per 1M output tokens | | `cached_input` | No | Price per 1M cached input tokens | | `reasoning` | No | Price per 1M reasoning tokens. Falls back to `output` price if not set | Model names are matched by exact key first, then by prefix — `claude-sonnet-4` matches both `claude-sonnet-4` and `claude-sonnet-4-20250514`. ### Service pricing Each entry under `services` defines how to calculate cost for HTTP calls to a specific API. The `url_pattern` field matches against the request URL, and the `type` determines the calculation method. Four pricing types are supported: #### `token` — Price per million tokens For APIs that report token usage in their response (like Jina Reader): ```yaml costs.yml theme={null} services: jina: type: token url_pattern: "r.jina.ai" usage_path: "body.data.usage.tokens" per_million: 0.045 ``` For APIs with separate input/output token counts: ```yaml costs.yml theme={null} services: perplexity_api: type: token url_pattern: "api.perplexity.ai" usage_path: "body.usage" input_field: "prompt_tokens" output_field: "completion_tokens" input_per_million: 1.00 output_per_million: 1.00 ``` #### `unit` — Price per API unit For APIs that charge by units (like Semrush): ```yaml costs.yml theme={null} services: semrush: type: unit url_pattern: "api.semrush.com" price_per_unit: 0.00025 endpoints: backlinks_overview: pattern: "type=backlinks_overview" units_per_request: 10 domain_organic: pattern: "type=domain_organic" units_per_line: 10 ``` #### `request` — Fixed price per request For APIs with simple per-request pricing (like Tavily): ```yaml costs.yml theme={null} services: tavily: type: request url_pattern: "api.tavily.com" endpoints: search: pattern: "/search" price: 0.01 extract: pattern: "/extract" price_per_item: 0.005 items_path: "body.urls" ``` #### `response_cost` — Cost reported in response For APIs that return the actual cost in their response (like Exa): ```yaml costs.yml theme={null} services: exa: type: response_cost url_pattern: "api.exa.ai" cost_path: "output.body.costDollars.total" ``` ### Service config reference | Field | Used by | Description | | - | - | - | | `type` | All | Pricing type: `token`, `unit`, `request`, `response_cost` | | `url_pattern` | All | Substring matched against HTTP request URL | | `usage_path` | `token` | Dot-path to token count in response | | `per_million` | `token` | Price per 1M tokens (single count) | | `input_field` / `output_field` | `token` | Field names for separate input/output counts | | `input_per_million` / `output_per_million` | `token` | Prices for separate input/output tokens | | `price_per_unit` | `unit` | Price per API unit | | `endpoints` | `unit`, `request` | Endpoint-specific patterns and pricing | | `model_path` | `request` | Dot-path to model name in request | | `models` | `request` | Map of model names to per-request prices | | `default_price` | `request` | Fallback price when model not matched | | `cost_path` | `response_cost` | Dot-path to dollar cost in response | | `billable_method` | `response_cost` | HTTP method to count when no cost data present | | `fallback_models` | `response_cost` | Map of model names to fallback prices | | `default_fallback` | `response_cost` | Fallback price when no cost data and no model match | ## Unknown models When the calculator encounters a model that isn't in the pricing config, it reports the cost as \$0 and prints a warning: ``` Warning: Unknown models (add to config/costs.yml): my-custom-model ``` Add the model to your project's `config/costs.yml` to include it in future calculations. ## CLI reference See [`output workflow cost`](/packages/cli#output-workflow-cost) for the full command reference. # LLM-as-a-Judge Best Practices Source: https://docs.output.ai/evaluators/best-practices Write effective judge prompts, choose the right grading scale, and build reliable evaluators for production Building evaluators that work reliably in production takes more than wrapping an LLM call in an `evaluator()`. This guide covers how to design judge prompts, pick grading scales, avoid common pitfalls, and structure evaluators that give your workflows useful signal. ## Start with Failure Modes, Not Metrics The most common mistake is building evaluators before understanding what actually goes wrong. Don't start with "I need a quality score." Start by looking at 20-50 real outputs from your workflow and identifying specific failure patterns. For a lead enrichment summary, you might find: * The summary hallucinates details not in the source data * It's too generic — could describe any company * It misses the prospect's industry or key product * It's too long and buries the useful information Each of these is a concrete, testable failure mode. Build evaluators that check for *these specific things*, not abstract "quality." ```typescript evaluators.ts theme={null} import { evaluator, EvaluationBooleanResult } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; import { CheckHallucinationInput } from './types.js'; // Good: checks a specific failure mode export const checkForHallucinations = evaluator({ name: 'checkForHallucinations', description: 'Check if summary contains claims not supported by source data', inputSchema: CheckHallucinationInput, fn: async (input) => { const { output } = await generateText({ prompt: 'check_hallucination@v1', variables: { summary: input.summary, sourceData: input.sourceData }, output: aiSdk.Output.object({ schema: z.object({ unsupportedClaims: z.array(z.string()), hasHallucinations: z.boolean(), confidence: z.number() }) }) }); return new EvaluationBooleanResult({ value: !output.hasHallucinations, confidence: output.confidence, reasoning: output.unsupportedClaims.length > 0 ? `Unsupported claims: ${output.unsupportedClaims.join('; ')}` : 'All claims supported by source data' }); } }); // types.ts // import { z } from '@outputai/core'; // // export const CheckHallucinationInput = z.object({ // summary: z.string(), // sourceData: z.string() // }); ``` ## Prefer Pass/Fail Over Numeric Scales When an LLM rates something 6 out of 10, what does that mean? Is it good enough? Almost good? The number sounds precise but it's actually vague — the LLM isn't calibrated, and a 6 from one run might be a 7 from another. Binary pass/fail forces clarity. Either the summary mentions the company's industry or it doesn't. Either the email has a clear call-to-action or it doesn't. This makes your evaluators more consistent and your workflow logic simpler. ```typescript theme={null} // Vague — what do you do with a 6? if (quality.value >= 6) { /* good enough? */ } // Clear — either it passes or it doesn't if (quality.value === true) { /* move on */ } ``` When you do need more granularity, use three categories instead of a numeric scale: `pass`, `borderline`, `fail`. This gives you a middle ground without the false precision of 1-10 scores. ```typescript evaluators.ts theme={null} import { evaluator, EvaluationStringResult } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; import { JudgeSummaryInput } from './types.js'; export const judgeSummaryQuality = evaluator({ name: 'judgeSummaryQuality', description: 'Judge summary quality with a three-tier scale', inputSchema: JudgeSummaryInput, fn: async (input) => { const { output } = await generateText({ prompt: 'judge_summary@v1', variables: { summary: input.summary, companyName: input.companyName, sourceData: input.sourceData }, output: aiSdk.Output.object({ schema: z.object({ reasoning: z.string(), verdict: z.enum(['pass', 'borderline', 'fail']), confidence: z.number() }) }) }); return new EvaluationStringResult({ value: output.verdict, confidence: output.confidence, reasoning: output.reasoning }); } }); // types.ts // import { z } from '@outputai/core'; // // export const JudgeSummaryInput = z.object({ // summary: z.string(), // companyName: z.string(), // sourceData: z.string() // }); ``` ## Writing Judge Prompts The judge prompt is everything. A vague prompt produces vague evaluations. Here's how to write prompts that give consistent, useful results. ### Be Specific About Criteria Don't ask "is this good?" — define what "good" means for your use case. **Vague (unreliable):** ```yaml judge_summary@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 temperature: 0 --- You judge the quality of company summaries. Is this summary good? Summary: {{ summary }} ``` **Specific (reliable):** ```yaml judge_summary@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 temperature: 0 --- You evaluate company research summaries for a sales team. A good summary must: 1. Mention what the company does (their core product or service) 2. Identify their target market or customer base 3. Include at least one specific, verifiable fact (founding year, employee count, funding, etc.) 4. Be 2-4 paragraphs long 5. Not contain any claims that aren't supported by the provided source data When uncertain, err on the side of failing the summary. A sales rep using bad information is worse than asking for a rewrite. Evaluate this summary of {{ company_name }}. Summary: {{ summary }} Source data used to generate it: {{ source_data }} Does this summary pass all five criteria? ``` ### Ask for Reasoning Before the Verdict LLMs produce better judgments when they think through the evaluation before committing to a score. Structure your schema so the reasoning comes first. ```typescript theme={null} schema: z.object({ reasoning: z.string(), // Think first verdict: z.enum(['pass', 'fail']), // Then decide confidence: z.number() }) ``` In your judge prompt, you can reinforce this: ```yaml theme={null} ... Think through each criterion step by step, then give your verdict. ``` ### Use Temperature 0 Judge prompts should use `temperature: 0` for maximum consistency. You want the same input to produce the same evaluation every time. Save creativity for the generation step, not the judging step. ### Define Each Label If you're using categories like `pass`/`borderline`/`fail`, define exactly what each one means in the prompt: ```yaml theme={null} ... Scoring guide: - pass: The summary meets all five criteria with no issues - borderline: The summary meets most criteria but has minor gaps (e.g., missing one specific fact, slightly too short) - fail: The summary is missing key information, contains unsupported claims, or is clearly not useful for a sales call ``` ## One Evaluator, One Concern Don't build a single evaluator that judges accuracy, tone, length, and relevance all at once. Split them up. Each evaluator should check one specific thing. This matters for two reasons: 1. **Debugging** — When a summary fails, you know *why* it failed. "Failed hallucination check" is actionable. "Got a quality score of 4" is not. 2. **Flow control** — Different failures need different responses. A hallucinated summary should be regenerated. A summary that's too short might just need a different prompt variant. ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { lookupCompany, generateSummary } from './steps.js'; import { checkForHallucinations, checkCompleteness } from './evaluators.js'; import { EnrichmentInput, EnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', inputSchema: EnrichmentInput, outputSchema: EnrichmentOutput, fn: async (input) => { const company = await lookupCompany(input.companyDomain); let summary; let attempts = 0; while (attempts < 3) { summary = await generateSummary(company); const factCheck = await checkForHallucinations({ summary, sourceData: JSON.stringify(company) }); if (!factCheck.value) { // Hallucinated — must regenerate attempts++; continue; } const completeness = await checkCompleteness({ summary, companyName: company.name }); if (completeness.value) break; attempts++; } return { company: company.name, summary }; } }); // types.ts // import { z } from '@outputai/core'; // // export const EnrichmentInput = z.object({ // companyDomain: z.string() // }); // // export const EnrichmentOutput = z.object({ // company: z.string(), // summary: z.string() // }); ``` ## Layer Deterministic Checks Before LLM Judges LLM judges cost money and take time. Don't burn an LLM call on something you can check with code. Run cheap deterministic evaluators first, and only call the LLM judge if the basic checks pass. ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { generateSummary, lookupCompany } from './steps.js'; import { checkSummaryStructure } from './evaluators.js'; import { judgeSummaryQuality } from './evaluators.js'; import { EnrichmentInput, EnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', inputSchema: EnrichmentInput, outputSchema: EnrichmentOutput, fn: async (input) => { const company = await lookupCompany(input.companyDomain); let summary; let attempts = 0; while (attempts < 3) { summary = await generateSummary(company); // Cheap check first — no LLM call const structure = await checkSummaryStructure({ summary, companyName: company.name }); if (!structure.value) { attempts++; continue; } // Expensive check only if structure passes const quality = await judgeSummaryQuality({ summary, companyName: company.name, sourceData: JSON.stringify(company) }); if (quality.value === 'pass') break; attempts++; } return { company: company.name, summary }; } }); ``` ## Evaluators in Agent Loops The generate-evaluate-retry pattern is the foundation of agentic workflows. An agent that can check its own work and improve is fundamentally more reliable than one that generates a single output and hopes for the best. The pattern scales beyond simple retry loops. You can use evaluator results to: * **Switch strategies** — if a summary keeps failing the hallucination check, try a different prompt or a more conservative model * **Accumulate context** — pass the evaluator's reasoning back into the next generation as feedback * **Gate progression** — only move to the next stage of a pipeline when the current output meets quality thresholds ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { generateSummary, generateSummaryConservative, lookupCompany } from './steps.js'; import { judgeSummaryQuality } from './evaluators.js'; import { EnrichmentInput, EnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', inputSchema: EnrichmentInput, outputSchema: EnrichmentOutput, fn: async (input) => { const company = await lookupCompany(input.companyDomain); // First attempt with the standard prompt let summary = await generateSummary(company); let quality = await judgeSummaryQuality({ summary, companyName: company.name, sourceData: JSON.stringify(company) }); if (quality.value !== 'pass') { // Second attempt — feed the failure reasoning back in summary = await generateSummary({ ...company, previousAttemptFeedback: quality.reasoning }); quality = await judgeSummaryQuality({ summary, companyName: company.name, sourceData: JSON.stringify(company) }); } if (quality.value !== 'pass') { // Third attempt — switch to a conservative prompt summary = await generateSummaryConservative(company); } return { company: company.name, summary }; } }); ``` ## Weighted Rubric Evaluators Sometimes you need more nuance than a single pass/fail but want to avoid the inconsistency of asking an LLM for a numeric score. The solution: ask the LLM a series of specific yes/no questions, then compute a weighted score from the boolean answers yourself. This gives you the best of both worlds — the LLM makes simple binary decisions it's good at, and you control the scoring logic deterministically. ```typescript evaluators.ts theme={null} import { evaluator, EvaluationNumberResult } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; import { RubricInput } from './types.js'; const RUBRIC = [ { key: 'mentionsProduct', weight: 0.25, label: 'Mentions core product or service' }, { key: 'identifiesMarket', weight: 0.20, label: 'Identifies target market' }, { key: 'hasSpecificFacts', weight: 0.20, label: 'Includes verifiable facts' }, { key: 'noHallucinations', weight: 0.25, label: 'No unsupported claims' }, { key: 'appropriateLength', weight: 0.10, label: 'Appropriate length (2-4 paragraphs)' } ] as const; export const scoreSummaryRubric = evaluator({ name: 'scoreSummaryRubric', description: 'Score a summary using a weighted yes/no rubric', inputSchema: RubricInput, fn: async (input) => { const { output } = await generateText({ prompt: 'rubric_check@v1', variables: { summary: input.summary, companyName: input.companyName, sourceData: input.sourceData }, output: aiSdk.Output.object({ schema: z.object({ mentionsProduct: z.boolean(), identifiesMarket: z.boolean(), hasSpecificFacts: z.boolean(), noHallucinations: z.boolean(), appropriateLength: z.boolean() }) }) }); // Compute weighted score from boolean answers const score = RUBRIC.reduce((total, criterion) => { return total + (output[criterion.key] ? criterion.weight : 0); }, 0); const failed = RUBRIC .filter(c => !output[c.key]) .map(c => c.label); return new EvaluationNumberResult({ value: score, confidence: 1.0, reasoning: failed.length > 0 ? `Failed: ${failed.join(', ')}` : 'All criteria met' }); } }); // types.ts // import { z } from '@outputai/core'; // // export const RubricInput = z.object({ // summary: z.string(), // companyName: z.string(), // sourceData: z.string() // }); ``` The confidence is `1.0` because the scoring logic itself is deterministic — it's the LLM's yes/no answers that carry the uncertainty, and those are simple enough to be reliable. The weights and criteria live in your code, so you can tune them without touching the prompt. Use the score in your workflow to set thresholds: ```typescript theme={null} const rubric = await scoreSummaryRubric({ summary, companyName: company.name, sourceData: JSON.stringify(company) }); if (rubric.value >= 0.8) { // Good enough — move on } else if (rubric.value >= 0.5) { // Borderline — retry with feedback } else { // Too many failures — switch strategy } ``` This pattern scales well. You can add new criteria, rebalance weights, or change thresholds without rewriting the judge prompt. And because each criterion is a separate boolean, you get clear visibility into exactly what passed and what didn't. ## Common Pitfalls ### Using the Same Model to Generate and Judge If Claude generates a summary and Claude judges it, there's a self-enhancement bias — the model tends to rate its own output more favorably. When possible, use a different model for judging, or at minimum validate your judge against human-labeled examples. ### Trusting High Pass Rates If your evaluator passes 100% of outputs, it's not checking hard enough. A useful evaluator should catch real failures. If everything passes, either your generator is perfect (unlikely) or your judge criteria are too loose. ### Numeric Scales Without Clear Anchors If you must use numeric scores, anchor every point on the scale with a concrete example or definition. "7 out of 10" means nothing without context. "7 = meets all criteria but lacks specific financial data" is actionable. ### Evaluating Too Many Things at Once A prompt that asks "rate this on accuracy, tone, completeness, and relevance" will produce muddled scores. The LLM trades off attention between criteria and the results become inconsistent. Split into separate evaluators. ### Skipping the Manual Review Phase Before trusting an evaluator in production, run it against 30-50 examples and compare its judgments to your own. If you disagree with the evaluator more than 10-15% of the time, the judge prompt needs work. ## Checklist When building a new evaluator: 1. **Identify the failure mode** — What specific problem are you catching? 2. **Can you check it with code?** — If yes, write a deterministic evaluator first 3. **Define clear criteria** — Write them down before writing the prompt 4. **Pick the simplest scale** — Pass/fail first, ternary if needed, numeric only as a last resort 5. **Ask for reasoning first** — Structure the schema so the LLM thinks before judging 6. **Use temperature 0** — Consistency over creativity for judges 7. **Validate against your own judgment** — Run 30-50 examples and check alignment 8. **Test in your workflow** — Does the evaluator's signal actually improve the output? # Datasets Source: https://docs.output.ai/evaluators/datasets Define test cases as YAML files with inputs, cached outputs, and ground truth for workflow evaluators Datasets are YAML files that define test cases for your [workflow evaluators](/evaluators/workflow-evaluators). Each file contains a workflow input, optionally a cached output, and ground truth values that evaluators can check against. Datasets live in `tests/datasets/` within your workflow directory: ```text theme={null} src/workflows/ blog_generator/ workflow.ts tests/ evals/ workflow.ts evaluators.ts datasets/ happy_path.yml edge_case.yml stripe_blog.yml ``` ## Basic Dataset The simplest dataset has a name, input, and cached output: ```yaml tests/datasets/basic_input.yml theme={null} name: basic_input input: values: - 1 - 2 - 3 - 4 - 5 last_output: output: result: 15 executionTimeMs: 100 date: '2026-02-13T00:00:00.000Z' ``` The `last_output` contains the workflow's cached result. When you run evals with `--cached`, the framework uses this output instead of re-executing the workflow. ## Dataset with Ground Truth For evaluators that need expected values, add a `ground_truth` section: ```yaml tests/datasets/stripe_blog.yml theme={null} name: stripe_blog input: topic: "Stripe the payment processor" requirements: "Include a link to https://stripe.com/en-gb/pricing" ground_truth: notes: "Known good case" evals: length_of_output: min_length: 100 evaluate_topic: required_topic: "Stripe the payment processor" evaluate_content: required_content: "https://stripe.com/en-gb/pricing" last_output: output: title: "Stripe: The Modern Payment Processing Platform" blog_post: | Stripe has revolutionized online payment processing... executionTimeMs: 5000 date: '2026-02-16T00:00:00.000Z' ``` ## Dataset Fields | Field | Required | Description | | - | - | - | | `name` | Yes | Unique name for this test case | | `input` | Yes | The workflow input (must match your workflow's input schema) | | `ground_truth` | No | Expected values for evaluators to check against | | `last_output` | No | Cached workflow output (used with `--cached` flag) | | `last_eval` | No | Cached evaluation results from the last run | ## Ground Truth Structure Ground truth supports global values and per-evaluator overrides: ```yaml theme={null} ground_truth: # Global values — available to all evaluators notes: "Known good case" min_length: 100 # Per-evaluator overrides evals: evaluate_topic: required_topic: "Stripe the payment processor" evaluate_content: required_content: "https://stripe.com" ``` When an evaluator runs, the framework merges global ground truth with evaluator-specific values. Per-evaluator values override globals with the same key. In your evaluator, access them through `context.ground_truth`: ```typescript theme={null} ( { output, context } ) => Verdict.gte( output.blog_post.length, Number( context.ground_truth.min_length ?? 100 ) ) ``` ## Managing Datasets with the CLI ### Listing Datasets ```bash theme={null} output workflow dataset list blog_generator ``` ### Generating Datasets You can generate datasets from scenario files, trace files, or production traces: ```bash theme={null} # Generate a dataset from a scenario file output workflow dataset generate blog_generator my_scenario --name new_case # Generate from a trace file output workflow dataset generate blog_generator --trace path/to/trace.json # Generate datasets from the most recent runs (traces fetched via the API) output workflow dataset generate blog_generator --download --limit 10 ``` Generating datasets from traces is useful when you want to test against real production inputs. The `--download` flag asks the Output API for the most recent runs of the workflow and turns each one's trace into a dataset YAML file with the input and output already filled in. The API reads the traces from S3, so the CLI needs no AWS credentials — only a reachable API. See [API Configuration](/api/configuration#aws-credential-permissions) for the S3 read permissions the API requires. ## What's Next * [Running Eval Workflows](/evaluators/datasets-and-cli) — Wire evaluators into an eval workflow and run them from the CLI * [Workflow Evaluators](/evaluators/workflow-evaluators) — Writing evaluators with `verify()`, Verdict helpers, and judge functions # Running from CLI Source: https://docs.output.ai/evaluators/datasets-and-cli Wire evaluators into an eval workflow and run them against datasets from the CLI Once you've written evaluators with `verify()` and `Verdict`, you need an eval workflow that ties them together. The eval workflow defines which evaluators to run, how to interpret their results, and whether each one is required or informational. ## Creating an Eval Workflow `evalWorkflow()` connects your evaluators and tells the framework how to interpret their results. The eval workflow file lives at `tests/evals/workflow.ts` inside your workflow directory. A minimal example with one evaluator: ```typescript tests/evals/workflow.ts theme={null} import { evalWorkflow } from '@outputai/core/evals'; import { evaluateSum } from './evaluators.js'; export default evalWorkflow( { name: 'simple_eval', evals: [ { evaluator: evaluateSum, criticality: 'required', interpret: { type: 'boolean' } } ] } ); ``` A more realistic example mixing deterministic checks and LLM judges: ```typescript tests/evals/workflow.ts theme={null} import { evalWorkflow } from '@outputai/core/evals'; import { lengthOfOutput, evaluateTopic, evaluateQuality, evaluateContent, evaluateTone } from './evaluators.js'; export default evalWorkflow( { name: 'blog_generator_eval', evals: [ { evaluator: lengthOfOutput, criticality: 'required', interpret: { type: 'boolean' } }, { evaluator: evaluateTopic, criticality: 'required', interpret: { type: 'verdict' } }, { evaluator: evaluateQuality, criticality: 'required', interpret: { type: 'number', pass: 0.7, partial: 0.4 } }, { evaluator: evaluateContent, criticality: 'informational', interpret: { type: 'boolean' } }, { evaluator: evaluateTone, criticality: 'informational', interpret: { type: 'string', pass: [ 'professional', 'informative' ], partial: [ 'casual' ] } } ] } ); ``` Each entry in the `evals` array has three fields: | Field | Type | Default | Description | | - | - | - | - | | `evaluator` | Function | — | An evaluator created with `verify()` | | `criticality` | `'required' \| 'informational'` | `'required'` | Whether failure should fail the case | | `interpret` | `InterpretConfig` | — | How to convert the raw result to a verdict | ### Criticality * **`required`** (default): If this evaluator fails, the entire case fails. Use for checks that gate quality — topic relevance, minimum length, factual accuracy. * **`informational`**: Failure is reported but doesn't affect the case verdict. Use for metrics you want to track without gating on — tone classification, style scores, auxiliary checks. ### Interpret Types Your evaluators return raw values (booleans, numbers, strings, verdicts). The `interpret` config tells the framework how to convert those into pass/partial/fail: | Type | Config | Pass | Partial | Fail | | - | - | - | - | - | | `boolean` | `{ type: 'boolean' }` | `value === true` | — | `value === false` | | `verdict` | `{ type: 'verdict' }` | `value === 'pass'` | `value === 'partial'` | `value === 'fail'` | | `number` | `{ type: 'number', pass: 0.7, partial: 0.4 }` | `value >= 0.7` | `value >= 0.4` | `value < 0.4` | | `string` | `{ type: 'string', pass: ['a', 'b'], partial: ['c'] }` | `value in ['a', 'b']` | `value in ['c']` | otherwise | The `partial` threshold is optional for both `number` and `string` types — omit it to have only pass and fail. ### Case Verdict Aggregation Each dataset case runs all evaluators. The case-level verdict follows these rules: 1. If any **required** evaluator fails, the case **fails** 2. Else if any **required** evaluator is partial, the case is **partial** 3. Otherwise, the case **passes** Informational evaluators never affect the case verdict. ## Running Evals from the CLI The `output workflow test` command runs your eval workflow against [datasets](/evaluators/datasets). ### Common Commands ```bash theme={null} # Run evals using cached output (no workflow re-execution) output workflow test blog_generator --cached # Run evals with fresh workflow execution and save results output workflow test blog_generator --save # Run specific datasets only output workflow test blog_generator --dataset happy_path,edge_case ``` ### Flags | Flag | Default | Description | | - | - | - | | `--cached` | `false` | Use cached output from `last_output` in datasets, skip workflow execution | | `--save` | `false` | Run workflow fresh and save output/eval results back to dataset files | | `--dataset` | all | Comma-separated list of dataset names to run | | `--format` | `text` | Output format (`text` or `json`) | Use `--cached` during development when iterating on evaluators — it's fast because it skips the workflow entirely. Use `--save` when you want to capture fresh output and eval results. > [!NOTE] > > Nested workflow folders work without any extra setup. `output workflow test content_writing_style_anchor` resolves datasets by the workflow's registered name — `src/workflows/content/writing/style_anchor/tests/datasets/` — and `output workflow dataset generate` writes new datasets to that same folder. Keep the worker running so the CLI can map the registered name to its folder; flat layouts resolve offline exactly as before. ## Putting It All Together Here's the complete setup for a blog generator workflow: **1. Write evaluators** — mix deterministic checks and LLM judges: ```typescript tests/evals/evaluators.ts theme={null} import { verify, Verdict } from '@outputai/core/evals'; import { judgeVerdict, judgeScore } from '@outputai/core/llm'; import { z } from '@outputai/core'; const blogInput = z.object( { topic: z.string() } ); const blogOutput = z.object( { title: z.string(), blog_post: z.string() } ); // Deterministic: check minimum length export const lengthOfOutput = verify( { name: 'length_of_output', input: blogInput, output: blogOutput }, ( { output, context } ) => Verdict.gte( output.blog_post.length, Number( context.ground_truth.min_length ?? 100 ) ) ); // LLM judge: is the blog on-topic? export const evaluateTopic = verify( { name: 'evaluate_topic', input: blogInput, output: blogOutput }, async ( { input, output, context } ) => judgeVerdict( { prompt: 'judge_topic@v1', variables: { blog_title: output.title, blog_post: output.blog_post, required_topic: String( context.ground_truth.required_topic ?? input.topic ) } } ) ); // LLM judge: rate quality 0-1 export const evaluateQuality = verify( { name: 'evaluate_quality', input: blogInput, output: blogOutput }, async ( { input, output } ) => judgeScore( { prompt: 'judge_quality@v1', variables: { blog_title: output.title, blog_post: output.blog_post, topic: input.topic } } ) ); ``` **2. Wire into an eval workflow:** ```typescript tests/evals/workflow.ts theme={null} import { evalWorkflow } from '@outputai/core/evals'; import { lengthOfOutput, evaluateTopic, evaluateQuality } from './evaluators.js'; export default evalWorkflow( { name: 'blog_generator_eval', evals: [ { evaluator: lengthOfOutput, criticality: 'required', interpret: { type: 'boolean' } }, { evaluator: evaluateTopic, criticality: 'required', interpret: { type: 'verdict' } }, { evaluator: evaluateQuality, criticality: 'required', interpret: { type: 'number', pass: 0.7, partial: 0.4 } } ] } ); ``` **3. Create [datasets](/evaluators/datasets):** ```yaml tests/datasets/stripe_blog.yml theme={null} name: stripe_blog input: topic: "Stripe the payment processor" ground_truth: evals: length_of_output: min_length: 100 evaluate_topic: required_topic: "Stripe the payment processor" last_output: output: title: "Stripe: The Modern Payment Processing Platform" blog_post: "Stripe has revolutionized online payment processing..." executionTimeMs: 5000 date: '2026-02-16T00:00:00.000Z' ``` **4. Run:** ```bash theme={null} output workflow test blog_generator --cached ``` ## What's Next * [Workflow Evaluators](/evaluators/workflow-evaluators) — Writing evaluators with `verify()`, Verdict helpers, and judge functions * [Verdict Helpers](/evaluators/verdicts) — Complete reference for deterministic assertions and manual verdicts * [Datasets](/evaluators/datasets) — Defining test cases with inputs and ground truth * [LLM-as-a-Judge Best Practices](/evaluators/best-practices) — Writing effective judge prompts and choosing grading scales * [Evals reference](/packages/core/evals) — Complete module reference * [CLI Commands](/packages/cli#evaluation-commands) — Full CLI reference for eval and dataset commands # Evaluator Step Source: https://docs.output.ai/evaluators/evaluator-step Build evaluators that score LLM output with confidence levels and use the results to control workflow flow Evaluators are a special type of step that scores content — usually LLM output. They return an `EvaluationResult` with a value, a confidence score, and optional reasoning. The real power is using that score in your workflow to control what happens next: retry if quality is low, skip a step if confidence is high, or branch to a different path. This generate-evaluate-retry loop is how you build self-correcting workflows — and it's a core pattern when building AI agents. Evaluators can be deterministic (rule-based checks) or use an LLM to judge quality. Deterministic evaluators are great for structured checks like length, format, or required fields. But more often than not, you'll want LLM-as-a-judge — using an LLM to evaluate things that are hard to check with rules, like whether a summary is accurate, an email sounds natural, or a classification makes sense. ## Deterministic Evaluator A simple evaluator that checks whether a company summary meets basic structural requirements: ```typescript evaluators.ts theme={null} import { evaluator, EvaluationBooleanResult } from '@outputai/core'; import { CheckSummaryStructureInput } from './types.js'; export const checkSummaryStructure = evaluator({ name: 'checkSummaryStructure', description: 'Check if a summary meets minimum structural requirements', inputSchema: CheckSummaryStructureInput, fn: async (input) => { const hasMinLength = input.summary.length >= 100; const mentionsCompany = input.summary.toLowerCase().includes(input.companyName.toLowerCase()); const passes = hasMinLength && mentionsCompany; return new EvaluationBooleanResult({ value: passes, confidence: 1.0, reasoning: !hasMinLength ? 'Summary is too short' : !mentionsCompany ? 'Summary does not mention the company name' : 'Meets structural requirements' }); } }); // types.ts // import { z } from '@outputai/core'; // // export const CheckSummaryStructureInput = z.object({ // summary: z.string(), // companyName: z.string() // }); ``` Deterministic evaluators are fast and predictable — confidence is always `1.0` because there's no ambiguity. Use them for checks where the rules are clear-cut. ## LLM-as-a-Judge Evaluator For subjective quality — accuracy, tone, relevance — you need an LLM to evaluate. This is the more common pattern: ```typescript evaluators.ts theme={null} import { evaluator, EvaluationBooleanResult } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; import { JudgeSummaryInput } from './types.js'; export const judgeSummaryQuality = evaluator({ name: 'judgeSummaryQuality', description: 'Judge whether a company summary is accurate and useful', inputSchema: JudgeSummaryInput, fn: async (input) => { const { output } = await generateText({ prompt: 'judge_summary@v1', variables: { summary: input.summary, companyName: input.companyName }, output: aiSdk.Output.object({ schema: z.object({ reasoning: z.string(), passes: z.boolean(), confidence: z.number() }) }) }); return new EvaluationBooleanResult({ value: output.passes, confidence: output.confidence, reasoning: output.reasoning }); } }); // types.ts // import { z } from '@outputai/core'; // // export const JudgeSummaryInput = z.object({ // summary: z.string(), // companyName: z.string() // }); ``` Evaluators are called from workflows like regular async functions — `await judgeSummaryQuality({ summary, companyName })`. The workflow decides what to do with the result. ## Evaluator Properties | Property | Type | Description | | - | - | - | | `name` | `string` | Unique identifier for the evaluator | | `description` | `string` | Human-readable description | | `inputSchema` | `ZodSchema` | Zod schema for input; values are **parsed** before `fn` runs | | `options` | `object` | Optional workflow options (see [Options](#options)) | | `fn` | `function` | The evaluator implementation (must return an `EvaluationResult`) | Evaluator names must start with a letter or underscore, followed by letters, numbers, or underscores. Hyphens, spaces, dots, and other punctuation are not allowed. > [!NOTE] > > The input schema parses evaluator input; it does not only validate it. The evaluator `fn` receives the value returned by `inputSchema`, so Zod transforms, coercions, defaults, and object-key stripping apply at runtime. ## EvaluationResult Types Evaluators must return an `EvaluationResult`. Three types are available depending on what you're scoring: > [card] EvaluationBooleanResult > > **EvaluationBooleanResult:** > > * Pass/fail judgments > * `value: boolean` > * Quality gates, compliance checks > [card] EvaluationNumberResult > > **EvaluationNumberResult:** > > * Numeric scores > * `value: number` > * Ratings (1-10), percentages > [card] EvaluationStringResult > > **EvaluationStringResult:** > > * Category assignments > * `value: string` > * Classifications, labels All three types share the same base fields: | Field | Required | Description | | - | - | - | | `value` | Yes | The evaluation result (boolean, number, or string) | | `confidence` | Yes | Confidence score between 0 and 1 | | `reasoning` | No | Explanation of the evaluation | | `name` | No | Name for this specific result | | `feedback` | No | Array of `EvaluationFeedback` objects with issues and suggestions | | `dimensions` | No | Array of nested `EvaluationResult` instances for multi-dimensional scoring | ## Boolean Evaluator Pass/fail checks. Use these as quality gates — does this output meet the bar? ```typescript evaluators.ts theme={null} import { evaluator, EvaluationBooleanResult } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; import { CheckFactualityInput } from './types.js'; export const checkFactuality = evaluator({ name: 'checkFactuality', description: 'Check whether a summary contains only factual claims', inputSchema: CheckFactualityInput, fn: async (input) => { const { output } = await generateText({ prompt: 'check_factuality@v1', variables: { summary: input.summary, sourceData: input.sourceData }, output: aiSdk.Output.object({ schema: z.object({ issues: z.array(z.string()), isFactual: z.boolean(), confidence: z.number() }) }) }); return new EvaluationBooleanResult({ value: output.isFactual, confidence: output.confidence, reasoning: output.issues.length > 0 ? `Issues found: ${output.issues.join(', ')}` : 'No factual issues detected' }); } }); // types.ts // import { z } from '@outputai/core'; // // export const CheckFactualityInput = z.object({ // summary: z.string(), // sourceData: z.string() // }); ``` ## Number Evaluator Numeric scores for when you need more granularity than pass/fail. In most cases, pass/fail or a three-tier scale (`pass`/`borderline`/`fail`) gives more consistent results — see [Evaluator Best Practices](/evaluators/best-practices#prefer-passfail-over-numeric-scales). But numeric scores are useful when you need to rank or compare outputs, or when you have well-defined anchors for each score level. ```typescript evaluators.ts theme={null} import { evaluator, EvaluationNumberResult } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; import { ScoreEmailInput } from './types.js'; export const scoreEmailDraft = evaluator({ name: 'scoreEmailDraft', description: 'Score a sales email draft on a 1-10 scale', inputSchema: ScoreEmailInput, fn: async (input) => { const { output } = await generateText({ prompt: 'score_email@v1', variables: { email: input.emailBody, recipientRole: input.recipientRole, companyName: input.companyName }, output: aiSdk.Output.object({ schema: z.object({ reasoning: z.string(), score: z.number().min(1).max(10), confidence: z.number() }) }) }); return new EvaluationNumberResult({ value: output.score, confidence: output.confidence, reasoning: output.reasoning }); } }); // types.ts // import { z } from '@outputai/core'; // // export const ScoreEmailInput = z.object({ // emailBody: z.string(), // recipientRole: z.string(), // companyName: z.string() // }); ``` ## String Evaluator Category assignments — classifying content into labels. ```typescript evaluators.ts theme={null} import { evaluator, EvaluationStringResult } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; import { ClassifyIntentInput } from './types.js'; export const classifyLeadIntent = evaluator({ name: 'classifyLeadIntent', description: 'Classify the buying intent of a lead based on their activity', inputSchema: ClassifyIntentInput, fn: async (input) => { const { output } = await generateText({ prompt: 'classify_intent@v1', variables: { recentActivity: input.recentActivity, companySize: input.companySize }, output: aiSdk.Output.object({ schema: z.object({ reasoning: z.string(), intent: z.enum(['high', 'medium', 'low', 'unknown']), confidence: z.number() }) }) }); return new EvaluationStringResult({ value: output.intent, confidence: output.confidence, reasoning: output.reasoning }); } }); // types.ts // import { z } from '@outputai/core'; // // export const ClassifyIntentInput = z.object({ // recentActivity: z.string(), // companySize: z.number() // }); ``` ## Feedback and Dimensions For more detailed evaluations, you can attach feedback (specific issues and suggestions) and dimensions (sub-scores that break down the overall result). ```typescript evaluators.ts theme={null} import { evaluator, EvaluationStringResult, EvaluationNumberResult, EvaluationFeedback } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; import { ReviewProposalInput } from './types.js'; export const reviewProposal = evaluator({ name: 'reviewProposal', description: 'Review a sales proposal across multiple dimensions', inputSchema: ReviewProposalInput, fn: async (input) => { const { output } = await generateText({ prompt: 'review_proposal@v1', variables: { proposal: input.proposal, prospect: input.prospectName }, output: aiSdk.Output.object({ schema: z.object({ reasoning: z.string(), overall: z.enum(['ready', 'needs_revision', 'major_issues']), confidence: z.number(), clarity: z.number().min(0).max(1), relevance: z.number().min(0).max(1), issues: z.array(z.object({ issue: z.string(), suggestion: z.string(), priority: z.enum(['high', 'medium', 'low']) })) }) }) }); return new EvaluationStringResult({ value: output.overall, confidence: output.confidence, dimensions: [ new EvaluationNumberResult({ value: output.clarity, confidence: output.confidence, name: 'clarity' }), new EvaluationNumberResult({ value: output.relevance, confidence: output.confidence, name: 'relevance' }) ], feedback: output.issues.map(i => new EvaluationFeedback({ issue: i.issue, suggestion: i.suggestion, priority: i.priority })) }); } }); // types.ts // import { z } from '@outputai/core'; // // export const ReviewProposalInput = z.object({ // proposal: z.string(), // prospectName: z.string() // }); ``` ## Using Evaluators in Workflows Evaluators are called like regular async functions. The typical pattern is: generate something, evaluate it, then decide what to do based on the score. ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { lookupCompany, generateSummary } from './steps.js'; import { judgeSummaryQuality } from './evaluators.js'; import { LeadEnrichmentInput, LeadEnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', inputSchema: LeadEnrichmentInput, outputSchema: LeadEnrichmentOutput, fn: async (input) => { const company = await lookupCompany(input.companyDomain); let summary; let attempts = 0; const maxAttempts = 3; while (attempts < maxAttempts) { summary = await generateSummary(company); const quality = await judgeSummaryQuality({ summary, companyName: company.name }); if (quality.value === true && quality.confidence >= 0.7) break; attempts++; } return { company: company.name, summary }; } }); // types.ts // import { z } from '@outputai/core'; // // export const LeadEnrichmentInput = z.object({ // companyDomain: z.string() // }); // // export const LeadEnrichmentOutput = z.object({ // company: z.string(), // summary: z.string() // }); ``` This pattern — generate, evaluate, retry if needed — is the core of LLM-as-a-judge. The evaluator gives your workflow a way to check its own work. ## Options Evaluators support the same options as steps for configuring retry behavior and timeouts. See [Step Options](/steps#options) for the full list. ```typescript evaluators.ts theme={null} import { evaluator, EvaluationBooleanResult } from '@outputai/core'; import { JudgeSummaryInput } from './types.js'; export const judgeSummaryQuality = evaluator({ name: 'judgeSummaryQuality', description: 'Judge whether a company summary is accurate and useful', inputSchema: JudgeSummaryInput, options: { retry: { maximumAttempts: 5, initialInterval: '1s', backoffCoefficient: 2 } }, fn: async (input) => { // ... } }); ``` ## Shared Evaluators When multiple workflows need the same evaluator, put it in `src/shared/evaluators/`: ```typescript src/shared/evaluators/check_factuality.ts theme={null} import { evaluator, EvaluationBooleanResult } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; import { CheckFactualityInput } from './types.js'; export const checkFactuality = evaluator({ name: 'checkFactuality', description: 'Check whether content contains only factual claims', inputSchema: CheckFactualityInput, fn: async (input) => { const { output } = await generateText({ prompt: 'check_factuality@v1', variables: { summary: input.summary, sourceData: input.sourceData }, output: aiSdk.Output.object({ schema: z.object({ confidence: z.number(), isFactual: z.boolean() }) }) }); return new EvaluationBooleanResult({ value: output.isFactual, confidence: output.confidence }); } }); // types.ts // import { z } from '@outputai/core'; // // export const CheckFactualityInput = z.object({ // summary: z.string(), // sourceData: z.string() // }); ``` Import shared evaluators in any workflow: ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { checkFactuality } from '../../shared/evaluators/check_factuality.js'; import { generateSummary, lookupCompany } from './steps.js'; import { LeadEnrichmentInput, LeadEnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', inputSchema: LeadEnrichmentInput, outputSchema: LeadEnrichmentOutput, fn: async (input) => { const company = await lookupCompany(input.companyDomain); const summary = await generateSummary(company); const check = await checkFactuality({ summary, sourceData: JSON.stringify(company) }); return { company: company.name, summary, factualityConfidence: check.confidence }; } }); ``` > [!WARNING] > > Shared evaluators can only be imported by workflows, not by other evaluators or steps. This enforces the activity isolation rule — evaluators are activities and activities can't call other activities. ## Evaluation Workflows The evaluators on this page run *inside* your workflows — they power generate-evaluate-retry loops in production. For testing workflow quality *across datasets* without modifying your workflow code, see [Evaluation Workflow](/evaluators/workflow-evaluators). It covers `verify()` for creating typed evaluators, `Verdict` helpers for deterministic assertions, LLM judge functions, datasets, and running evals from the CLI. ## What's Next * [LLM-as-a-Judge Best Practices](/evaluators/best-practices) — Writing effective judge prompts, choosing grading scales, avoiding common pitfalls, and patterns for production evaluators * [Evaluation Workflow](/evaluators/workflow-evaluators) — Test workflow quality across datasets with `verify()`, `Verdict`, and the CLI * [Evals reference](/packages/core/evals) — Complete module reference # Overview Source: https://docs.output.ai/evaluators/index Score LLM output, control workflow flow, and test quality across datasets Evaluators score content — usually LLM output — and return results with a value, a confidence score, and optional reasoning. Output uses evaluators in two distinct ways: **[Evaluator Step](/evaluators/evaluator-step)** — An evaluator that runs *inside* your workflow as a step. Your workflow generates something, evaluates it, and decides what to do next: retry if quality is low, skip if confidence is high, or branch to a different path. This generate-evaluate-retry loop is how you build self-correcting workflows. ```typescript workflow.ts theme={null} const summary = await generateSummary( company ); const quality = await judgeSummaryQuality( { summary, companyName: company.name } ); if ( quality.value === true && quality.confidence >= 0.7 ) { return summary; } // retry or take a different path... ``` **[Evaluation Workflow](/evaluators/workflow-evaluators)** — A separate workflow that tests another workflow's quality across a dataset of test cases. You define evaluators with `verify()`, wire them into an eval workflow, and run them from the CLI. Use this for regression testing, CI/CD quality gates, and systematic quality monitoring — without modifying your production workflow code. ```bash theme={null} npx output workflow test my_workflow --dataset golden_set ``` ## Which one do I need? | I want to... | Use | | - | - | | Have my workflow check and improve its own output | [Evaluator Step](/evaluators/evaluator-step) | | Test my workflow against a set of known inputs | [Evaluation Workflow](/evaluators/workflow-evaluators) | | Add quality gates that retry on failure | [Evaluator Step](/evaluators/evaluator-step) | | Run evals in CI/CD before deploying | [Evaluation Workflow](/evaluators/workflow-evaluators) | | Use both in the same project | Start with evaluator steps in your workflow, then add an evaluation workflow for testing | Both approaches use evaluators under the hood — the difference is *where* they run and *what* they control. ## What's Next > [card] [Evaluator Step](/evaluators/evaluator-step) > > **Evaluator Step.** Build evaluators and use them inside your workflows for self-correction. > [card] [Evaluation Workflow](/evaluators/workflow-evaluators) > > **Evaluation Workflow.** Test workflow quality across datasets from the CLI. > [card] [LLM-as-a-Judge Best Practices](/evaluators/best-practices) > > **LLM-as-a-Judge Best Practices.** Writing effective judge prompts, grading scales, and common pitfalls. # Verdict Helpers Source: https://docs.output.ai/evaluators/verdicts Deterministic assertions, manual verdicts, and LLM result wrappers for workflow evaluators The `Verdict` object from `@outputai/core/evals` provides helpers for returning evaluation results from your [workflow evaluators](/evaluators/workflow-evaluators). There are three categories: deterministic assertions for programmatic checks, manual verdicts for custom logic, and LLM result wrappers for judge output. ```typescript theme={null} import { Verdict } from '@outputai/core/evals'; ``` ## Deterministic Assertions These helpers compare values and return an `EvaluationBooleanResult` with `confidence: 1.0`. The reasoning is auto-generated based on the comparison result — you don't need to write it yourself. ### Verdict.equals Strict equality check (`===`). ```typescript theme={null} Verdict.equals( actual: unknown, expected: unknown ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: 'Value equals expected: 15' } Verdict.equals( output.result, 15 ) // Fail: { value: false, confidence: 1.0, reasoning: 'Expected 15, got 10' } Verdict.equals( 10, 15 ) ``` Uses `===` comparison, so `Verdict.equals(1, '1')` will fail. Objects are compared by reference, not by deep equality — use for primitives. ### Verdict.closeTo Checks if a number is within a tolerance of an expected value. ```typescript theme={null} Verdict.closeTo( actual: number, expected: number, tolerance: number ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: '0.31 is within 0.05 of 0.3' } Verdict.closeTo( 0.31, 0.3, 0.05 ) // Fail: { value: false, confidence: 1.0, reasoning: '0.5 is not within 0.05 of 0.3 (diff: 0.2)' } Verdict.closeTo( 0.5, 0.3, 0.05 ) ``` Passes when `Math.abs(actual - expected) <= tolerance`. The tolerance is inclusive. Use this for floating-point comparisons where exact equality is unreliable. ### Verdict.gt Strict greater-than (`>`). ```typescript theme={null} Verdict.gt( actual: number, threshold: number ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: '8 > 5' } Verdict.gt( 8, 5 ) // Fail (equal is not greater): { value: false, confidence: 1.0, reasoning: '5 is not greater than 5' } Verdict.gt( 5, 5 ) ``` ### Verdict.gte Greater-than-or-equal (`>=`). ```typescript theme={null} Verdict.gte( actual: number, threshold: number ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: '5 >= 5' } Verdict.gte( 5, 5 ) // Fail: { value: false, confidence: 1.0, reasoning: '3 is not greater than or equal to 5' } Verdict.gte( 3, 5 ) ``` Common use: checking minimum lengths or scores from ground truth. ```typescript theme={null} export const lengthOfOutput = verify( { name: 'length_of_output', input: blogInput, output: blogOutput }, ( { output, context } ) => Verdict.gte( output.blog_post.length, Number( context.ground_truth.min_length ?? 100 ) ) ); ``` ### Verdict.lt Strict less-than (`<`). ```typescript theme={null} Verdict.lt( actual: number, threshold: number ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: '3 < 5' } Verdict.lt( 3, 5 ) ``` ### Verdict.lte Less-than-or-equal (`<=`). ```typescript theme={null} Verdict.lte( actual: number, threshold: number ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: '5 <= 5' } Verdict.lte( 5, 5 ) ``` ### Verdict.inRange Inclusive range check — both boundaries are included. ```typescript theme={null} Verdict.inRange( actual: number, min: number, max: number ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: '7 is in range [1, 10]' } Verdict.inRange( 7, 1, 10 ) // Pass (boundaries are inclusive): Verdict.inRange( 1, 1, 10 ) Verdict.inRange( 10, 1, 10 ) // Fail: { value: false, confidence: 1.0, reasoning: '15 is not in range [1, 10]' } Verdict.inRange( 15, 1, 10 ) ``` Equivalent to `actual >= min && actual <= max`. ### Verdict.contains Substring search using `String.includes()`. ```typescript theme={null} Verdict.contains( haystack: string, needle: string ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: 'String contains "stripe.com"' } Verdict.contains( output.blog_post, 'stripe.com' ) // Fail: { value: false, confidence: 1.0, reasoning: 'String does not contain "pricing"' } Verdict.contains( 'Hello world', 'pricing' ) ``` Case-sensitive. An empty needle always passes. ### Verdict.matches Regular expression test using `RegExp.test()`. ```typescript theme={null} Verdict.matches( value: string, pattern: RegExp ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: 'Value matches /https?:\/\//' } Verdict.matches( output.url, /https?:\/\// ) // Fail: { value: false, confidence: 1.0, reasoning: 'Value does not match /^\d{4}-\d{2}-\d{2}$/' } Verdict.matches( 'not-a-date', /^\d{4}-\d{2}-\d{2}$/ ) ``` ### Verdict.includesAll Checks that an array contains every expected element. ```typescript theme={null} Verdict.includesAll( actual: unknown[], expected: unknown[] ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: 'Array includes all expected values' } Verdict.includesAll( [ 'a', 'b', 'c', 'd' ], [ 'a', 'c' ] ) // Fail: { value: false, confidence: 1.0, reasoning: 'Array is missing: ["d"]' } Verdict.includesAll( [ 'a', 'b', 'c' ], [ 'a', 'd' ] ) ``` Order doesn't matter. Uses `===` for element comparison, so this works best with primitives (strings, numbers). ### Verdict.includesAny Checks that an array contains at least one expected element. ```typescript theme={null} Verdict.includesAny( actual: unknown[], expected: unknown[] ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: 'Array includes: ["b"]' } Verdict.includesAny( [ 'a', 'b', 'c' ], [ 'b', 'x', 'y' ] ) // Fail: { value: false, confidence: 1.0, reasoning: 'Array includes none of: ["x","y"]' } Verdict.includesAny( [ 'a', 'b', 'c' ], [ 'x', 'y' ] ) ``` The success message shows which elements were found. ### Verdict.isTrue Strict boolean check against `true`. ```typescript theme={null} Verdict.isTrue( value: boolean ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: 'Value is true' } Verdict.isTrue( true ) // Fail: { value: false, confidence: 1.0, reasoning: 'Expected true, got false' } Verdict.isTrue( false ) ``` Uses strict equality (`===`). Truthy values like `1` or `"true"` will fail — only boolean `true` passes. ### Verdict.isFalse Strict boolean check against `false`. ```typescript theme={null} Verdict.isFalse( value: boolean ): EvaluationBooleanResult ``` ```typescript theme={null} // Pass: { value: true, confidence: 1.0, reasoning: 'Value is false' } Verdict.isFalse( false ) // Fail: { value: false, confidence: 1.0, reasoning: 'Expected false, got true' } Verdict.isFalse( true ) ``` Uses strict equality. Falsy values like `0` or `""` will fail — only boolean `false` passes. ## Manual Verdicts When no deterministic helper fits your logic, construct verdicts directly. These return `EvaluationVerdictResult` with the verdict value `'pass'`, `'partial'`, or `'fail'`. ### Verdict.pass ```typescript theme={null} Verdict.pass( reasoning?: string ): EvaluationVerdictResult ``` Returns a pass verdict with `confidence: 1.0`. ```typescript theme={null} Verdict.pass() // { value: 'pass', confidence: 1.0 } Verdict.pass( 'All criteria met' ) // { value: 'pass', confidence: 1.0, reasoning: 'All criteria met' } ``` ### Verdict.partial ```typescript theme={null} Verdict.partial( confidence: number, reasoning?: string, feedback?: FeedbackArg[] ): EvaluationVerdictResult ``` Returns a partial verdict with caller-specified confidence. Use when the result is in between pass and fail. ```typescript theme={null} Verdict.partial( 0.6, 'Meets most criteria but missing specific facts' ) // { value: 'partial', confidence: 0.6, reasoning: 'Meets most criteria but missing specific facts' } ``` You can attach structured feedback to explain specific issues: ```typescript theme={null} Verdict.partial( 0.5, 'Some issues found', [ { issue: 'Missing company founding year', suggestion: 'Add founding year to the summary', priority: 'medium' }, { issue: 'No source citations', suggestion: 'Include at least one verifiable source', priority: 'high' } ] ) ``` Feedback objects accept these fields: | Field | Required | Description | | - | - | - | | `issue` | Yes | What the problem is | | `suggestion` | No | How to fix it | | `reference` | No | A reference URL or identifier | | `priority` | No | `'low'` \| `'medium'` \| `'high'` \| `'critical'` | ### Verdict.fail ```typescript theme={null} Verdict.fail( reasoning: string, feedback?: FeedbackArg[] ): EvaluationVerdictResult ``` Returns a fail verdict with `confidence: 0.0`. The reasoning is required — you must explain why the evaluation failed. ```typescript theme={null} Verdict.fail( 'Blog post is empty' ) // { value: 'fail', confidence: 0.0, reasoning: 'Blog post is empty' } Verdict.fail( 'Multiple critical issues', [ { issue: 'Content is off-topic', priority: 'critical' }, { issue: 'Contains hallucinated facts', priority: 'critical' } ] ) ``` ### Using Manual Verdicts in Evaluators Manual verdicts are useful when your check logic doesn't map cleanly to a single assertion: ```typescript tests/evals/evaluators.ts theme={null} import { verify, Verdict } from '@outputai/core/evals'; import { z } from '@outputai/core'; export const evaluateStructure = verify( { name: 'evaluate_structure', input: z.object( { topic: z.string() } ), output: z.object( { title: z.string(), blog_post: z.string() } ) }, ( { output } ) => { const hasTitle = output.title.length > 0; const hasContent = output.blog_post.length >= 100; const hasHeadings = /^##\s/m.test( output.blog_post ); if ( hasTitle && hasContent && hasHeadings ) { return Verdict.pass( 'Has title, sufficient content, and section headings' ); } const issues = []; if ( !hasTitle ) issues.push( { issue: 'Missing title', priority: 'critical' } ); if ( !hasContent ) issues.push( { issue: 'Content too short', priority: 'high' } ); if ( !hasHeadings ) issues.push( { issue: 'No section headings', priority: 'medium' } ); if ( !hasTitle || !hasContent ) { return Verdict.fail( `Missing: ${issues.map( i => i.issue ).join( ', ' )}`, issues ); } return Verdict.partial( 0.7, 'Content present but could be better structured', issues ); } ); ``` ## LLM Result Wrappers When you call the LLM yourself (instead of using the [judge functions](/evaluators/workflow-evaluators#llm-judge-functions)), these wrappers convert raw LLM output into evaluation results. All set `confidence: 0.9` to reflect the inherent uncertainty of LLM-generated judgments. ### Verdict.fromJudge ```typescript theme={null} Verdict.fromJudge( { verdict, reasoning }: { verdict: 'pass' | 'partial' | 'fail', reasoning: string } ): EvaluationVerdictResult ``` Wraps an LLM verdict into an `EvaluationVerdictResult`. ```typescript theme={null} import { verify, Verdict } from '@outputai/core/evals'; import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; export const evaluateAccuracy = verify( { name: 'evaluate_accuracy' }, async ( { output } ) => { const { output: judgment } = await generateText( { prompt: 'judge_accuracy@v1', variables: { content: output.summary }, output: aiSdk.Output.object( { schema: z.object( { verdict: z.enum( [ 'pass', 'partial', 'fail' ] ), reasoning: z.string() } ) } ) } ); return Verdict.fromJudge( judgment ); // { value: 'pass'|'partial'|'fail', confidence: 0.9, reasoning: '...' } } ); ``` ### Verdict.score ```typescript theme={null} Verdict.score( value: number, reasoning?: string ): EvaluationNumberResult ``` Wraps a numeric score into an `EvaluationNumberResult`. ```typescript theme={null} Verdict.score( 0.85, 'High quality content with minor formatting issues' ) // { value: 0.85, confidence: 0.9, reasoning: 'High quality content with minor formatting issues' } ``` ### Verdict.label ```typescript theme={null} Verdict.label( value: string, reasoning?: string ): EvaluationStringResult ``` Wraps a classification label into an `EvaluationStringResult`. ```typescript theme={null} Verdict.label( 'professional', 'Formal tone with industry terminology' ) // { value: 'professional', confidence: 0.9, reasoning: 'Formal tone with industry terminology' } ``` ## Confidence Levels | Category | Confidence | Why | | - | - | - | | Deterministic assertions (`equals`, `gt`, `contains`, etc.) | `1.0` | Programmatically certain | | `Verdict.pass()` | `1.0` | Explicitly marked as passing | | `Verdict.fail()` | `0.0` | Explicitly marked as failing | | `Verdict.partial()` | Caller-specified | Custom confidence for partial results | | LLM wrappers (`fromJudge`, `score`, `label`) | `0.9` | LLM output has inherent uncertainty | ## What's Next * [Workflow Evaluators](/evaluators/workflow-evaluators) — Creating evaluators with `verify()` and judge functions * [Datasets](/evaluators/datasets) — Defining test cases with inputs and ground truth * [Running Eval Workflows](/evaluators/datasets-and-cli) — Wiring evaluators into eval workflows and running them from the CLI # Overview Source: https://docs.output.ai/evaluators/workflow-evaluators Test workflow quality across datasets without modifying your workflow code Your workflows have [evaluator steps](/evaluators/evaluator-step) that power generate-evaluate-retry loops in production. Evaluation workflows answer a different question: "across a set of known inputs, does my workflow still produce acceptable output?" Workflow evaluators run *outside* your workflow. You define evaluators with `verify()`, write test cases as YAML datasets, and run them with the CLI. The framework feeds each dataset case through your evaluators and reports pass/partial/fail verdicts. Nothing in your production workflow changes. This is how you catch regressions when you update a prompt, swap a model, or refactor a step. Run evals before deploying and you'll know if quality dropped. ## Evaluator Step vs Evaluation Workflow These serve different purposes and live in different places: | | Evaluator Step | Evaluation Workflow | | - | - | - | | **Purpose** | Control workflow flow at runtime | Test quality across datasets | | **Runs** | Inside production workflows | Outside, via CLI | | **Created with** | `evaluator()` from `@outputai/core` | `verify()` from `@outputai/core/evals` | | **File location** | `src/workflows//evaluators.ts` | `src/workflows//tests/evals/evaluators.ts` | | **Affects output** | Yes — retry, branch, gate | No — reports results only | | **Uses** | Quality gates, self-correcting agents | Regression testing, prompt comparison, CI/CD | Evaluator steps are documented in [Evaluator Step](/evaluators/evaluator-step). This section covers evaluation workflows. ## Directory Structure Eval files live alongside your workflow in a `tests/` directory: ```text theme={null} src/workflows/ blog_generator/ workflow.ts steps.ts evaluators.ts # Inline evaluators (production) types.ts prompts/ generate_blog@v1.prompt tests/ evals/ workflow.ts # evalWorkflow() definition evaluators.ts # Workflow evaluators (verify + Verdict) judge_topic@v1.prompt # Judge prompt files judge_quality@v1.prompt datasets/ happy_path.yml # Test cases edge_case.yml ``` The eval workflow file (`tests/evals/workflow.ts`) is discovered automatically by the worker alongside your regular workflow. ### Nested workflow folders Workflow folders nest to any depth. A workflow at `src/workflows/content/writing/style_anchor/` registered as `content_writing_style_anchor` keeps its evals and datasets in its own `tests/` directory, and the CLI resolves them by the registered name — no symlink and no flat folder required. > [!WARNING] > > The eval workflow only registers if `tests/evals/workflow.ts` compiles to `dist` — the worker loads workflows from the compiled output, not from source. A `tsconfig` that excludes the whole `src/**/tests` tree silently drops it, and `output workflow test` then can't find `_eval`. Exclude test files individually instead: > > ```json tsconfig.json theme={null} > { > "exclude": ["node_modules", "dist", "**/*.spec.ts", "**/*.test.ts"] > } > ``` > > When the eval source exists but isn't registered, `output workflow test` says so and points at this fix instead of failing with a generic "workflow not found". ## Writing Evaluators with verify() `verify()` creates a typed evaluator that receives the workflow's input, output, and optional ground truth from the dataset. It wraps `evaluator()` from `@outputai/core`, so it integrates with both the eval workflow and the Temporal worker. ```typescript tests/evals/evaluators.ts theme={null} import { verify, Verdict } from '@outputai/core/evals'; import { z } from '@outputai/core'; export const evaluateSum = verify( { name: 'evaluate_sum', input: z.object( { values: z.array( z.number() ) } ), output: z.object( { result: z.number() } ) }, ( { input, output } ) => Verdict.equals( output.result, input.values.reduce( ( a, b ) => a + b, 0 ) ) ); ``` The check function receives a `CheckContext` with three fields: | Field | Type | Description | | - | - | - | | `input` | `TInput` | The workflow input from the dataset | | `output` | `TOutput` | The workflow output (cached or freshly executed) | | `context.ground_truth` | `Record` | Ground truth values from the dataset YAML | The `input` and `output` schemas are optional — they default to `z.any()` if omitted. When provided, they give you type safety inside the check function. ### Using Ground Truth Evaluators can read expected values from the dataset's `ground_truth` field. This lets you define per-case expectations without hardcoding them: ```typescript tests/evals/evaluators.ts theme={null} import { verify, Verdict } from '@outputai/core/evals'; import { z } from '@outputai/core'; export const lengthOfOutput = verify( { name: 'length_of_output', input: z.object( { topic: z.string() } ), output: z.object( { title: z.string(), blog_post: z.string() } ) }, ( { output, context } ) => Verdict.gte( output.blog_post.length, Number( context.ground_truth.min_length ?? 100 ) ) ); ``` The `min_length` value comes from the dataset YAML — see [Ground Truth Structure](/evaluators/datasets#ground-truth-structure) for how this works. ## Verdict Helpers The `Verdict` object provides helpers for returning evaluation results. There are three categories: * **Deterministic assertions** — `equals`, `gte`, `contains`, `matches`, etc. Return `EvaluationBooleanResult` with `confidence: 1.0`. * **Manual verdicts** — `pass()`, `partial()`, `fail()`. Return `EvaluationVerdictResult` for custom logic. * **LLM result wrappers** — `fromJudge()`, `score()`, `label()`. Wrap LLM output with `confidence: 0.9`. ```typescript tests/evals/evaluators.ts theme={null} import { verify, Verdict } from '@outputai/core/evals'; import { z } from '@outputai/core'; export const evaluateContent = verify( { name: 'evaluate_content', input: z.object( { topic: z.string() } ), output: z.object( { title: z.string(), blog_post: z.string() } ) }, ( { output, context } ) => { const required = String( context.ground_truth.required_content ?? '' ); if ( !required ) { return Verdict.isTrue( true ); } return Verdict.contains( output.blog_post, required ); } ); ``` For the complete reference with signatures, examples, and edge cases for every Verdict method, see [Verdict Helpers](/evaluators/verdicts). ## LLM Judge Functions For subjective evaluation — "is this blog post on-topic?", "rate the quality" — use the judge functions. They load a `.prompt` file, call the LLM, and return a typed evaluation result. Four judge functions are available from `@outputai/core/llm`: | Function | Returns | Use for | | - | - | - | | `judgeVerdict` | `pass` / `partial` / `fail` | Subjective quality gates | | `judgeScore` | `number` | Numeric ratings | | `judgeBoolean` | `true` / `false` | Binary subjective checks | | `judgeLabel` | `string` | Classifications | ```typescript tests/evals/evaluators.ts theme={null} import { verify } from '@outputai/core/evals'; import { judgeVerdict, judgeScore, judgeLabel } from '@outputai/core/llm'; import { z } from '@outputai/core'; const blogInput = z.object( { topic: z.string() } ); const blogOutput = z.object( { title: z.string(), blog_post: z.string() } ); export const evaluateTopic = verify( { name: 'evaluate_topic', input: blogInput, output: blogOutput }, async ( { input, output, context } ) => judgeVerdict( { prompt: 'judge_topic@v1', variables: { blog_title: output.title, blog_post: output.blog_post, required_topic: String( context.ground_truth.required_topic ?? input.topic ) } } ) ); export const evaluateQuality = verify( { name: 'evaluate_quality', input: blogInput, output: blogOutput }, async ( { input, output } ) => judgeScore( { prompt: 'judge_quality@v1', variables: { blog_title: output.title, blog_post: output.blog_post, topic: input.topic } } ) ); export const evaluateTone = verify( { name: 'evaluate_tone', input: blogInput, output: blogOutput }, async ( { output } ) => judgeLabel( { prompt: 'judge_tone@v1', variables: { blog_title: output.title, blog_post: output.blog_post } } ) ); ``` All judge functions accept a `JudgeArgs` object: | Field | Type | Description | | - | - | - | | `prompt` | `string` | Prompt filename (e.g., `'judge_topic@v1'`) | | `variables` | `Record` | Template variables | | `schema` | `ZodType` | Optional custom output schema (overrides the default) | ### Writing Judge Prompts Judge `.prompt` files live in the same `tests/evals/` directory as your evaluators. Each judge function expects a specific output schema from the LLM: | Function | Expected JSON fields | | - | - | | `judgeVerdict` | `{ verdict: 'pass'\|'partial'\|'fail', reasoning: string }` | | `judgeScore` | `{ score: number, reasoning: string }` | | `judgeBoolean` | `{ result: boolean, reasoning: string }` | | `judgeLabel` | `{ label: string, reasoning: string }` | Here's a judge prompt for topic evaluation: ```yaml tests/evals/judge_topic@v1.prompt theme={null} --- provider: anthropic model: claude-haiku-4-5-20251001 temperature: 0 maxOutputTokens: 1000 --- You are an evaluation judge. Assess whether a blog post is faithfully about the required topic. Return a JSON object with: - verdict: "pass" if the blog clearly focuses on the topic, "partial" if it mentions the topic but lacks depth, "fail" if it is not about the topic - reasoning: a brief explanation of your judgment Required topic: {{ required_topic }} Blog title: {{ blog_title }} Blog post: {{ blog_post }} Judge whether this blog post is faithfully about the required topic. ``` Use `temperature: 0` for judge prompts — you want consistency, not creativity. For best practices on writing effective judge prompts, see [LLM-as-a-Judge Best Practices](/evaluators/best-practices). ### LLM Result Wrappers If you're calling the LLM yourself instead of using the judge functions, the `Verdict` object provides wrappers to convert raw LLM output into evaluation results (with confidence `0.9`). See [LLM Result Wrappers](/evaluators/verdicts#llm-result-wrappers) for the full reference. ## What's Next * [Verdict Helpers](/evaluators/verdicts) — Complete reference for all Verdict methods with signatures and examples * [Datasets](/evaluators/datasets) — Defining test cases with inputs and ground truth * [Running Eval Workflows](/evaluators/datasets-and-cli) — Wire evaluators into an eval workflow and run from the CLI * [LLM-as-a-Judge Best Practices](/evaluators/best-practices) — Writing effective judge prompts and choosing grading scales * [Evals reference](/packages/core/evals) — Complete module reference # Home Source: https://docs.output.ai/index The open-source TypeScript framework for building AI workflows and agents. Designed for Claude Code — describe what you want, Claude builds it, with all the best practices already in place. Output is the open-source TypeScript framework for building AI workflows and agents. Designed for Claude Code — describe what you want, Claude builds it, with all the best practices already in place. Prompts, evals, tracing, cost tracking, orchestration, credentials. One framework. No SaaS fragmentation. ## Build AI using AI Output is the first framework designed for AI coding agents. The entire codebase is structured so Claude Code can scaffold, plan, generate, test, and iterate on your workflows. **Each workflow is a folder.** `workflow.ts`, `steps.ts`, `types.ts`, `prompts/`, `evaluators.ts` — everything your agent needs to understand context lives together. **Ships with Claude Code integration.** Native commands, sub-agents, and a CLAUDE.md that teaches Claude the framework's patterns. Describe what you want in plain English. Claude builds it. ```bash theme={null} # Tell Claude what you want "Create a workflow that researches a company and generates a sales brief" # Claude scaffolds the workflow, steps, prompts, and evals # You refine from there ``` Beginners ship professional code from day one — the conventions teach best practices. Experienced AI engineers stop rebuilding the same infrastructure. ## Everything included No more stitching together SaaS subscriptions. Output handles the fundamentals in one place: **Where do prompts live?** In your repo as `.prompt` files — version-controlled, reviewable, deployable with your code. Not scattered strings. Not locked in external dashboards. **How do you test non-deterministic code?** LLM-as-judge evaluators with confidence scores. Programmatic quality gates, not vibes. **How do you track costs?** Every LLM call traces token counts and model info. Query execution history anytime. **How do you handle secrets?** AI apps need a lot of API keys. Sharing `.env` files is risky, and coding agents shouldn't see your secrets. Encrypted credentials, scoped per environment, managed through the CLI. **How do you scale?** Temporal is already there under the hood. You don't think about it until you need it. ## The Code Two functions to organize your code: `workflow()` for orchestration, `step()` for I/O. ```typescript theme={null} // workflow.ts - orchestration only import { workflow, z } from '@outputai/core'; import { scrapeWebsite, summarizeContent } from './steps.js'; export default workflow({ name: 'research_company', inputSchema: z.object({ companyUrl: z.string().url() }), outputSchema: z.object({ summary: z.string() }), fn: async ({ companyUrl }) => { const content = await scrapeWebsite(companyUrl); const summary = await summarizeContent(content); return { summary }; } }); ``` ```typescript theme={null} // steps.ts - where I/O happens import { step, z } from '@outputai/core'; import { generateText } from '@outputai/core/llm'; import { outputFetch } from '@outputai/core/http'; export const scrapeWebsite = step({ name: 'scrapeWebsite', inputSchema: z.string().url(), outputSchema: z.string(), fn: async (url) => { const response = await outputFetch(url, { signal: AbortSignal.timeout(30000) }); return response.text(); } }); export const summarizeContent = step({ name: 'summarizeContent', inputSchema: z.string(), outputSchema: z.string(), fn: async (content) => { return generateText({ prompt: 'summarize@v1', variables: { content } }); } }); ``` ## What's Included > [card] Prompt Management > > **Prompt Management.** `.prompt` files with LiquidJS templating. Version-controlled, reviewable in PRs, deployed with your code. > [card] Multi-Provider LLM > > **Multi-Provider LLM.** Anthropic, OpenAI, Azure, Vertex AI, Bedrock. Switch providers by changing one line in your prompt file. > [card] LLM-as-Judge Evals > > **LLM-as-Judge Evals.** Built-in evaluators with confidence scores and reasoning. Test non-deterministic code programmatically. > [card] Tracing and Cost Tracking > > **Tracing and Cost Tracking.** Every operation traced automatically. Token counts, costs, latency. JSON on disk, zero config. You own your data. > [card] Durable Orchestration > > **Durable Orchestration.** Temporal under the hood. Automatic retries, workflow history, replay on failure. You don't think about it until you need it. > [card] Encrypted Credentials > > **Encrypted Credentials.** AES-256-GCM encrypted secrets, scoped per environment and workflow. No more sharing `.env` files or external vault subscriptions. > [card] [Get Started](/start-here/getting-started) > > **Get Started.** Set up your first Output project in 5 minutes. # Migrations Source: https://docs.output.ai/migrations/index Upgrade guides for moving between versions of the Output framework. Breaking changes are rare. When they happen, each one gets a dedicated guide below with the before/after patterns and a checklist. ## How to upgrade The fastest path is the CLI: ```bash theme={null} npx output migrate ``` It reads the `@outputai/*` version in your `package.json`, finds the matching guide below, applies the steps, and runs your type checker. If you're jumping several versions, apply each guide in order. ## Guides > [card] [v0.1.12 → v0.2.0](/migrations/v0.1.12-to-v0.2.0) > > Dataset file format and deprecated workflow run endpoints. > [card] [v0.2.0 → v0.3.0](/migrations/v0.2.0-to-v0.3.0) > > LLM cost payload format and cost event name. > [card] [v0.3.0 → v0.4.0](/migrations/v0.3.0-to-v0.4.0) > > Package.json Output.ai config section rename. > [card] [v0.4.0 → v0.5.0](/migrations/v0.4.0-to-v0.5.0) > > HTTP request cost API and cost event payload changes. > [card] [v0.5.2 → v0.6.0](/migrations/v0.5.2-to-v0.6.0) > > Hook payload context objects and trace run ids. > [card] [v0.6.0 → v0.7.0](/migrations/v0.6.0-to-v0.7.0) > > Removed web search tool re-exports and provider list helper rename. > [card] [v0.7.0 → v0.8.0](/migrations/v0.7.0-to-v0.8.0) > > Workflow result aggregation removal, workflow invocation options, and child workflow execution semantics. > [card] [v0.8.0 → v0.9.0](/migrations/v0.8.0-to-v0.9.0) > > CLI replaces `--format json` with the native `--json` flag. > [card] [v0.9.0 → v0.10.0](/migrations/v0.9.0-to-v0.10.0) > > Trace destinations omit unavailable `local` and `remote` keys instead of returning `null`. > [card] [v0.10.0 → v0.11.0](/migrations/v0.10.0-to-v0.11.0) > > Workflow results and error handling, parsed component schemas, Temporal worker cutover, and other breaking changes. > [card] [v0.11.0 → v0.12.0](/migrations/v0.11.0-to-v0.12.0) > > LLM call signatures, strict prompt body parsing, loaded prompt shape, `aiSdk` re-exports, and prompt-only skills in `@outputai/llm`. > [card] [v0.12.0 → v0.13.0](/migrations/v0.12.0-to-v0.13.0) > > Worker shutdown defaults, worker exit codes, and the catalog startup gate in `@outputai/core`, plus the LLM pricing snapshot in `@outputai/llm`. > [card] [v0.13.0 → v0.14.0](/migrations/v0.13.0-to-v0.14.0) > > Usage and cost reporting for failed and aborted LLM calls in `@outputai/llm`, plus new trace node ids for steps and activities in `@outputai/core`. > [card] [v0.14.0 → v0.15.0](/migrations/v0.14.0-to-v0.15.0) > > `@outputai/credentials` folded into `@outputai/core/credentials`, removed `onBeforeWorkerStart` hook, and non-retryable credentials errors. > [card] [v0.15.0 → v0.16.0](/migrations/v0.15.0-to-v0.16.0) > > Package consolidation, peer dependencies, provider-native web search costs, HTTP response parsing, and worker concurrency defaults. > [card] [v0.16.0 → v0.17.0](/migrations/v0.16.0-to-v0.17.0) > > Worker exit code on a forced shutdown, shutdown and Temporal log changes, and `OUTPUT_TEMPORAL_LOG_LEVEL` validation. # v0.1.12 → v0.2.0 Source: https://docs.output.ai/migrations/v0.1.12-to-v0.2.0 Upgrading Output.ai projects from v0.1.12 to v0.2.0. Covers dataset file format changes and deprecated workflow run endpoints. This release ships two breaking changes that require attention: 1. **`@outputai/evals`** — dataset files use a new multi-case format; the old single-case format is no longer supported. 2. **`output-api`** — several workflow run routes are deprecated in favour of pinned-run equivalents. Old routes keep working until 2026-07-16 but emit `Deprecation` response headers. ## `@outputai/evals` — dataset file format Old dataset files carried a top-level `name:` field and held a single case: ```yaml tests/datasets/stripe_blog.yml theme={null} name: stripe_blog input: topic: "Stripe the payment processor" requirements: "Include a link to https://stripe.com/en-gb/pricing" last_output: output: title: "Stripe: The Modern Payment Processing Platform" word_count: 350 executionTimeMs: 5000 ground_truth: notes: "Known good case" evals: length_of_output: min_length: 100 ``` New files use the case name as a top-level YAML key, and can hold multiple cases: ```yaml tests/datasets/stripe_blog.yml theme={null} stripe_blog: input: topic: "Stripe the payment processor" requirements: "Include a link to https://stripe.com/en-gb/pricing" last_output: output: title: "Stripe: The Modern Payment Processing Platform" word_count: 350 executionTimeMs: 5000 ground_truth: notes: "Known good case" evals: length_of_output: min_length: 100 stripe_blog_low_quality: input: topic: "Stripe the payment processor" requirements: "Include a link to https://stripe.com/en-gb/pricing" last_output: output: title: "Payment Processing" blog_post: "Payment processing is important for businesses." word_count: 12 executionTimeMs: 1200 ground_truth: notes: "Known low quality case" evals: length_of_output: min_length: 100 ``` ### Migration steps For every `.yml` file under `tests/datasets/`: 1. Remove the top-level `name:` field. 2. Use the value of `name` as a new top-level YAML key. 3. Indent everything else by two spaces so it nests under that key. Optionally collapse related cases into a single file by adding more top-level keys. Case names must be unique across every file in `tests/datasets/` — duplicates now throw instead of silently overwriting. > [!TIP] > > The old format is no longer supported. Files that still have `name:` at the top will fail to load with an explicit error. ## `output-api` — deprecated workflow run endpoints Three mutation endpoints are deprecated. They still respond, but should be migrated to pinned-run equivalents by 2026-07-16: | Deprecated | Replacement | | - | - | | `PATCH /workflow/:id/stop` | `PATCH /workflow/:id/runs/:rid/stop` | | `POST /workflow/:id/terminate` | `POST /workflow/:id/runs/:rid/terminate` | | `POST /workflow/:id/reset` | `POST /workflow/:id/runs/:rid/reset` | Pinned-run routes target a specific Temporal run by ID. You get the `runId` from `POST /workflow/run` or `POST /workflow/start` — both responses now include it. ### Migration steps Replace each deprecated call with its pinned-run equivalent, passing the `runId` you captured when the workflow started: ```diff theme={null} - await fetch(`/workflow/${workflowId}/stop`, { method: 'PATCH' }) + await fetch(`/workflow/${workflowId}/runs/${runId}/stop`, { method: 'PATCH' }) - await fetch(`/workflow/${workflowId}/terminate`, { method: 'POST' }) + await fetch(`/workflow/${workflowId}/runs/${runId}/terminate`, { method: 'POST' }) - await fetch(`/workflow/${workflowId}/reset`, { method: 'POST' }) + await fetch(`/workflow/${workflowId}/runs/${runId}/reset`, { method: 'POST' }) ``` If you're using the generated SDK client, regenerate it after upgrading. Every deprecated call now emits `Deprecation`, `Sunset`, and `Link` response headers you can alert on. ### Additive changes (no action required) These are backwards-compatible response-shape additions — mentioned here so they don't surprise you when you regenerate clients: * `POST /workflow/run` response now includes `runId`. * `POST /workflow/start` response now includes `runId`. * `PATCH /workflow/:id/stop` response is now `{ workflowId, runId }` (previously had no body). * `POST /workflow/:id/terminate` response now includes `runId`. * All status, result, and trace-log responses now include `runId`. ## Verify After applying both migrations: 1. Bump the framework packages in your `package.json` to `0.2.0`. 2. Run `pnpm install` (or the equivalent for your package manager). 3. Run your type checker. The dataset format change surfaces at runtime rather than compile time, so also run whatever test suite exercises your evals. 4. Start your workers and hit a sample workflow; confirm responses include `runId`. # v0.10.0 → v0.11.0 Source: https://docs.output.ai/migrations/v0.10.0-to-v0.11.0 Upgrading Output.ai projects from v0.10.0 to v0.11.0: workflow results and error handling, parsed component schemas, Temporal worker cutover, and other breaking changes. This guide covers breaking changes across `@outputai/core`, `@outputai/http`, `@outputai/llm`, `@outputai/cli`, and `output-api`. The main ones are unwrapped workflow results and error handling, Zod schemas that return parsed values, and a Temporal worker runtime that is not replay-compatible with open v0.10.x executions. ## API HTTP request logging The API server was refactored to remove the `morgan` dependency and emit richer request logs. The public HTTP API contract is unchanged, but the shape, level, and message of the per-request log lines the server emits are different. This only affects you if you consume `output-api` logs in an observability tool (Datadog, CloudWatch, Loki, etc.) or match on them in scripts. ### Log level now derives from response status This is the most impactful change. Previously every request was logged at the `http` level regardless of outcome. Now the level is chosen from the response status: | Status | Level (before) | Level (after) | | - | - | - | | 2xx / 3xx | `http` | `http` | | 4xx | `http` | `warn` | | 5xx | `http` | `error` | If you have alerts or filters keyed on winston log levels, they will now behave differently: any alert on `error` or `warn` will fire on 4xx/5xx HTTP responses that previously logged at `http`. ### The `status` field was renamed to `statusCode` The structured metadata field carrying the numeric response status changed name, for consistency with the other fields the logger emits. ```diff theme={null} - "status": 200 + "statusCode": 200 ``` If you use Datadog, map `statusCode` to the standard `http.status_code` attribute with a remapper in your log pipeline. That keeps the built-in HTTP status facet working without emitting a dotted field name from the application. ### The log message changed from a constant to a request summary Previously the message was the constant string `"HTTP request"`, with all detail in the metadata. Now the message is a human-readable summary and the structured record is still attached as metadata. ```diff theme={null} - "HTTP request" + "POST /workflow 200 12ms" ``` ### `responseTime` is now an integer `responseTime` is now whole milliseconds (measured with `Date.now()`) rather than a sub-millisecond float. ```diff theme={null} - "responseTime": 12.347 + "responseTime": 12 ``` ### Before and after A successful request, before (v0.10.0): ```json theme={null} { "level": "http", "message": "HTTP request", "method": "POST", "url": "/workflow", "status": 200, "contentLength": "42", "responseTime": 12.347, "requestId": "8f3c...", "workflowName": "simple" } ``` The same request, after (v0.11.0): ```json theme={null} { "level": "http", "message": "POST /workflow 200 12ms", "method": "POST", "url": "/workflow", "statusCode": 200, "contentLength": "42", "responseTime": 12, "requestId": "8f3c...", "workflowName": "simple" } ``` A server error, before — logged at `http`: ```json theme={null} { "level": "http", "message": "HTTP request", "status": 500, "errorType": "Error", "errorMessage": "Something went wrong" } ``` After — logged at `error`, with the renamed field: ```json theme={null} { "level": "error", "message": "POST /workflow 500 34ms", "statusCode": 500, "errorType": "Error", "errorMessage": "Something went wrong" } ``` ### Migration steps #### Update alerts and level-based filters If you alert or filter on winston levels, audit those rules. HTTP 4xx now arrives at `warn` and 5xx at `error`. Decide whether that is what you want: * To keep alerting only on application errors, scope alerts to exclude HTTP request logs (for example, filter on the presence of `statusCode`). * To alert on failing requests, this is now available directly from the log level with no extra query. #### Update queries and facets that reference `status` Anywhere you query, facet, or dashboard on the request-log `status` field, switch to `statusCode`. ```diff theme={null} # Datadog / log query - @status:500 + @statusCode:500 ``` In Datadog, add a remapper in your log pipeline to map `statusCode` onto the standard `http.status_code` attribute. That attribute maps to the built-in HTTP status facet, so once the remapper is in place you can query on `@http.status_code:500` and reuse the standard facet instead of defining a custom one. #### Update anything that matches the message string Scripts, log processors, or saved searches that match the literal message `"HTTP request"` will no longer match. Match on a structural field instead (for example, the presence of `statusCode` or `requestId`), or update the matcher to the new summary format ` ms`. #### Adjust `responseTime` consumers expecting sub-millisecond precision If a dashboard or aggregation relied on fractional milliseconds in `responseTime`, note that values are now whole milliseconds. ### API logging checklist * Review winston level-based alerts and filters; 4xx now logs at `warn`, 5xx at `error`. * Rename `status` to `statusCode` in log queries, facets, and dashboards; in Datadog, add a remapper from `statusCode` to `http.status_code`. * Replace any match on the constant message `"HTTP request"` with a structural field or the new summary format. * Confirm `responseTime` consumers tolerate integer milliseconds. ## Hook event changes This section applies to hook files that import from `@outputai/core/hooks`. ### `on()` now receives an event envelope In v0.10.x, SDK event fields were merged into the same object as framework metadata. In v0.11.0, framework metadata remains at the top level and event-specific data is available under `payload`. This affects every handler registered with `on()`, including: * `http:request` * `cost:http:request` * `cost:llm:request` * Custom events Lifecycle hooks such as `onWorkflowStart`, `onActivityEnd`, and `onError` remain flat. #### Before ```ts theme={null} import { on } from '@outputai/core/hooks'; import type { HttpRequestEvent } from '@outputai/http'; on( 'http:request', event => { console.log( event.eventId, event.workflowDetails.workflowId, event.method, event.url ); } ); ``` #### After ```ts theme={null} import { on } from '@outputai/core/hooks'; import type { HttpRequestEvent } from '@outputai/http'; on( 'http:request', event => { if ( !event.workflowDetails || !event.payload ) { return; } console.log( event.eventId, event.workflowDetails.workflowId, event.payload.method, event.payload.url ); } ); ``` The envelope has this shape: ```ts theme={null} { eventId: string; eventDate: number; activityInfo?: Info; workflowDetails?: WorkflowDetails; outputActivityKind?: string; payload: T | undefined; } ``` The generic passed to `on()` still describes the event-specific data. The difference is that `T` now types `event.payload` instead of fields on `event` itself. Because custom events can omit their payload, check `event.payload` before reading its fields. SDK events such as `http:request` and cost events always supply one, but the public handler type still represents the optional case. v0.11.0 also adds `emit(eventName, payload?)` for publishing custom events from an Output activity: ```ts theme={null} import { emit, on } from '@outputai/core/hooks'; emit( 'company:enriched', { companyId: 'company-123' } ); on<{ companyId: string }>( 'company:enriched', event => { if ( !event.payload ) { return; } console.log( event.payload.companyId ); } ); ``` When an event is emitted outside an activity context, `activityInfo`, `workflowDetails`, and `outputActivityKind` are omitted. These fields are therefore optional on `ExternalHookPayload`; check any context field before using it. ### Activity lifecycle hooks no longer include `aggregations` `onActivityEnd`, `onActivityError`, and activity-sourced `onError` payloads no longer include the `aggregations` field. Remove reads of `event.aggregations` from hook handlers and use the dedicated cost and request events when those measurements are needed. ```ts theme={null} import { on } from '@outputai/core/hooks'; on( 'cost:llm:request', event => { console.log( event.payload ); } ); ``` ### Workflow error hooks receive rehydrated `Error` instances Workflow errors are still serialized to cross Temporal's workflow sandbox boundary (so `name`, `message`, `cause`, and other diagnostics survive). Before hooks run, the worker rehydrates that payload into an `Error`. `onWorkflowError` and workflow-sourced `onError` handlers therefore receive an `Error` instance again — the same shape as activity and runtime error hooks. ```ts theme={null} import { onError } from '@outputai/core/hooks'; onError( event => { if ( event.source === 'workflow' ) { console.log( event.error instanceof Error ); // true console.log( event.error.name, event.error.message ); } } ); ``` The rehydrated value is always a bare `Error`, not the original subclass. `instanceof FatalError` is false even when `error.name === 'FatalError'`. Use `error.name`, or `hasErrorType(error, FatalError)` from `@outputai/core` (matches `.name` and walks `.cause`), to distinguish failure kinds after the boundary. Extra enumerable fields may still be present at runtime; narrow or cast in TypeScript when you need them. ### Update imported hook payload types The exported base and envelope types were simplified in v0.11.0. If your hook files import these types directly, make the following replacements: * Replace `OnHookPayload` with `ExternalHookPayload`. * Replace `OnHookEnvelope` with `ActivityPayloadBase`. * Replace `ActivityHookPayload` with `ActivityPayloadBase`. `HookPayloadBase` now contains only `eventId` and `eventDate`. Use `WorkflowPayloadBase` when you also need `workflowDetails`, or `ActivityPayloadBase` when you need the workflow and activity context fields. #### Before ```ts theme={null} import type { ActivityHookPayload, OnHookEnvelope, OnHookPayload } from '@outputai/core/hooks'; type CompanyEnrichedEvent = OnHookPayload<{ companyId: string }>; ``` #### After ```ts theme={null} import type { ActivityPayloadBase, ExternalHookPayload } from '@outputai/core/hooks'; type CompanyEnrichedEvent = ExternalHookPayload<{ companyId: string }>; ``` ### Activity lifecycle hooks include internal activities `onActivityStart`, `onActivityEnd`, and `onActivityError` now run for internal activities as well as steps and evaluators. Internal activity payloads have: ```ts theme={null} { outputActivityKind: 'internal_step' } ``` If your handler should keep the v0.10.x behavior, add an explicit filter: ```ts theme={null} import { onActivityStart } from '@outputai/core/hooks'; onActivityStart( event => { if ( event.outputActivityKind === 'internal_step' ) { return; } // Handle steps and evaluators. } ); ``` Review metrics, logs, webhooks, and state updates triggered by activity lifecycle hooks. Without a filter, internal activities now contribute to those side effects. ### `onError` excludes the internal catalog workflow The internal `$catalog` workflow was already excluded from `onWorkflowStart`, `onWorkflowEnd`, and `onWorkflowError`. In v0.11.0, its workflow and activity errors are also excluded from `onError`. No migration is needed unless an `onError` handler explicitly relied on `$catalog` failures. Worker startup and catalog-manager failures still surface as runtime errors. Monitor Temporal or API catalog health if you need to detect the catalog workflow being terminated after startup. ### Hook migration checklist * Update every `on()` handler to read event-specific fields from `event.payload`. * Guard `event.payload` before accessing its fields. * Keep framework fields such as `eventId`, `workflowDetails`, and `activityInfo` at the top level. * Remove reads of `aggregations` from activity lifecycle and error hooks. * Treat workflow hook errors as reconstructed `Error` instances (not plain serialized objects). `instanceof FatalError` is always false after rehydration — use `error.name` or `hasErrorType(error, FatalError)` when subclass identity matters. * Filter `outputActivityKind === 'internal_step'` in activity lifecycle hooks when internal activities should remain hidden. * Remove assumptions that `onError` reports `$catalog` workflow failures. ## HTTP client changes `@outputai/http` now exposes two explicitly named, instrumented clients: * `outputFetch` for Fetch-compatible requests. * `createKyClient` for a Ky client backed by `outputFetch`. Ky was upgraded from v1 to v2 and both Ky and Undici are now peer dependencies. Most projects using the previous `httpClient` need import, option, and dependency updates. ### Upgrade and resolve the HTTP peers Ky and Undici were previously private dependencies of `@outputai/http` and are now peers. Current npm and pnpm versions install compatible peers automatically, so upgrading the Output package is normally enough: ```bash theme={null} npm install @outputai/http@^0.11 ``` Use the equivalent command for your package manager, then commit the updated lockfile. Install `ky@^2` or `undici@^8` explicitly only if you need to pin a version or resolve a peer-version conflict. ### Rename HTTP exports Update imports using this mapping: | v0.10.x | v0.11.0 | | - | - | | `fetch` | `outputFetch` | | `httpClient` | `createKyClient` | | `HTTPError` | `ky.HTTPError` | | `TimeoutError` | `ky.TimeoutError` | | `HttpClientOptions` | `ky.Options` | | `RequestInfo` | `undici.RequestInfo` or a native Fetch type | | `RequestInit` | `undici.RequestInit` or a native Fetch type | For example: ```diff theme={null} - import { httpClient, HTTPError, TimeoutError } from '@outputai/http'; + import { createKyClient, ky } from '@outputai/http'; - const client = httpClient( { + const client = createKyClient( { timeout: 30_000 } ); try { await client.get( url ); } catch ( error ) { - if ( error instanceof HTTPError ) { + if ( error instanceof ky.HTTPError ) { console.log( error.response.status ); } - if ( error instanceof TimeoutError ) { + if ( error instanceof ky.TimeoutError ) { console.log( 'Request timed out' ); } } ``` The complete Ky and Undici namespaces are available as `ky` and `undici` from `@outputai/http`. ### Update Ky v2 options Replace Ky's `prefixUrl` option with `prefix`: ```diff theme={null} - const client = httpClient( { - prefixUrl: 'https://api.example.com', + const client = createKyClient( { + prefix: 'https://api.example.com', timeout: 30_000 } ); ``` Review other Ky options against Ky 2 when upgrading. This is especially important for shared client factories that expose Ky's `Options` type. See [Ky's official v2.0.0 migration guide](https://github.com/sindresorhus/ky/releases/tag/v2.0.0#migration-guide) for the complete list of changes, including empty-response JSON parsing, `beforeError` behavior, hook option normalization, `searchParams` merging, and `HTTPError.data`. ### Update Ky hook callbacks Ky 2 passes one state object to every hook. Ky 1 `beforeRequest`, `beforeError`, and `afterResponse` callbacks commonly used positional arguments. ```diff theme={null} - const beforeRequest = request => { + const beforeRequest = ( { request } ) => { request.headers.set( 'x-api-key', apiKey ); }; - const beforeError = error => { + const beforeError = ( { error } ) => { console.error( error.response?.status ); return error; }; - const afterResponse = async ( request, options, response ) => { + const afterResponse = async ( { request, options, response } ) => { await recordUsage( request, response ); }; ``` Types for hooks are also available through the Ky namespace: ```ts theme={null} import { ky } from '@outputai/http'; const afterResponse = async ( { response }: ky.AfterResponseState ) => { // ... }; ``` Audit hook functions passed indirectly through shared option objects as well as inline hooks. ### Replace custom wrappers around the old fetch export If your project created its own Ky factory solely to inject Output's old `fetch`, use `createKyClient` directly: ```diff theme={null} - import ky from 'ky'; - import type { Options } from 'ky'; - import { fetch } from '@outputai/http'; + import { createKyClient, ky } from '@outputai/http'; - export const createHttpClient = ( options: Options = {} ) => - ky.create( { fetch: fetch as NonNullable, ...options } ); + export const createHttpClient = ( options: ky.Options = {} ) => + createKyClient( options ); ``` If the wrapper adds other defaults or hooks, keep the wrapper and pass those options to `createKyClient`. ### Update direct Fetch usage Rename direct imports: ```diff theme={null} - import { fetch } from '@outputai/http'; + import { outputFetch } from '@outputai/http'; - const response = await fetch( url, init ); + const response = await outputFetch( url, init ); ``` `outputFetch` accepts URL strings, `URL` objects, and both Node and Undici `Request` objects. Node inputs are normalized before entering the Undici-backed implementation. Keep `Request` and `FormData` from the same family within one call: ```ts theme={null} import { outputFetch, undici } from '@outputai/http'; const form = new undici.FormData(); form.set( 'name', 'Ada' ); await outputFetch( 'https://api.example.com/users', { method: 'POST', body: form } ); ``` The same pattern works with Node's global `FormData`. Do not combine a Node `Request` with Undici `FormData`, or an Undici `Request` with Node `FormData`. ### Remove reliance on `undici.install()` Importing `@outputai/http` no longer replaces `globalThis.fetch`, `Request`, `Response`, `Headers`, or `FormData`. Code that imports an Undici dispatcher but calls global `fetch` should choose the HTTP implementation explicitly. Use `outputFetch` when the request should be traced: ```diff theme={null} - import { undici } from '@outputai/http'; + import { outputFetch, undici } from '@outputai/http'; const dispatcher = new undici.EnvHttpProxyAgent( { headersTimeout: 15 * 60 * 1000, bodyTimeout: 15 * 60 * 1000 } ); - const customFetch = ( input: string | URL | Request, init?: RequestInit ) => - fetch( input, { ...init, dispatcher } as RequestInit ); + const customFetch = ( + input: undici.RequestInfo, + init?: undici.RequestInit + ) => outputFetch( input, { ...init, dispatcher } ); ``` Use `undici.fetch` instead when tracing is not wanted. Do not assume the npm Undici dispatcher's types or behavior apply to Node's built-in Fetch implementation. ### Configure proxy behavior explicitly Core workers no longer install a process-wide Undici dispatcher when proxy environment variables are present. * `outputFetch` and `createKyClient` continue to use an `EnvHttpProxyAgent` and honor standard `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` variables. * For direct npm Undici calls, pass an `undici.EnvHttpProxyAgent` or configure Undici's global dispatcher yourself. * For Node's built-in Fetch, enable Node's environment proxy support at process startup with `NODE_USE_ENV_PROXY=1` and set the standard proxy variables. Audit libraries that receive a custom `fetch` callback. Ensure the callback uses `outputFetch`, `undici.fetch`, or native Fetch intentionally rather than relying on the old import-time global replacement. ### HTTP migration checklist * Upgrade `@outputai/http` and confirm the lockfile resolved Ky 2 and Undici 8. * Rename `fetch` and `httpClient`. * Update error and option types to the `ky` and `undici` namespaces. * Replace `prefixUrl` with `prefix`. * Convert Ky hooks to state-object parameters. * Replace custom Ky factories that only injected Output's old `fetch`. * Check custom dispatchers and Fetch callbacks for reliance on `undici.install()`. * Configure proxy behavior for non-Output HTTP calls. * Run type checking and HTTP integration tests after regenerating the lockfile. ## Component schemas now return parsed values In v0.10.x, workflow, step, and evaluator schemas validated values, but component handlers and callers continued to receive the original values. In v0.11.0, components use the values returned by Zod: * `inputSchema` parsing happens before `fn`, so the handler receives parsed input. * `outputSchema` parsing happens after `fn`, so workflow and step callers receive parsed output. * Zod coercions, transforms, defaults, and object-key handling now affect runtime values. TypeScript mirrors that split: handlers are typed with `z.infer` for input (post-parse) and `z.input` for what they return (pre-parse). Callers pass `z.input` and receive `z.infer`. For example: ```js theme={null} const calculateTotal = step( { name: 'calculate_total', inputSchema: z.object( { count: z.coerce.number().default( 1 ) } ), outputSchema: z.object( { total: z.number(), currency: z.string().default( 'USD' ) } ), fn: async input => ( { total: input.count * 10, internalNote: 'not part of the public result' } ) } ); const result = await calculateTotal( { count: '2', requestId: 'request-123' } ); // result => { total: 20, currency: 'USD' } ``` In v0.10.x, `input.count` was the string `'2'`, `input.requestId` remained available, `result.internalNote` was returned, and `currency` was absent because `fn` did not set it. In v0.11.0, `input.count` is the number `2`, Zod's default object behavior removes `requestId` from the handler input and `internalNote` from the caller result, and `outputSchema` fills `currency` with `'USD'`, so the returned result is `{ total: 20, currency: 'USD' }`. Trace files still record the **raw** Temporal workflow arguments at start (before `inputSchema` parse) and the **parsed** output at end (after `outputSchema` parse). ### Transforms, replay, and continue-as-new Because schemas run at the component boundary, `.transform()`, `z.coerce`, `.preprocess()`, and similar helpers are no longer documentation-only: * **Determinism (workflow schemas):** Workflow code is replayed by Temporal. Any transform on a workflow `inputSchema` or `outputSchema` must be deterministic (no `Date.now()`, `Math.random()`, or other non-replay-safe sources). Prefer keeping workflow input as wire format (types, `.default()`, optional coerce) and putting one-shot shaping in a step or inside `fn` when possible. * **Idempotency (re-parse):** Every workflow run parses its Temporal args again — including runs started with `continueAsNew`. The next run does not know it is a continuation. If you pass values that were already transformed, a non-idempotent transform runs twice (for example appending a suffix on each continue-as-new). Prefer idempotent transforms, or pass wire-format input into `continueAsNew` (the same shape you would pass when starting the workflow). * **Catalog JSON Schema:** The worker catalog still converts Zod schemas with `z.toJSONSchema`. Bare `.transform()` often cannot be represented and may omit the schema from the catalog; `z.coerce` and `.pipe()` usually convert. Authors who control both the schema and catalog consumers should treat catalog JSON Schema as best-effort for advanced Zod features. ### Published workflow package types `WorkflowFunctionWrapper`, `StepFunctionWrapper`, and `EvaluatorFunctionWrapper` are now typed as `Wrapper` (schema generics), not `Wrapper>`. Runtime is unchanged; TypeScript breaks for packages that still ship `.d.ts` built against the old arity (for example a published workflows catalog). Rebuild and republish those packages against `@outputai/core` v0.11.0 so their declarations match, or release them together with the core bump. ### Migration steps Review the `inputSchema` and `outputSchema` of every workflow, step, and evaluator: * Update handlers and callers to use the parsed Zod input and output types (`z.infer` in handlers, `z.input` at call sites when schemas coerce or default). * Check schemas using `.transform()`, `z.coerce`, `.default()`, `.catch()`, or `.preprocess()` for values that now change at runtime. * Check object schemas for unknown properties that Zod strips by default. Use `z.looseObject( { ... } )` when those properties must be preserved. * Ensure transforms on **workflow** schemas are deterministic for Temporal replay. * Ensure workflow `inputSchema` transforms are idempotent if you `continueAsNew` with values that will be parsed again, or pass wire-format input instead. * Republish any package that exports workflow/step/evaluator wrappers so its `.d.ts` matches the new `Wrapper` arity. ## Workflow result changes New workflows return their declared value directly instead of an internal Output wrapper. Activity results are also no longer wrapped. Code should consume the declared return value without reading a nested `.output`. Trace destinations now live in Temporal memo and use a flat shape: ```json theme={null} { "trace": { "local": "/path/to/trace.json", "remote": "s3://trace-bucket/path/to/trace.json" } } ``` The previous `trace.destinations` object is removed. API and CLI JSON results created by v0.11.0 workers include `v: "2"`, and failures expose a structured `error` object instead of only an error string: ```json theme={null} { "v": "2", "status": "failed", "output": null, "trace": null, "error": { "name": "ValidationError", "message": "companyDomain is required" } } ``` v2 also drops legacy `errorDetails.retryable`. That flag was after-the-fact Temporal metadata on a link in the failure chain (whether that failure had been marked retryable while running), not a signal that the API or client should retry — by the time a result is returned the execution is already terminal. The structured `error` object carries the failure content instead. `POST /workflow/run` no longer hardcodes `status` to only `completed` or `failed`. It now uses the same path as the other result builders (`/workflow/.../result`, list/status, and related endpoints): Temporal's terminal execution status, formatted for the API (`cancelled`, `terminated`, `timed_out`, and so on). If you treated every unsuccessful `/run` as `status === "failed"`, broaden that check — cancellation used to appear as `failed` there even though result endpoints already returned the real status. The API continues to return the legacy unversioned shape for workflows started by older workers. Consumers that can read results from both versions should branch on `result.v === "2"`. ## Workflow and activity error handling v0.11.0 changes how the workflow and activity interceptors classify failures. The goal is to follow Temporal's model: only explicit fatal failures complete the workflow run; other workflow code bugs retry the Workflow Task. ### Workflow interceptor In v0.10.x, **root** workflows attached trace metadata to every thrown error after `ContinueAsNew` / cancellation handling, and the interceptor converted any error carrying that metadata into an `ApplicationFailure`, so the workflow run failed. **Child** workflows did not attach that metadata, so those errors were rethrown unchanged. Cancellation always rethrew before that wrap, on both root and child. v0.11.0 replaces the blanket root wrap with explicit classification: | Error | v0.10.x | v0.11.0 | | - | - | - | | `ContinueAsNew` | Ends the trace as continued-as-new and rethrows | Same | | Cancellation (`isCancellation`) | Sinks the `Error` and rethrows (never wrapped in `ApplicationFailure`) | Sinks a serialized error (no `stack`) and rethrows | | `FatalError` / `ValidationError` | Root: sunk, then converted to `ApplicationFailure` (workflow fails). Child: sunk and rethrown. (`ValidationError` did not extend `FatalError` yet.) | Sinks the serialized error and throws a non-retryable `ApplicationFailure` with the serialized error in `.details[0].error`. `TransparentFatalError` is unwrapped to its cause first | | Temporal failures (`ActivityFailure`, `ChildWorkflowFailure`, other `TemporalFailure`) | Root: sunk, then converted to `ApplicationFailure` when trace metadata was attached. Child: sunk and rethrown. (`CancelledFailure` usually matches `isCancellation` first.) | Sinks the serialized error and rethrows unchanged. (`CancelledFailure` still matches `isCancellation` first when applicable.) | | Other errors (`TypeError`, syntax/`JSON.parse` failures, unexpected throws) | Root: sunk, then converted to `ApplicationFailure` → workflow **failed**, masking Temporal Workflow Task retries. Child: sunk and rethrown | Rethrown unchanged **without** sinking → the **Workflow Task retries** (or stays open until timeout). The CLI can look "stuck" until the task succeeds, times out, or you throw `FatalError` / an `ApplicationFailure` | ### Activity interceptor | Error | v0.10.x | v0.11.0 | | - | - | - | | `CompleteAsyncError` | Error hook and trace error fired, then rethrown (or wrapped in `ApplicationFailure` when aggregations were present) | Recorded as an async handoff in the trace (not an error). No activity error hook. Rethrown | | Temporal failures (`TemporalFailure`) | Error hook and trace error fired, then rethrown (or wrapped in `ApplicationFailure` when aggregations were present) | Error hook and trace error fire, then rethrown unchanged | | `FatalError` / `ValidationError` | Error hook and trace error fired, then rethrown (or wrapped in `ApplicationFailure` when aggregations were present). Non-retryable mainly via activity `nonRetryableErrorTypes` (defaults included both names) | Converted to `ApplicationFailure` with serialized error in `.details[0].error`. Always `nonRetryable: true` via `instanceof FatalError`. User `nonRetryableErrorTypes` cannot make these retryable. `TransparentFatalError` is unwrapped to its cause first | | Other errors | Error hook and trace error fired, then rethrown (or wrapped in `ApplicationFailure` when aggregations were present). Retry followed the activity retry policy / `nonRetryableErrorTypes` | Converted to `ApplicationFailure` with serialized error in `.details[0].error`. `nonRetryable` when the error class name is listed in `activityInfo.retryPolicy.nonRetryableErrorTypes` | `ValidationError` and `TransparentFatalError` both extend `FatalError` in v0.11.0, so they share the fatal rows above. `TransparentFatalError` did not exist in v0.10.x; it is a transport whose `.cause` is used for logs, traces, hooks, and failure details. ### What to do * Throw `FatalError` (or `ValidationError`) when the workflow or activity must end without Temporal Task retries. * Expect ordinary bugs in workflow code (for example a bad `JSON.parse`) to retry the Workflow Task instead of failing the run immediately. * Read structured failures from `ApplicationFailure.details[0].error` (and from API/CLI `error` on result `v: "2"`) instead of relying on a plain message string alone. * Update monitors that assumed every root-workflow throw became a failed workflow execution. ## Workflow runtime changes This section covers the workflow execution changes in `@outputai/core` v0.11.0. ### What changed * Steps, evaluators, and shared activities now use one workflow-scoped runtime dispatcher. * Shared activities are registered as `#` instead of `$shared#`. * Child workflow invocation options are passed as workflow arguments instead of being propagated through Temporal memo. * A child workflow's definition-level `activityOptions` now override inherited parent options. Invocation-level and step-level options remain more specific. * Worker startup fails if a workflow-scoped activity uses the same name as a shared activity. * Steps/evaluators files that use unsupported export or import shapes (or top-level activity calls) fail worker startup instead of bundling with broken rewrites. ### Steps and evaluators file shape These forms were already unsupported by workflow rewriting. The worker now rejects them during bundling: | Invalid | Valid | | - | - | | `export default step(…)` / `export * from './other.js'` | `export const foo = step(…)` (named exports only) | | `import foo from './steps.js'` / `import * as steps from './steps.js'` | `import { foo } from './steps.js'` | | `const steps = require( './steps.js' )` | `const { foo } = require( './steps.js' )` | | `foo()` at module top level | Call `foo()` inside a function | ### Before upgrading running workers > [!WARNING] > > v0.11.0 is **not replay-compatible** with open v0.10.x workflow executions. Do not deploy v0.10.x and v0.11.0 workers to the same Temporal task queue, and do not replace a v0.10.x worker while any v0.10.x executions are still open on that queue. The v0.11.0 runtime changes Temporal history commands and attributes on paths that every workflow hits, not only shared activities or child workflows: * Every workflow run issues an early `upsertMemo` (`ModifyWorkflowProperties`) for `payloadVersion` (and root `traceInfo` when tracing is enabled). v0.10.x histories do not contain that command at the same point. * Every scheduled activity gets framework-enforced `retry.nonRetryableErrorTypes` (at least `FatalError`), so activity schedule attributes differ from v0.10.x even when the activity type name is unchanged. * A shared activity previously scheduled as `$shared#send_event` is now scheduled as `lead_enrichment#send_event`. * A child workflow is now started with its invocation-level activity options in its argument payload instead of inherited through memo. * Memo shape and usage changed (flat `trace`, resolved `activityOptions`, no legacy result-wrapper metadata). Temporal replays a workflow's existing history when another worker processes it. If a v0.11.0 worker replays a history produced by v0.10.x, command type or attributes can differ from the recorded events. Temporal then reports a nondeterminism failure. Treat **all** open v0.10.x executions as unsafe to replay on v0.11.0. There is no supported mixed-version or rolling cutover on the same task queue. An old parent and new child (or the reverse) can also disagree on memo and child-argument contracts even when replay does not fail immediately. #### Choose a safe rollout strategy Use one of these strategies before changing the worker version: 1. **Drain the existing task queue.** Stop starting new workflows on the v0.10.x queue, wait for **all** open executions to complete, and then replace the worker. 2. **Move v0.11.0 to a new task queue.** Keep the v0.10.x worker serving its existing queue until that queue is empty, while new executions are routed to a separate v0.11.0 queue. 3. **Restart open executions.** If executions can be safely terminated and restarted from their original input or a checkpoint, restart them after the v0.11.0 cutover rather than letting v0.11.0 replay v0.10.x history. Do not rely on a normal rolling restart on the same task queue. #### Update activity-type consumers Update dashboards, alerts, history processors, and scripts that match the old `$shared` activity prefix. ##### Before ```ts theme={null} const isSharedActivity = activityType.startsWith( '$shared#' ); ``` ##### After Shared and local activities use the same workflow namespace. Match the full workflow activity type when possible: ```ts theme={null} const isSendEventActivity = activityType === 'lead_enrichment#send_event'; ``` If the workflow name is not known: ```ts theme={null} const activityName = activityType.split( '#' ).at( -1 ); const isSendEventActivity = activityName === 'send_event'; ``` ### Review child workflow activity options Activity options are merged from broad defaults to specific overrides. v0.11.0 changes the relative precedence of inherited parent options and the child workflow's definition. #### v0.10.x precedence 1. Output's default activity options 2. The child workflow's definition-level `options.activityOptions` 3. Activity options inherited from the parent workflow 4. The `activityOptions` passed to this child invocation 5. The called step's own `options.activityOptions` #### v0.11.0 precedence 1. Output's default activity options 2. Activity options inherited from the parent workflow 3. The child workflow's definition-level `options.activityOptions` 4. The `activityOptions` passed to this child invocation 5. The called step's own `options.activityOptions` This means a child definition now protects its own retry and timeout defaults from broader settings inherited through the parent. For example: ```ts theme={null} const childWorkflow = workflow( { name: 'enrich_company', options: { activityOptions: { retry: { maximumAttempts: 2 } } }, async fn( input ) { // ... } } ); ``` If the parent currently has `maximumAttempts: 8`, the child used 8 attempts in v0.10.x. In v0.11.0, the child uses 2 attempts. #### Preserve a parent-selected override Pass the policy on the child invocation when the parent must override the child's definition: ```ts theme={null} await childWorkflow( { companyId: input.companyId }, { activityOptions: { retry: { maximumAttempts: 8 } } } ); ``` Invocation-level options remain more specific than inherited parent options and the child definition. Alternatively, remove the overlapping option from the child definition when the child should always inherit that field from its parent. > [!NOTE] > > Step-level `options.activityOptions` still have final precedence. Review step definitions as well as parent and child workflow definitions when calculating the effective policy. ### Workflow runtime checklist * Inventory **all** open v0.10.x executions on queues you plan to upgrade — assume none are safe to replay on v0.11.0. * Drain the old task queue, keep a v0.10.x worker until that queue is empty, route new work to a v0.11.0 queue, or restart open executions before the cutover. * Do not run v0.10.x and v0.11.0 workers on the same Temporal task queue. * Update dashboards and history tooling that match `$shared#`. * Rename any workflow activity that shares a name with a shared activity. * Replace default/`export *` exports and default/namespace/non-destructured imports in steps and evaluators with named bindings; move top-level activity calls into functions. * Audit parent and child workflows that configure the same retry or timeout fields. * Pass `activityOptions` on child invocations where the parent must override the child's definition. * Update tests that assert inherited parent options override child definition options. ## Temporal TypeScript SDK version Output now ships the Temporal TypeScript SDK (`@temporalio/*`) at **v1.20.3** (previously **v1.17.0**). Re-test any project code that imports `@temporalio/*` directly against that version. ## CLI: `workflow test_eval` renamed to `workflow test` The workflow evaluation command id is now `workflow:test`. The previous primary id `workflow:test_eval` is removed (it was only the filename-derived id; published docs already used `output workflow test`). ```bash theme={null} # Before npx output workflow test_eval # After npx output workflow test ``` `output workflow test` continues to work the same way; only the `test_eval` name stops resolving. ### CLI rename checklist * Replace any scripts, CI steps, or aliases that call `output workflow test_eval` with `output workflow test`. * No change if you already use `output workflow test`. ## CLI: worker hot-reload and install scripts ### What changed In v0.10.x, worker hot-reload watched `package.json` and `output:worker` ran `npm install` on every restart. Editing dependencies (or even touching `package.json`) triggered a full install cycle through nodemon. In v0.11.0, hot-reload only watches source under `src`. Dependency installs are explicit: * `output:worker` builds and starts; it no longer runs install. * `output:worker:watch` no longer passes `--watch package.json` to nodemon. * `output:worker:install` remains the script that runs `npm install`. * `output dev` still runs `output:worker:install` once when the worker container starts, then uses watch for source changes only. ### Update project scripts Existing projects keep their old `package.json` scripts until you sync them. From the project root: ```bash theme={null} npx output fix ``` That rewrites `scripts` to the current scaffold template, including the new `output:worker` and `output:worker:watch` definitions. It does not install packages and does not change your dependencies list. ### After you change dependencies Hot-reload will not pick up new or updated packages. After editing `package.json` / the lockfile: 1. Run `npm install` on the host. 2. Recreate the worker so it reinstalls into its `node_modules` volume: * Foreground `output dev` that owns the stack: quit it, then start `output dev` again. * Attached session or `output dev -d`: run `output dev down`, then `output dev` again. If you start the worker yourself (without `output dev`), run `npm run output:worker:install` before `npm run output:worker` whenever dependencies change. ### Worker scripts checklist * Run `npx output fix` once after upgrading so `output:worker` / `output:worker:watch` match the v0.11.0 scaffold. * Treat dependency changes as an install + worker recreate, not a hot-reload. ## CLI: `.env` loading The CLI loads `.env` with Node's `process.loadEnvFile` instead of `dotenv`. Values are taken literally — `${OTHER}` is not expanded. Put the final value in the file (or export the variable in the shell). `OUTPUT_CLI_ENV` still selects which file to load. ## LLM permanent errors and schema-mismatch messages `@outputai/llm` still maps non-retryable AI SDK failures so Temporal does not retry them, but the transport and some messages changed. This can break log queries, monitors, or tests that matched the old strings or `FatalError` name. | Case | Before (v0.10.x) | After (v0.11.0) | | - | - | - | | Non-retryable AI SDK / API failures (`APICallError` with `isRetryable: false`, `InvalidArgumentError`, `NoSuchModelError`, …) | Wrapped in `FatalError` with message `AI-SDK fatal error…: ` | Wrapped in `TransparentFatalError`; logs, traces, hooks, and result `error` use the **original** AI SDK error | | `NoObjectGeneratedError` whose message includes `No object generated: response did not match schema.` and has a `ZodError` in the cause chain | Rebuilt as a new `NoObjectGeneratedError` with `First issue is "" at path [].` appended | Same `NoObjectGeneratedError` returned unchanged (no message rewrite). Still not mapped to a fatal transport | `NoObjectGeneratedError` was not turned into `FatalError` in v0.10.x either; only the optional message enrichment was removed. ### Migration steps * Prefer matching AI SDK error names/types (or structured result `error`) instead of `FatalError` / the `AI-SDK fatal error` prefix. * If you parsed the appended `First issue is … at path […]` suffix, read issues from the error cause chain (or Zod error) instead. ## Prompt Liquid rendering is strict `@outputai/llm` now renders `.prompt` files with Liquid `strictVariables: true` and `strictFilters: true` (plus `lenientIf: true`). ### What changed | Case | Before (v0.10.0) | After (v0.11.0) | | - | - | - | | Undefined variable (`{{ missing }}`) | Rendered as an empty string | Throws a non-retryable `FatalError` | | Unknown filter (`{{ x \| not_a_filter }}`) | Rendered without failing closed | Throws a non-retryable `FatalError` | | Falsy / missing values in `{% if %}` | Omitted / falsey as usual | Unchanged (`lenientIf` still allows this) | ### Migration steps 1. Audit `.prompt` files for placeholders that are not always passed in `variables`. 2. Pass every referenced variable (or remove / guard the placeholder). Prefer `{% if var %}` / `| default:` only when the variable is still provided or you intentionally rely on `lenientIf` conditionals. 3. Replace custom or misspelled filters with [supported Liquid filters](https://liquidjs.com/filters/overview.html). 4. Expect render failures to surface as `FatalError` (no Temporal retry) — fix the prompt or inputs rather than catching and retrying. ### Prompt strictness checklist * Grep prompts for `{{` and confirm each name is supplied by callers. * Run critical workflows once after upgrade and watch for `Prompt "…" could not be rendered` fatals. * Update any docs or tests that assumed empty-string rendering for missing variables. ## LLM provider names: `google-vertex` and `amazon-bedrock` `@outputai/llm` renames the built-in Vertex and Bedrock prompt `provider` values to match the underlying AI SDK packages and the [models.dev](https://models.dev) catalog. LLM cost lookup is also keyed by `provider` + `model` in that catalog (not by model id alone). | Before (v0.10.x) | After (v0.11.0) | | - | - | | `provider: vertex` | `provider: google-vertex` (preferred). `vertex` still works as a deprecated alias and is rewritten at prompt load with a warning. | | `provider: bedrock` | `provider: amazon-bedrock` (preferred). `bedrock` still works as a deprecated alias and is rewritten at prompt load with a warning. | | `registerProvider('vertex', …)` / `registerProvider('bedrock', …)` | Throws `ValidationError`. Register under `google-vertex` or `amazon-bedrock` instead. | | Custom `registerProvider` name sharing a model id with another models.dev provider | Previously could pick that other provider’s rates. Now `response.cost` is `null` unless the registered name is a models.dev provider id. | Prompt files that still use the old names keep working. Overrides registered under the old names do **not**. ### Custom providers and pricing If you registered a custom provider under a name that is **not** a [models.dev](https://models.dev) provider id (for example `my-proxy` or a private gateway), cost used to fall back to whatever catalog entry matched the model id alone — often the wrong vendor’s rates. That fallback is removed: those calls still run, but pricing is unavailable (`null`) instead of incorrect. To get catalog pricing again, register and reference a models.dev provider id (such as `openai`, `google-vertex`, or `amazon-bedrock`). ### Before ```ts theme={null} import { createVertex } from '@ai-sdk/google-vertex'; import { registerProvider } from '@outputai/llm'; registerProvider('vertex', createVertex({ project: process.env.GOOGLE_VERTEX_PROJECT, location: process.env.GOOGLE_VERTEX_LOCATION })); ``` ```yaml theme={null} --- provider: vertex model: gemini-2.5-flash-lite --- ``` ### After ```ts theme={null} import { createVertex } from '@ai-sdk/google-vertex'; import { registerProvider } from '@outputai/llm'; registerProvider('google-vertex', createVertex({ project: process.env.GOOGLE_VERTEX_PROJECT, location: process.env.GOOGLE_VERTEX_LOCATION })); ``` ```yaml theme={null} --- provider: google-vertex model: gemini-2.5-flash-lite --- ``` ### Migration steps 1. Replace `registerProvider('vertex', …)` with `registerProvider('google-vertex', …)` and `registerProvider('bedrock', …)` with `registerProvider('amazon-bedrock', …)`. 2. Prefer updating prompt front matter to `google-vertex` / `amazon-bedrock` (aliases remain until they are removed in a later release). 3. Grep for `registerProvider\(\s*['"]vertex['"]` and `registerProvider\(\s*['"]bedrock['"]` before upgrading. ### Provider rename checklist * Update any `registerProvider` calls that used `vertex` or `bedrock`. * Optionally update `.prompt` files to the canonical names to silence deprecation warnings. * Expect `response.cost === null` (and no `cost:llm:request` event) for custom provider names that are not models.dev ids — they no longer inherit another provider’s pricing by model name alone. # v0.11.0 → v0.12.0 Source: https://docs.output.ai/migrations/v0.11.0-to-v0.12.0 Upgrading Output.ai projects from v0.11.0 to v0.12.0: AI SDK 7, LLM call signatures, loaded prompt shape, aiSdk re-exports, and prompt-only skills in @outputai/llm. This guide covers breaking changes in `@outputai/llm`. The package now uses AI SDK 7 and its matching provider majors. Generation APIs drop native AI SDK call arguments. Skills load only from prompt frontmatter. Call-argument tools merge with prompt YAML tools. Prompt file `config` is a strict key list. Loaded messages carry resolved `providerOptions` instead of tag `attributes`. LLM traces use a single loaded `prompt` on start, keep raw usage and merged sources on end, and store normalized usage and cost as attributes. ## Upgrade AI SDK and provider packages `@outputai/llm` v0.12 requires these dependency majors: * `ai`: 7.x * `@ai-sdk/openai`, `@ai-sdk/anthropic`, `@ai-sdk/azure`, and `@ai-sdk/perplexity`: 4.x * `@ai-sdk/amazon-bedrock` and `@ai-sdk/google-vertex`: 5.x Update only the provider packages your application installs. The complete upstream changes are in the [AI SDK 7 migration guide](https://ai-sdk.dev/docs/migration-guides/migration-guide-7-0). The separate `@perplexity-ai/ai-sdk` search-tool package is not the official `@ai-sdk/perplexity` provider. Its latest release, `0.1.3`, declares support for AI SDK 5 and 6 only. Projects using `perplexitySearch()` should replace it or verify its behavior with AI SDK 7 before upgrading; package managers may report an unmet peer dependency. ### Rename stream callbacks and properties `streamText()` and `Agent.stream()` now use `onEnd` instead of `onFinish`: ```ts theme={null} // Before await streamText( { prompt: 'writer@v1', onFinish( event ) { console.log( event.result ); } } ); // After await streamText( { prompt: 'writer@v1', onEnd( event ) { console.log( event.result ); } } ); ``` Rename the corresponding exported types: * `WrappedStreamTextOnFinishEvent` -> `WrappedStreamTextOnEndEvent` * `WrappedStreamTextOnFinishCallback` -> `WrappedStreamTextOnEndCallback` The wrapped event continues to include `result`, `cost`, and merged `sources`. AI SDK 7 also renamed the full event stream: ```ts theme={null} // Before for await ( const part of result.fullStream ) { // ... } // After for await ( const part of result.stream ) { // ... } ``` `fullStream` remains available as a deprecated alias, but migrate to `stream`. `textStream` is unchanged. Direct AI SDK `onStepFinish` usage becomes `onStepEnd`. `onChunk` now receives every AI SDK 7 stream part, including start, finish, error, step boundaries, text boundaries, and reasoning boundaries. Update exhaustive handlers to ignore part types they do not use. ### Review native AI SDK response usage Output returns proxied AI SDK 7 results. If your application reads native response fields beyond Output's `result`, `cost`, and merged `sources`, follow the official AI SDK 7 migration guide linked above instead of treating this guide as a replacement for it. Output's merged `sources` now includes native sources accumulated across every AI SDK step as well as URLs extracted from tools. ### Normalized usage and cost metadata Cost calculation uses AI SDK 7's detailed token counts when they reconcile with the aggregate input or output count. Incomplete breakdowns use the aggregate count. Missing cache pricing uses the regular input price, and missing reasoning pricing uses the regular output price. Traces now store separate `llm:generation:usage` and `llm:generation:cost` attributes. Both include `providerId`, `modelId`, nullable aggregate `input`, `output`, and `total` fields, plus detailed `items`. Priced calls also retain the deprecated `llm:usage` attribute for existing trace consumers. Usage items have an `amount`, a `group` (`input` or `output`), and one of these labels: * Input: `no_cache`, `cache_read`, or `cache_write` * Output: `text` or `reasoning` When detailed counts do not reconcile with an aggregate count, that group uses `label: null`. `LLMGenerationUsage.status` is `complete` when both input and output usage are available; otherwise it is `incomplete`. Cost items repeat the usage identity and amount, then add `ppm`, item `total`, and a status: * `ok`: the matching price was available. * `fallback`: cache or reasoning usage used the regular input or output price. * `missing`: no applicable price was available; `ppm` and item `total` are `null`. `LLMGenerationCost.status` is `precise`, `imprecise`, or `incomplete` based on those item statuses and usage completeness. Missing model or dimension pricing therefore produces a non-null, incomplete `LLMGenerationCost` whose `total` may be `null`. The complete cost object is `null` only when the pricing catalog itself could not be loaded. The new `llm:generation:metering` event is emitted whenever raw AI SDK usage can be normalized. Its payload is `{ usage: LLMGenerationUsage, cost: LLMGenerationCost | null }`. Prefer it for new integrations because it preserves reported usage independently from pricing and records fallback and missing prices explicitly. The existing `cost:llm:request` event remains supported with its legacy payload shape, so existing handlers do not need a structural migration for v0.12. Its deprecated `LLMUsageEvent` retains the `input`, `input_cached`, `output`, and `reasoning` line types. Values can differ where AI SDK 7 reports a different breakdown or where v0.12 corrects legacy reasoning double-counting. Raw AI SDK usage remains available on the response and trace output. ### Update Agent assumptions `Agent` no longer inherits from AI SDK's `ToolLoopAgent`. Its Output APIs retain their existing behavior, but code must not depend on `Agent instanceof ToolLoopAgent` or other inherited `ToolLoopAgent` members. The intended `MessageStore` conversation behavior is unchanged. Output reads AI SDK 7's accumulated `responseMessages` so intermediate tool-call and tool-result messages continue to be persisted once. Custom stores must preserve all AI SDK 7 `ModelMessage` content parts. File data may require binary-safe serialization, and assistant content can contain the new `reasoning-file` part. ### Review provider behavior * OpenAI reasoning requests now return detailed reasoning summaries by default when reasoning is enabled. Set `providerOptions.openai.reasoningSummary` to `null` in prompt frontmatter to disable them. * Function-valued tool descriptions are now accepted in addition to string descriptions. Call-level `toolApproval`, `runtimeContext`, and `toolsContext` are not exposed by the v0.12 Output wrapper. AI SDK 7's deprecated tool-level `needsApproval` field remains accepted. ## Skills load only from the prompt file `generateText`, `streamText`, `generateTextWithStreaming`, and `Agent` no longer accept a `skills` argument. Dynamic skill resolvers (sync or async functions) are gone with it. Passing `skills` throws: ``` skills must be set in the prompt file, not as a call argument ``` `skill()` is no longer exported. Colocated `skills/` auto-discovery is gone: a `skills/` folder next to the prompt is not loaded unless you list it in frontmatter. ### Move call-argument and inline skills into the prompt #### Before ```ts theme={null} import { generateText, skill } from '@outputai/llm'; const audienceSkill = skill( { name: 'audience', description: 'Audience voice', instructions: 'Write for operators, not executives.' } ); await generateText( { prompt: 'writer@v1', skills: [ audienceSkill ] } ); ``` #### After Put the instructions in a markdown file and list the path in frontmatter. Paths are relative to the prompt file. ```markdown prompts/skills/audience.md theme={null} --- name: audience description: Audience voice --- Write for operators, not executives. ``` ```yaml prompts/writer@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-6 skills: - ./skills/audience.md --- You are a writer. Use load_skill before applying a skill. {{ task }} ``` ```ts theme={null} import { generateText } from '@outputai/llm'; await generateText( { prompt: 'writer@v1' } ); ``` A directory path loads every `.md` file under it (recursive): ```yaml theme={null} skills: - ./skills ``` A single string is still valid YAML and is coerced to an array at load time: ```yaml theme={null} skills: ./skills/audience.md ``` ### Restore colocated skills that used auto-discovery #### Before ``` prompts/ ├── writer@v1.prompt └── skills/ └── audience.md ``` No `skills:` key in the prompt. Output discovered `./skills` automatically. #### After Keep the folder. Add an explicit path: ```yaml theme={null} skills: - ./skills ``` ## Prompt tools and call-argument tools merge Call-argument `tools` no longer replace the whole prompt YAML tools map. * Prompt YAML tools and call-argument tools are merged. * The same key: the caller wins. * When skills are present, `load_skill` is added last and cannot be overridden. #### Before ```yaml theme={null} tools: googleSearch: {} ``` ```ts theme={null} await generateText( { prompt: 'research@v1', tools: { lookup: lookupTool } } ); ``` `googleSearch` was dropped. Only `lookup` was sent. #### After Both are sent: `{ googleSearch, lookup }`. If you meant to disable YAML tools, remove them from the prompt (or override that key on the call). ## Loaded prompt shape `loadPrompt` returns the parsed prompt object. | v0.11.0 | v0.12.0 | | | - | - | - | | `prompt.promptFileDir` | `prompt.fileDir` (always set) | | | - | `prompt.variables` (`Record`, including nested objects and arrays; default `{}`) | | | `prompt.config.skills` missing, a string, or a string array | Always a `string[]` (`null` / missing -> `[]`, a string -> `[string]`) | | | `prompt.config.maxSteps` missing | Always a positive integer (default 10) | | | `prompt.instructions` missing or omitted | Always \`string | null`(chat prompts are`null\`) | | `message.attributes` (`{ options: 'cached' }` or `{}`) | `message.providerOptions` (resolved set(s); omitted when the tag has no `options`) | | #### Before ```ts theme={null} const prompt = loadPrompt( 'writer@v1' ); const dir = prompt.promptFileDir; ``` #### After ```ts theme={null} const prompt = loadPrompt( 'writer@v1' ); const dir = prompt.fileDir; ``` The `SkillsArg` and `Skill` types are removed. Skills are now internal loaded values; declare file paths in prompt frontmatter instead of constructing or typing skill objects. ### Per-message options resolve at load v0.11 kept the role tag's `attributes` on the loaded message and compiled `options="..."` into AI SDK `providerOptions` at generate time. v0.12 compiles that at `loadPrompt`. LLM traces (`input.prompt.messages`) use the same loaded shape. #### Before ```ts theme={null} const prompt = loadPrompt( 'writer@v1' ); prompt.messages[0].attributes; // { options: 'cached' } ``` #### After ```ts theme={null} const prompt = loadPrompt( 'writer@v1' ); prompt.messages[0].providerOptions; // { anthropic: { cacheControl: { type: 'ephemeral' } } } ``` The only supported role-tag attribute is `options`. Any other attribute throws at load (previously this could fail later, at generate): ``` Error parsing content on prompt "writer@v1": Message has unsupported attributes. The only supported attribute is "options". ``` Unknown `options` names, `options` without a value, and `options` set while `config.messageOptions` is missing or empty also throw at load. ### Prompt message roles are narrowed `PromptMessage.role` is now typed as `'system' | 'user' | 'assistant'` instead of `string`, matching the authored role blocks accepted by `loadPrompt()`. Code that constructs a `PromptMessage` from a dynamic string must validate or narrow the value before assigning it. ### Prompt bodies use explicit parsing modes v0.11 searched the rendered body for supported role blocks wherever they appeared. This could silently ignore text outside those blocks, unknown top-level tags, and malformed attributes. v0.12 selects one mode from the first meaningful token after leading whitespace and HTML comments: * Plain text selects instruction mode. The whole trimmed body becomes `prompt.instructions`, including any tags that appear later. * A tag selects message mode. The complete body is validated as top-level role blocks and `prompt.instructions` is `null`. These modes describe `loadPrompt()` output; API requirements are unchanged. `generateText`, `generateTextWithStreaming`, `streamText`, and `Agent` require message mode, while `generateImage` requires instruction mode. For example, v0.11 extracted the `` block here and discarded the surrounding text: ```text theme={null} Context for the prompt: Summarize {{ article }}. End of prompt. ``` In v0.12 this is one instruction string because it starts with text. To keep message mode, move the text inside the role block: ```text theme={null} Context for the prompt: Summarize {{ article }}. End of prompt. ``` Message mode now enforces these rules: * Top-level blocks must use `system`, `user`, or `assistant`. * Only whitespace and HTML comments may appear between blocks. * Root self-closing tags, unmatched closing tags, and unclosed blocks throw. * Different-name tags inside a message remain literal message content. * A nested non-self-closing tag with the same name as its message throws instead of prematurely closing the outer block. Escape literal examples, such as `<user>example</user>`. * Attribute names, separators, and quotes are validated. Spaces around `=` and `>` inside quoted values are supported; malformed fragments no longer pass silently. Prompt files no longer accept authored `` blocks. Their string content never matched AI SDK's structured tool-result message contract, so text generation rejected them. AI SDK continues to create tool messages during execution, and Agent callers may supply structured tool messages through `messages` or `messageStore`. ## LLM trace details Start-trace `input` on `generateText`, `streamText`, `generateTextWithStreaming`, `generateImage`, and `Agent` (`generate`, `generateWithStreaming`, `stream`) is the loaded prompt object only. Filename, interpolation values, and rendered config live on that object. Agent traces use the same shape as the text APIs (v0.11 recorded only the filename as `prompt`). End-trace `output` keeps the raw AI SDK `usage` and replaces tool-only `sourcesFromTools` with merged `sources` (tool results plus native provider sources; always an array). Normalized usage and cost are stored as trace attributes. ### Start (`input`) | v0.11.0 | v0.12.0 | | - | - | | `prompt` (filename string) | `prompt.name` | | `variables` (sibling) | `prompt.variables` | | `loadedPrompt` (loaded object) | `prompt` | #### Before ```json theme={null} { "prompt": "generate_summary@v1", "variables": { "companyName": "Acme Corp" }, "loadedPrompt": { "name": "generate_summary@v1", "config": { "provider": "anthropic", "model": "claude-sonnet-4-6" } } } ``` #### After ```json theme={null} { "prompt": { "name": "generate_summary@v1", "fileDir": "/prompts", "variables": { "companyName": "Acme Corp" }, "config": { "provider": "anthropic", "model": "claude-sonnet-4-6" } } } ``` If you read `input.prompt` as a filename, use `input.prompt.name`. If you read `input.loadedPrompt`, switch to `input.prompt`. If you read sibling `input.variables`, use `input.prompt.variables`. ### End (`output`) | v0.11.0 | v0.12.0 | | - | - | | `result`, `usage`, `providerMetadata` | same | | `sourcesFromTools` | `sources` (merged tool + provider sources) | #### Before ```json theme={null} { "result": "Acme Corp is a B2B SaaS company...", "usage": { "inputTokens": 38, "outputTokens": 204, "totalTokens": 242 }, "providerMetadata": { "anthropic": {} }, "sourcesFromTools": [] } ``` #### After ```json theme={null} { "result": "Acme Corp is a B2B SaaS company...", "usage": { "inputTokens": 38, "outputTokens": 204, "totalTokens": 242 }, "providerMetadata": { "anthropic": {} }, "sources": [] } ``` If you read `output.sourcesFromTools`, switch to `output.sources`. ### Attributes The raw AI SDK `output.usage` shape remains on the trace output. Normalized usage and cost live under the LLM node's `attributes` object: ```json theme={null} { "llm:generation:usage": { "type": "llm:generation:usage", "providerId": "anthropic", "modelId": "claude-sonnet-4-6", "status": "complete", "input": 38, "output": 204, "total": 242, "items": [ { "group": "input", "label": null, "amount": 38 }, { "group": "output", "label": null, "amount": 204 } ] }, "llm:generation:cost": { "type": "llm:generation:cost", "providerId": "anthropic", "modelId": "claude-sonnet-4-6", "status": "precise", "input": 0.000114, "output": 0.00306, "total": 0.003174, "items": [ { "group": "input", "label": null, "amount": 38, "ppm": 3, "total": 0.000114, "status": "ok" }, { "group": "output", "label": null, "amount": 204, "ppm": 15, "total": 0.00306, "status": "ok" } ] }, "llm:usage": { "type": "llm:usage", "modelId": "claude-sonnet-4-6", "usage": [ { "type": "input", "ppm": 3, "amount": 38, "total": 0.000114 }, { "type": "output", "ppm": 15, "amount": 204, "total": 0.00306 } ], "total": 0.003174, "tokensUsed": 242 } } ``` The legacy `attributes["llm:usage"]` payload remains available for compatibility, so existing trace readers do not need an immediate migration. New integrations should use `attributes["llm:generation:usage"]` and `attributes["llm:generation:cost"]`; these preserve normalized usage independently from pricing and represent detailed dimensions explicitly. The CLI accepts all three keys and prefers the normalized attributes. ### Response source, cost, and metering types `ExtractedSource` now matches the AI SDK source union. A source can be a URL or a document, so narrow on `sourceType` before reading `url`: ```ts theme={null} // Before const urls = response.sources.map(source => source.url); // After const urls = response.sources .filter(source => source.sourceType === 'url') .map(source => source.url); ``` `response.cost` and direct-stream `onEnd` cost now use `LLMGenerationCost | null`. The old `LLMCallCost` type is removed. `@outputai/core` no longer exports the LLM-specific `Attribute.LLMUsage` class or `Attribute.Usage` interface. Core now exposes only the generic `Attribute.BaseAttribute` for package-owned trace attributes. Import `LLMGenerationUsage`, `LLMGenerationCost`, and the deprecated legacy `LLMUsageEvent` type from `@outputai/llm`. In v0.11, `response.cost` used the legacy `llm:usage` shape with priced lines under `usage`. In v0.12, read aggregate costs directly and detailed dimensions from `items`: ```ts theme={null} // Before const cachedInputCost = response.cost?.usage .find(item => item.type === 'input_cached') ?.total; // After const cachedInputCost = response.cost?.items .find(item => item.group === 'input' && item.label === 'cache_read') ?.total; ``` The new object has `type: "llm:generation:cost"`, `providerId`, `modelId`, nullable `input`, `output`, and `total`, a calculation `status`, and one cost item for each normalized usage item. Do not use only `response.cost === null` to detect unavailable totals. Missing model or dimension pricing returns an incomplete `LLMGenerationCost`; check `response.cost?.total == null` or inspect its status and item statuses. `response.cost` itself is `null` when the pricing catalog could not be loaded. `LLMUsageEvent` remains exported from `@outputai/llm` for `cost:llm:request`. Its legacy payload shape remains compatible, but the type is deprecated to guide new integrations toward the more complete metering event. ```ts theme={null} import { on } from '@outputai/core/hooks'; import type { LLMGenerationMeteringEvent } from '@outputai/llm'; on('llm:generation:metering', event => { if (!event.payload) { return; } console.log(event.payload.usage.total, event.payload.cost?.total); }); ``` Use `llm:generation:metering` for new integrations when you need normalized usage and cost data. It fires when usage can be normalized; `event.payload.cost` may be `null` or incomplete. Existing `cost:llm:request` handlers can remain until you choose to adopt the more detailed format. ## AI SDK helpers come from `aiSdk` `@outputai/llm` no longer re-exports `tool`, `Output`, `smoothStream`, `stepCountIs`, `hasToolCall`, or `jsonSchema` as named exports. The namespace re-export `ai` is renamed to `aiSdk`. #### Before ```ts theme={null} import { generateText, Output, stepCountIs, tool } from '@outputai/llm'; await generateText( { prompt: 'writer@v1', output: Output.object( { schema } ), stopWhen: stepCountIs( 1 ), tools: { lookup: tool( { description: 'Lookup', parameters: schema, execute } ) } } ); ``` #### After ```ts theme={null} import { generateText, aiSdk } from '@outputai/llm'; await generateText( { prompt: 'writer@v1', output: aiSdk.Output.object( { schema } ), stopWhen: aiSdk.isStepCount( 1 ), tools: { lookup: aiSdk.tool( { description: 'Lookup', inputSchema: schema, execute } ) } } ); ``` `import { ai } from '@outputai/llm'` becomes `import { aiSdk } from '@outputai/llm'`. Output APIs (`generateText`, `Agent`, `loadPrompt`, ...) stay named exports. Cherry-picked AI SDK type re-exports (`ToolSet`, `FinishReason`, `ModelMessage`, `StreamTextOnChunkCallback`, ...) are also gone. Import those from `ai`, or as `aiSdk.ToolSet`. ### Replace removed Output option types The Output-owned AI SDK option aliases were removed with the unrestricted native arguments. Use the corresponding public parameter type: ```ts theme={null} // Before import type { GenerateTextAiSdkOptions, StreamTextAiSdkOptions, GenerateImageAiSdkOptions } from '@outputai/llm'; // After import type { GenerateTextParameters, StreamTextParameters, GenerateImageParameters } from '@outputai/llm'; ``` `OutputAgentGenerateWithStreamingParameters` no longer accepts an output type argument. Remove the generic: ```ts theme={null} // Before type Options = OutputAgentGenerateWithStreamingParameters; // After type Options = OutputAgentGenerateWithStreamingParameters; ``` ## Call arguments are a fixed list Dropped native AI SDK call arguments from `generateText()`, `generateTextWithStreaming()`, `streamText()`, `generateImage()`, and `Agent`. Calls no longer accept `temperature`, `maxOutputTokens`, `maxTokens`, `maxSteps`, `providerOptions`, image `n`/`size`/`seed`, `experimental_transform`, `onStepFinish`, and similar. Unknown keys throw. Set model and generation or image config (including `maxSteps`, default 10) on the prompt file; call-argument `stopWhen` still overrides it. | Argument | `generateText` | `generateTextWithStreaming` | `streamText` | `generateImage` | | - | - | - | - | - | | `prompt` | required | required | required | required | | `promptDir` | optional | optional | optional | optional | | `variables` | optional | optional | optional | optional | | `tools` | optional | optional | optional | - | | `output` | optional | optional | optional | - | | `toolChoice` | optional | optional | optional | - | | `stopWhen` | optional | optional | optional | - | | `abortSignal` | optional | optional | optional | optional | | `onChunk` | - | optional | optional | - | | `onEnd` | - | - | optional | - | | `onError` | - | - | optional | - | | `images` | - | - | - | optional | | `mask` | - | - | - | optional | | Argument | `new Agent` | `.generate` | `.generateWithStreaming` | `.stream` | | - | - | - | - | - | | `prompt` | required | - | - | - | | `promptDir` | optional | - | - | - | | `variables` | optional | - | - | - | | `tools` | optional | - | - | - | | `output` | optional | - | - | - | | `stopWhen` | optional | - | - | - | | `messageStore` | optional | - | - | - | | `messages` | - | optional | optional | optional | | `abortSignal` | - | optional | optional | optional | | `toolChoice` | - | optional | optional | optional | | `onChunk` | - | - | optional | optional | | `onEnd` | - | - | - | optional | | `onError` | - | - | - | optional | `generateImage` `mask` still requires `images`. `Agent.generate()`, `Agent.generateWithStreaming()`, and `Agent.stream()` append to `messageStore` only when `finishReason` is not `'error'`. Errored turns are not persisted. `streamText()` and `Agent.stream()` now treat `onError` as a fire-and-forget observer. Output maps and forwards the provider error, but exceptions and rejected promises from the callback are ignored. To fail a workflow step with the original error, capture it in `onError` and throw it after consuming the stream. ## Agent message store `conversationStore` is renamed to `messageStore`. The type is `MessageStore`. `createMemoryConversationStore()` is removed; implement the store yourself. #### Before ```ts theme={null} import { Agent, createMemoryConversationStore } from '@outputai/llm'; new Agent( { prompt: 'chatbot@v1', conversationStore: createMemoryConversationStore() } ); ``` #### After ```ts theme={null} import { Agent } from '@outputai/llm'; import type { MessageStore } from '@outputai/llm'; const messages: Parameters[0] = []; const messageStore: MessageStore = { getMessages: () => messages, addMessages: incoming => { messages.push( ...incoming ); } }; new Agent( { prompt: 'chatbot@v1', messageStore } ); ``` ### Move model config onto the prompt #### Before ```ts theme={null} await generateText( { prompt: 'writer@v1', temperature: 0.2, maxSteps: 5, maxRetries: 2 } ); await generateTextWithStreaming( { prompt: 'writer@v1', experimental_transform: aiSdk.smoothStream() } ); ``` #### After ```yaml prompts/writer@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-6 temperature: 0.2 maxSteps: 5 --- ``` ```ts theme={null} await generateText( { prompt: 'writer@v1' } ); ``` Any merged tools, including prompt-only Vertex `googleSearch` / `urlContext`, now get `stopWhen: isStepCount(maxSteps)` from that prompt value. Previously the ceiling applied only when call-argument tools or `load_skill` were present; YAML-only grounding stayed at the AI SDK default of one step. If you need the old one-step grounding behavior, set `maxSteps: 1` on the prompt, or pass `stopWhen` on the call: ```ts theme={null} import { generateText, aiSdk } from '@outputai/llm'; await generateText( { prompt: 'grounded@v1', stopWhen: aiSdk.isStepCount( 1 ) } ); ``` ## Agent constructor validation `new Agent( {} )` no longer throws `Agent requires a prompt`. Invalid constructor args use the same schema as `generateText` and throw `Invalid Agent() arguments`. That includes a missing/empty `prompt`, an empty `promptDir`, and call-argument `skills` or `maxSteps` fields. ## Prompt config is a strict key list Unknown top-level keys on a `.prompt` file now throw `Invalid prompt file`. Previously they were kept on `config` and ignored. `provider` and `model` must be non-empty strings. When provided, `maxOutputTokens` and deprecated `maxTokens` must each be a positive integer. Nested `providerOptions` (including `thinking`) stays open. Allowed top-level keys: `provider`, `model`, `temperature`, `maxOutputTokens`, deprecated `maxTokens`, `topP`, `topK`, `presencePenalty`, `frequencyPenalty`, `stopSequences`, `seed`, `maxSteps`, `skills`, `tools`, `providerOptions`, `messageOptions`, `n`, `maxImagesPerCall`, `size`, `aspectRatio`. `maxTokens` remains available for backward compatibility and is retained on the loaded prompt config. When `maxOutputTokens` is absent, `loadPrompt` also copies the `maxTokens` value to `maxOutputTokens`. When both keys are set, `maxOutputTokens` takes precedence. Text generation APIs read the normalized `maxOutputTokens` value. Snake_case aliases of those keys fail with a suggestion: ``` Invalid prompt file "writer@v1": Unrecognized key: "max_images_per_call". "max_images_per_call" is not valid; use "maxImagesPerCall" ``` Move provider-specific fields under `providerOptions`. `effort` and `reasoningEffort` at the top level are unknown keys; they belong under `providerOptions.anthropic` and `providerOptions.openai`. #### Before ```yaml theme={null} --- provider: openai model: gpt-5.4 reasoningEffort: medium max_output_tokens: 16000 --- ``` #### After ```yaml theme={null} --- provider: openai model: gpt-5.4 maxOutputTokens: 16000 providerOptions: openai: reasoningEffort: medium --- ``` ## Checklist * Delete `skills` from `generateText` / `streamText` / `generateTextWithStreaming` / `Agent` calls. * Remove `skill()`, `Skill`, and `SkillsArg` imports; move inline skills into files listed under prompt `skills:`. * Add `skills: ./skills` (or explicit file paths) to prompts that relied on colocated auto-discovery. * Expect YAML tools and call-argument tools to merge; remove YAML tools if you previously relied on replacement. * Strip dropped call arguments from `generateText` / `generateTextWithStreaming` / `streamText` / `generateImage` / `Agent` (`temperature`, `maxOutputTokens`, `maxTokens`, `maxSteps`, `providerOptions`, `maxRetries`, `experimental_transform`, `onStepFinish`, image `n` / `size` / `seed`, and any other AI SDK-only keys). Unknown keys throw. Put model and generation or image config on the prompt file; call-argument `stopWhen` still overrides `maxSteps`. * Update installed AI SDK packages to `ai` 7.x, OpenAI / Anthropic / Azure / Perplexity 4.x, and Amazon Bedrock / Google Vertex 5.x. * Rename `onFinish` to `onEnd` in `streamText()` and `Agent.stream()`. Rename the corresponding wrapped callback and event types. * Replace `fullStream` with `stream`, and update exhaustive `onChunk` handlers for the expanded AI SDK 7 part union. * Replace `stepCountIs()` with `isStepCount()`. * Review direct AI SDK result-field access against the official AI SDK 7 migration guide. * Use `group` and `label` when reading normalized `LLMGenerationUsage` and `LLMGenerationCost` items. Legacy event lines retain their existing type names. * Remove assumptions that Output's `Agent` inherits from AI SDK's `ToolLoopAgent`. * Preserve binary file and `reasoning-file` content parts in custom `MessageStore` serializers. * Set `providerOptions.openai.reasoningSummary: null` on reasoning prompts that should not return summaries. * Set `maxSteps: 1` on YAML-only grounding prompts that must stay one-shot, or pass `stopWhen: aiSdk.isStepCount(1)` on the call. * Rename `promptFileDir` to `fileDir`. Read interpolation values from `prompt.variables`. * Treat `config.skills` as always `string[]` after `loadPrompt`. * Treat `config.maxSteps` as always a positive integer after `loadPrompt` (default 10). * Treat `prompt.instructions` as always `string | null` after `loadPrompt` (chat prompts are `null`). * Read `message.providerOptions` instead of `message.attributes` on `loadPrompt` results and LLM trace `input.prompt.messages`. * Narrow dynamic role strings before assigning them to `PromptMessage.role`; the type now accepts only `'system'`, `'user'`, and `'assistant'`. * Remove unknown attributes from role tags (`name`, `id`, `pinned`, ...). Only `options` is allowed; extras throw at `loadPrompt`. * Remove authored `` blocks from prompt files; pass structured tool history through Agent `messages` or `messageStore`. * Audit prompt bodies that put prose before the first role tag. They now load as instructions; move the prose inside a role block to keep message mode. * Remove text between or after top-level role blocks. Only whitespace and HTML comments are allowed there. * Escape literal same-name role tags inside messages (`<user>...</user>`). Different-name semantic tags remain valid content. * Give every `options` attribute a value and fix malformed attribute names or quotes; prompt markup now fails explicitly at load. * Read LLM trace `input.prompt` as the loaded prompt object (`input.prompt.name`, `input.prompt.variables`). Do not treat `input.prompt` as a filename or read `input.loadedPrompt`. * Read LLM trace `output.sources` instead of `output.sourcesFromTools`. * Keep existing `llm:usage` trace readers for compatibility, but prefer `llm:generation:usage` and `llm:generation:cost` for normalized trace metadata. * Narrow `ExtractedSource` on `sourceType` before reading `url`. Replace `LLMCallCost` with `LLMGenerationCost`, replace `response.cost.usage` reads with `response.cost.items`, and handle an incomplete cost whose `total` is `null`. Import LLM generation usage and cost types from `@outputai/llm`, not `@outputai/core`. * Keep existing `cost:llm:request` handlers for structural compatibility, while allowing corrected reasoning values. Prefer `llm:generation:metering` with `LLMGenerationMeteringEvent` for new normalized usage/cost integrations. * Import AI SDK helpers and types from `aiSdk` (`aiSdk.Output`, `aiSdk.tool`, `aiSdk.isStepCount`, `aiSdk.ToolSet`, ...). Replace `import { ai }` with `import { aiSdk }`. Do not import cherry-picked AI SDK types from `@outputai/llm`. * Replace `GenerateTextAiSdkOptions`, `StreamTextAiSdkOptions`, and `GenerateImageAiSdkOptions` with their `*Parameters` equivalents. Remove the generic from `OutputAgentGenerateWithStreamingParameters`. * Expect `Agent.generate()`, `Agent.generateWithStreaming()`, and `Agent.stream()` to persist message-store history only when `finishReason` is not `'error'`. * Replace `conversationStore` with `messageStore`. Replace `ConversationStore` with `MessageStore`. Remove `createMemoryConversationStore()` and pass your own store. * Update Agent tests and error matchers that expected `Agent requires a prompt`. * Ensure prompt `provider` and `model` values are non-empty. If set, `maxOutputTokens` and deprecated `maxTokens` must each be positive integers. * Review prompt frontmatter against the supported configuration and remove unsupported fields. Any remaining fields cause an Invalid prompt file error. # v0.12.0 → v0.13.0 Source: https://docs.output.ai/migrations/v0.12.0-to-v0.13.0 Upgrading Output.ai projects from v0.12.0 to v0.13.0: worker shutdown defaults, worker exit codes, the catalog startup gate in @outputai/core, and LLM cost during a pricing outage. This guide covers behavior changes in the `@outputai/core` worker and in `@outputai/llm` cost reporting. Nothing in your code needs to change, but four runtime behaviors differ: the worker now bounds its own shutdown, every way it can end now has a defined outcome and exit code, a worker refuses to start unless it can publish a catalog matching its own source code, and LLM costs fall back to a bundled pricing snapshot instead of coming back empty. ## Worker shutdown is now bounded `TEMPORAL_SHUTDOWN_GRACE_TIME` and `TEMPORAL_SHUTDOWN_FORCE_TIME` have defaults, and the previously hardcoded hook flush allowance is now `OUTPUT_HOOK_FLUSH_TIMEOUT_MS`: | Variable | v0.12.0 | v0.13.0 | Meaning | | - | - | - | - | | `TEMPORAL_SHUTDOWN_GRACE_TIME` | unset (Temporal default `0`) | `15s` | How long in-flight activities run before they are asked to cancel | | `TEMPORAL_SHUTDOWN_FORCE_TIME` | unset (no force termination) | `20s` | How long the worker drains before it gives up and terminates | | `OUTPUT_HOOK_FLUSH_TIMEOUT_MS` | hardcoded `30000` | `5000` | How long pending hook callbacks are awaited once the drain is over | Previously the worker never force-terminated: it waited indefinitely for in-flight activities and was stopped only when the platform sent `SIGKILL`, which meant the hook flush was never reached at all on a deploy that caught in-flight work. It now stops draining after `20s` and exits under its own control with code `1` - closing its Temporal connection, flushing hooks, and logging first. For most projects this is an improvement, because activities get 15 seconds of runway instead of being asked to cancel the instant a deploy starts, and buffered hook data actually gets written. ### The three values are one budget The drain runs to `TEMPORAL_SHUTDOWN_FORCE_TIME` and only then does the flush start, so the worst-case shutdown is force time plus flush timeout. That total has to fit inside the window your platform allows between `SIGTERM` and `SIGKILL`. The defaults total 25 seconds against the 30 seconds most platforms allow, leaving 5 seconds of margin. The hook flush is the part to watch when retuning. It used to be 30 seconds, which on a default platform window could not complete; it is now 5 seconds, which fits. Five seconds is ample for handlers that write to stdout or an in-process buffer, which is what hook handlers should be doing - they all share this one budget, so a single handler awaiting remote I/O spends the allowance the others need. If you do have a handler that must await a network round trip, batch it and raise both this value and your platform's window, in that order. ### Set the values explicitly if your activities drain slowly If your activities routinely run longer than 20 seconds and you raised your platform's shutdown window to accommodate them, set the variables explicitly. Otherwise those activities are cancelled at 15 seconds and abandoned at 20 on every deploy, then retried on the new instance. Keep grace below force, and force plus flush below your platform's shutdown window, so the worker always exits before it is killed: ```bash theme={null} # Platform allows 300s between SIGTERM and SIGKILL TEMPORAL_SHUTDOWN_GRACE_TIME=280s TEMPORAL_SHUTDOWN_FORCE_TIME=285s OUTPUT_HOOK_FLUSH_TIMEOUT_MS=10000 ``` Values above your platform's window never take effect, since the platform terminates the process first. On Render that window is `maxShutdownDelaySeconds`, which defaults to 30 seconds and can be raised to 300. On Kubernetes it is `terminationGracePeriodSeconds`. Raising these only extends shutdowns started by a signal. When an uncaught exception or unhandled rejection starts the shutdown instead, the worker force quits 60 seconds later regardless of `TEMPORAL_SHUTDOWN_FORCE_TIME`, exiting `1` after logging `Uncaught exception handling timed out, force quitting...`. That cap is fixed, so a force time above 60 seconds only fully applies to signal shutdowns. An empty value falls back to the default rather than disabling the bound, so there is no longer a way to configure an unbounded drain. ## Shutdown scenarios Every path that ends the worker changed shape. The exit code is also explicit now: v0.12.0 only called `process.exit` on the failure path and let the event loop empty on the success path. | Scenario | v0.12.0 | v0.13.0 | | - | - | - | | `SIGTERM`, `SIGINT` or `SIGUSR2` while polling | Stops polling and asks in-flight activities to cancel at once, then waits for them for as long as they take. Exits `0` | Stops polling and lets in-flight activities run for `TEMPORAL_SHUTDOWN_GRACE_TIME` before asking them to cancel. Exits `0` | | In-flight work outlives the drain | Nothing bounds it, so the worker waits until the platform sends `SIGKILL` and the hook flush is never reached. Exit code is whatever the platform reports | Stops draining at `TEMPORAL_SHUTDOWN_FORCE_TIME`, warns with `Stopping Worker error`, flushes hooks. Exits `1` | | A signal during startup | No handler was installed until the worker had been built, so the process died on the spot with no teardown and no hook flush. Exits `128 + signal number`, `143` for `SIGTERM` | The handler is installed first, so startup stops at the next step, services are torn down and hooks flush. Exits `0` | | A second signal, more than a second after the first | Force quits on the spot, abandoning the drain. Exits `1` | Unchanged | | A service other than the worker fails to stop | Warns and carries on with the rest of the teardown. Exit code unaffected | Unchanged | | Uncaught exception or unhandled rejection | Not handled, so Node printed the stack and terminated immediately: no drain, no hook flush, no `onError` hook. Exits `1` | Drains exactly like a signal, emits `RUNTIME_ERROR` so `onError` hooks fire, flushes hooks. Exits `1` | | An uncaught error whose drain stalls | Not applicable, there was no drain | Force quits 60 seconds after the error. Exits `1` | | The Temporal connection is lost | Drains, then reports the loss. Exits `1` | Unchanged | | The worker fails to stop | Drains what it can, then reports the failure. Exits `1` | Unchanged | | The catalog cannot be published | The catalog ran alongside the worker, so the worker was already polling against a stale catalog when the failure surfaced. Exits `1` | The catalog gates the worker: it retries twice and never starts polling. Exits `1` | | Startup fails to load, bundle or connect | Tears down whatever was built. Exits `1` | Unchanged | If you alert on non-zero worker exits, the situations that produce one changed. A drain that outlives its window is now one of them, where v0.12.0 hung until the platform stepped in, so expect an exit `1` from any deploy that lands on work longer than `TEMPORAL_SHUTDOWN_FORCE_TIME`. Nothing in the logs separates it from another failure to stop: the `Stopping Worker error` warning reports `IllegalStateError: Worker still in use`, because the forced termination leaves in-flight polls behind, and Temporal's own `Worker failed` line serializes its error as empty. Treat a non-zero exit on a deploy you triggered as routine. An uncaught error still exits `1`, but now only after draining. Two log lines moved with this. The failure log is now `Worker error` rather than `Fatal error`, and the last line is always `Bye`, where a failing worker used to end on `Exiting...`. ## Workers exit when the catalog does not match The worker publishes its catalog during startup and treats it as a gate. If it cannot publish a catalog matching its own source code, it retries twice and then exits rather than serving requests against an outdated catalog. A worker that would previously have started with a stale catalog now fails its deploy instead. The failure is logged as `Worker error` with the underlying Temporal error. Reconciliation also changed: a stale catalog workflow is now terminated rather than asked to complete. A catalog that stopped processing workflow tasks no longer blocks every deploy that follows it. ## LLM cost survives a pricing outage `@outputai/llm` now ships a snapshot of the pricing table. When the live catalog is unreachable and nothing is cached, costs are calculated from that snapshot instead of coming back as `null`, and are reported with `status: "imprecise"` and `pricingFreshness: "snapshot"`. If you branch on `cost === null` to skip cost accounting during an outage, that branch stops firing and you start recording snapshot-derived figures instead. Check `pricingFreshness` or `status` for that case. `cost` is still `null` when usage cannot be normalized, and a provider or model missing from the table still produces a non-null, incomplete cost. ## Checklist * Set `TEMPORAL_SHUTDOWN_GRACE_TIME`, `TEMPORAL_SHUTDOWN_FORCE_TIME` and `OUTPUT_HOOK_FLUSH_TIMEOUT_MS` explicitly if your activities need more than 20 seconds to drain, keeping force time plus flush timeout under your platform's shutdown window. * Raise `OUTPUT_HOOK_FLUSH_TIMEOUT_MS` if your hook callbacks do real I/O, since the allowance dropped from a hardcoded 30 seconds to 5. * Update alerts that key off worker exits or the `Fatal error` log line, which is now `Worker error`. * Expect a worker whose catalog cannot be published to exit instead of starting with a stale catalog. * Replace any `cost === null` check used to detect a pricing outage with a `pricingFreshness` or `status` check. # v0.13.0 → v0.14.0 Source: https://docs.output.ai/migrations/v0.13.0-to-v0.14.0 Upgrading Output.ai projects from v0.13.0 to v0.14.0: failed and aborted LLM calls now report the usage and cost they already spent, and trace node ids for steps and activities changed shape. This guide covers a billing behavior change in `@outputai/llm`: LLM calls that fail after the model ran now report usage and cost instead of reporting nothing, so the same traffic produces more metering events and a higher total. One smaller break comes with it: a failure in the SDK's own response handling is no longer retryable. A separate change in `@outputai/core` affects anything that reads trace files: step, evaluator, and internal activity nodes have a new `id` shape. See [Trace node ids](#trace-node-ids) at the end of this guide. ## What changed Usage and cost used to be read from the value a call returned. A call that threw returned nothing, so everything it had already spent went unreported - even when the provider had answered and the failure came afterwards, in output validation, in the tool loop, or in your own code. Usage is now collected from the AI SDK lifecycle events as the call progresses, so billing no longer depends on reaching a return statement. Every generation that produced at least one completed step reports what that step cost, whether the call ends with a response, an error, or an abort. Nothing changed in the shape of `LLMGenerationUsage`, `LLMGenerationCost`, the `llm:generation:usage` / `llm:generation:cost` trace attributes, or the `llm:generation:metering` and `cost:llm:request` events. A failing call still throws, and the thrown error still carries no cost - the numbers reach the trace and the events only. Response sources are now filtered on the way out: entries carrying neither a url nor an id are dropped, and a malformed `sources` payload is logged and yields no sources instead of failing the call. Sources that survive are returned exactly as the AI SDK produced them. ## Where cost is now recovered ### `generateText` / `Agent.generate` * Output or schema validation failure after the model answered (`NoObjectGeneratedError`, `NoOutputGeneratedError`) * Tool loop failing after at least one step finished * Your own post-response code throwing, including an `Agent.generate` message store failure * Abort after at least one step finished ### `generateTextWithStreaming` / `Agent.generateWithStreaming` * Provider error part mid stream, once the stream closes * Abort mid stream, after at least one step finished * Output parse or validation failure on the structured output * Message store failure after the stream finished (`Agent.generateWithStreaming`) ### `streamText` / `Agent.stream` * Error part that ends the run with steps already collected * Abort after at least one step finished ## Where it still is not Nothing was spent, or nothing was reported, so there is nothing to bill: * Any failure before the first step completes: authentication, a rejected request, an unknown model or provider, a connection error * An abort before the first step completes, for every method * A provider that stalls without closing the stream after a failure, if the step events had not arrived before the stream went quiet for 250 ms (`generateTextWithStreaming`, `Agent.generateWithStreaming`) * A `streamText` consumer that abandons the stream instead of reading it * `generateImage`, which has no step loop: a failure there always precedes any usage ## Migration steps ### Re-baseline cost dashboards and budgets Totals rise for unchanged traffic, by the cost of failures that were previously invisible. The size of the shift depends on how often your workflows hit the paths above - a workflow with a strict output schema and a retrying activity can move noticeably, since each attempt bills the tokens it spent. If you alert on a cost threshold, expect the step change at the upgrade and reset the baseline rather than treating it as a spike. ### Expect metering events on failed runs Code that assumed a `llm:generation:metering` or `cost:llm:request` event implies a successful generation no longer holds. Billing is emitted once per call, and per attempt when an activity retries. To distinguish the two cases, read the trace: an LLM event that also carries an error is a failed call that still spent tokens. ### Re-check retries around response-handling failures A failure in the SDK's own response handling - reading the model response, merging sources, building the returned proxy - now throws a non-retryable `FatalError` wrapping the original error, where before the original error surfaced unchanged. Such a failure is deterministic, so a retry pays for the model call again and fails the same way; an activity that used to recover on a later attempt now fails permanently. Errors from the provider and from the AI SDK are unaffected and stay as retryable as they were. The generic streaming error messages were normalized at the same time: `Streaming generation aborted.` is now `Streaming aborted.`, `Streaming generation failed.` is now `Streaming failed.`, and both `Streaming generation completed without a response.` and `Agent streaming generation completed without a response.` are now `Streaming completed without a response.`. They only appear when the AI SDK reports a failure that carries no error of its own, so this matters only to code matching on the text. ### Nothing to change in call sites No signatures, options, or return shapes changed, and `cost` on a returned response behaves as before. The only code-level effect is the one above: the retry semantics of a response-handling failure. ## Trace node ids In trace files, the `id` of step, evaluator, and internal activity nodes was Temporal's activity id. It is now `::`: ```json theme={null} "id": "019a3c1f-8e4d-7a52-b0c6-1f7d9e2a4b83:2:1" ``` Temporal numbers activity ids per workflow run and reuses them on retry, so the old ids were not unique within a trace file. Entries that collided were merged into one node, which was then listed once per colliding entry. A retried step reported only its last attempt's input, error, and timing while carrying every attempt's LLM and HTTP calls as its children, and a child workflow's step appeared a second time directly under the root, overwriting whatever the root's own activity with that number was. Two visible differences in new traces: * A retried step appears once per attempt, as sibling nodes sharing the same `name`. A step that failed twice before succeeding is three nodes, not one. * A child workflow's steps appear only inside that child workflow's node. Reported cost is unchanged. Duplicated nodes were already ignored by id when costs were summed, so the same generations are counted, once each. ### Update readers that key on node ids Code that treats a step's `id` as Temporal's activity id needs to change. Run ids contain no colon, so splitting the `id` on `:` always yields three parts and the activity id is the middle one. Prefer matching on `name` and the enclosing workflow node where you can, since that does not depend on the id format. Code that reads a step's `children` to reason about a run should expect them spread across one node per attempt rather than pooled on a single node. `output workflow debug`, `output workflow cost`, and `output workflow dataset generate` need no changes. The run detail view lists one entry per attempt, so a retried step appears more than once. # v0.14.0 → v0.15.0 Source: https://docs.output.ai/migrations/v0.14.0-to-v0.15.0 Upgrading Output.ai projects from v0.14.0 to v0.15.0: @outputai/credentials is folded into @outputai/core, the onBeforeWorkerStart hook is removed, and credentials errors are no longer retried. This guide covers the move of `@outputai/credentials` into `@outputai/core`. The package is no longer published: its API now lives at `@outputai/core/credentials`, and the worker resolves `credential:` env refs on its own, so the hook file that used to wire it up must go. Two smaller breaks come with it: the `onBeforeWorkerStart` hook is removed, and credentials errors are now non-retryable. ## What changed * `@outputai/credentials` is replaced by the `@outputai/core/credentials` subpath. Nothing else needs installing: `@outputai/core` (and `@outputai/output`, which depends on it) ships it. * Importing the package no longer has a side effect. The worker resolves `credential:` env refs itself, after hook files, workflows, and activities are loaded and before the Temporal worker starts. * The encrypted YAML provider is the default. `setProvider()` is only needed to plug in a custom provider. * The exports were trimmed to what projects use. See [Removed exports](#removed-exports). * `MissingKeyError`, `MissingCredentialError`, `InvalidCredentialsKeyError`, and `MalformedCredentialsKeyError` now extend `FatalError`. * A missing or invalid key while resolving `credential:` env refs now stops the worker at startup. Before, the error was logged and the worker started with the refs unresolved. * `onBeforeWorkerStart` is removed from `@outputai/core/hooks`. ## Migration steps ### Remove the credentials hook file entry Projects scaffolded before v0.15.0 list a hook file from the credentials package in `package.json`: ```json theme={null} { "outputai": { "hookFiles": [ "node_modules/@outputai/credentials/dist/hooks.js" ] } } ``` The file no longer exists, so the worker fails to start while the entry is there. Remove it by hand, or run: ```bash theme={null} npx output fix ``` `output fix` drops every `outputai.hookFiles` entry pointing into `@outputai/credentials`. ### Delete hook files that only import the package Some projects register credentials with a hook file of their own instead: ```ts theme={null} // src/hooks/register_credentials.ts import '@outputai/credentials'; ``` If that is all the file does, delete it and remove its entry from `outputai.hookFiles`. If it does more, remove only the import. ### Update imports Replace every import of `@outputai/credentials` with `@outputai/core/credentials`, including module mocks in tests: ```ts theme={null} // Before import { credentials } from '@outputai/credentials'; vi.mock( '@outputai/credentials', () => ( { credentials: { get: vi.fn() } } ) ); // After import { credentials } from '@outputai/core/credentials'; vi.mock( '@outputai/core/credentials', () => ( { credentials: { get: vi.fn() } } ) ); ``` ### Remove the dependency Delete `@outputai/credentials` from `dependencies`, `devDependencies`, and `peerDependencies` in `package.json`, then reinstall. If your project depends on `@outputai/core` directly rather than through `@outputai/output`, bump it to `0.15.0`. ### Removed exports | Removed | Use instead | | - | - | | `getProvider` | Keep a reference to the provider you pass to `setProvider()` | | `encryptedYamlProvider` | Nothing - it is the default provider, so drop the `setProvider( encryptedYamlProvider )` call | | `GlobalContext`, `WorkflowContext` | `Parameters[0]` and `Parameters[0]` | ### Replace `onBeforeWorkerStart` The hook existed to resolve `credential:` env refs, which the worker now does directly. Move any other handler body to the top level of its hook file, where it runs when the worker loads the file: ```ts theme={null} // Before import { onBeforeWorkerStart } from '@outputai/core/hooks'; onBeforeWorkerStart( () => { setupMetrics(); } ); // After setupMetrics(); ``` Hook files load before `credential:` env refs are resolved. A handler that read a resolved env var such as `process.env.ANTHROPIC_API_KEY` sees the raw `credential:...` value at the top level. Read the secret with `credentials.get()` instead, or defer the read until first use. ### Re-check retries around credentials errors A step that fails on a missing key, a key that cannot decrypt the file, a malformed key, or a missing required credential now fails on its first attempt instead of running through its retry policy. These failures are deterministic, so retries could not succeed. If you relied on a retry to pick up a key deployed mid-run, restart the workflow after deploying the key instead. ### Make sure the worker has its key If your `.env` uses `credential:` refs, the worker now exits at startup when the matching key is missing or wrong. Set `OUTPUT_CREDENTIALS_KEY` (or `OUTPUT_CREDENTIALS_KEY_`) or provide the key file before deploying. See [Credentials](/packages/core/credentials#deploying-to-production). # v0.15.0 → v0.16.0 Source: https://docs.output.ai/migrations/v0.15.0-to-v0.16.0 Upgrading Output.ai projects from v0.15.0 to v0.16.0: package consolidation, new peer dependencies, provider-native web search costs, HTTP response parsing changes, and worker concurrency defaults. This guide covers the move of `@outputai/http`, `@outputai/llm` and `@outputai/evals` into `@outputai/core`. None of these packages is published anymore: their APIs now live at `@outputai/core/http`, `@outputai/core/llm` and `@outputai/core/evals`. The http and llm exports are unchanged; the evals LLM judges moved to `@outputai/core/llm`, and the evals internals are no longer exported. The `@outputai/output` umbrella package is not published anymore either: projects depend on `@outputai/core` and `@outputai/cli` directly. Smaller breaks come with them: `ky`, `undici` and `ai` are now peer dependencies of `@outputai/core`, the AI SDK provider packages are no longer installed for you, provider-native web search charges are included in normalized LLM costs, and `sendHttpRequest()` parses some response bodies differently. Separately, the worker no longer sets defaults for two workflow concurrency variables, and one telemetry field is renamed. See [Worker defaults and telemetry](#worker-defaults-and-telemetry). ## What changed * `@outputai/http` is replaced by the `@outputai/core/http` subpath. `outputFetch`, `createKyClient`, `addRequestCost`, and the `ky` and `undici` re-exports are unchanged. * `@outputai/llm` is replaced by the `@outputai/core/llm` subpath. `generateText`, `generateTextWithStreaming`, `streamText`, `generateImage`, `Agent`, `loadPrompt`, `registerProvider`, `getProviderNames`, and the `aiSdk` re-export are unchanged. * `@outputai/evals` is replaced by the `@outputai/core/evals` subpath. `evalWorkflow`, `verify`, `Verdict`, `VERDICT`, `CRITICALITY`, `DatasetSchema`, `EvalOutputSchema`, and the eval types are unchanged. * `judgeVerdict`, `judgeScore`, `judgeBoolean`, `judgeLabel`, and the `JudgeArgs` type moved to `@outputai/core/llm`, with the same arguments and results. * `interpretResult`, `aggregateCaseVerdict`, `renderEvalOutput`, `computeExitCode`, `getEvalWorkflowName`, `isEvalWorkflow`, `getParentWorkflowName`, and the other Zod schemas of `@outputai/evals` (`VerdictSchema`, `CriticalitySchema`, `InterpretConfigSchema`, `EvaluatorResultSchema`, `EvalCaseSchema`, `LastOutputSchema`, `LastEvalSchema`) are no longer exported. * Steps and evaluators referenced as values in workflow files, rather than called, are replaced with their activity names in the workflow bundle. Previously their modules were bundled into the workflow sandbox when the file had no activity calls. * The `output-workflow-bundle` package export condition is no longer used when bundling workflows. Packages resolve through their `import`, `module`, `webpack` or `default` conditions. * `@outputai/output` is no longer published. New projects depend on `@outputai/core` and, as a dev dependency, `@outputai/cli`. `output fix` replaces an existing `@outputai/output` dependency with both. * `zod` (`>=4.6.6 <5`), `ky` (`>=2 <3`), `undici` (`>=8.12.2 <9`) and `ai` (`>=7 <8`) are peer dependencies of `@outputai/core`. * The built-in AI SDK provider packages are optional peer dependencies of `@outputai/core`, so they are no longer installed automatically. Using a provider whose package is missing throws a `FatalError` naming the package. * `getProviderNames()` lists only the built-in providers whose package is installed, plus registered ones. * Normalized LLM metering records Anthropic and OpenAI native web searches as `tools` usage and includes their charges in `cost.tools` and `cost.total`. * Google Vertex grounding pricing now includes Gemini 4 per-query charges. Existing Gemini 2 prompt pricing and Gemini 3 query pricing remain supported. * Context-tiered LLM models are priced separately for each provider request. Normalized cost items can repeat a `group` and `label` with different rates and tiers. * The legacy `cost:llm:request` event and `llm:usage` trace attribute remain token-only and unchanged. * `sendHttpRequest()` returns XML, form-urlencoded, and JavaScript response bodies as text instead of base64, and returns empty or invalid JSON bodies as raw text instead of throwing. * With `OUTPUT_TRACE_HTTP_VERBOSE` on, HTTP request and response bodies in trace files are parsed the same way as `sendHttpRequest()`. Multipart bodies are stored as base64. * Step and workflow failures no longer duplicate the error as their own `ApplicationFailure` cause. API responses, traces and logs expose one fewer level in the cause chain. ## Migration steps ### Update imports Replace every import of `@outputai/http` with `@outputai/core/http`, every import of `@outputai/llm` with `@outputai/core/llm`, and every import of `@outputai/evals` with `@outputai/core/evals`, including module mocks in tests. Import the LLM judges from `@outputai/core/llm`: ```ts theme={null} // Before import { createKyClient, addRequestCost } from '@outputai/http'; import { generateText, aiSdk } from '@outputai/llm'; import { verify, Verdict, judgeVerdict } from '@outputai/evals'; vi.mock( '@outputai/http', () => ( { outputFetch: vi.fn() } ) ); vi.mock( '@outputai/llm' ); // After import { createKyClient, addRequestCost } from '@outputai/core/http'; import { generateText, aiSdk, judgeVerdict } from '@outputai/core/llm'; import { verify, Verdict } from '@outputai/core/evals'; vi.mock( '@outputai/core/http', () => ( { outputFetch: vi.fn() } ) ); vi.mock( '@outputai/core/llm' ); ``` If you used one of the exports that were removed from `@outputai/evals`, copy its logic into your project. `output workflow test` still interprets, aggregates and renders eval results the same way. ### Replace `@outputai/output` If your project depends on `@outputai/output`, replace it with `@outputai/core` in `dependencies` and `@outputai/cli` in `devDependencies`: ```jsonc theme={null} // Before "dependencies": { "@outputai/output": "0.15.0" } // After "dependencies": { "@outputai/core": "0.16.0" }, "devDependencies": { "@outputai/cli": "0.16.0" } ``` `npx @outputai/cli@0.16.0 fix` makes this change for you, keeping the version you had. Bump both packages to `0.16.0` afterwards. ### Remove the dependencies Delete `@outputai/http`, `@outputai/llm` and `@outputai/evals` from `dependencies`, `devDependencies`, and `peerDependencies` in `package.json`. Bump `@outputai/core` and `@outputai/cli` to `0.16.0`. ### Install the peer dependencies npm 7+ and pnpm install required peer dependencies automatically. With other package managers, or if your install reports missing peers, add them yourself: ```bash theme={null} npm install zod@^4.6.6 ky@2 undici@^8.12.2 ai@7 ``` If your project already depends on `zod`, `ky`, `undici` or `ai`, make sure the versions fall in the supported ranges. ### Install the AI SDK providers you use The provider packages are optional peers, so no package manager installs them for you. Add the ones your prompts reference in their `provider` field: | `provider` | Package | | - | - | | `amazon-bedrock` | `@ai-sdk/amazon-bedrock@5` | | `anthropic` | `@ai-sdk/anthropic@4` | | `azure` | `@ai-sdk/azure@4` | | `google-vertex` | `@ai-sdk/google-vertex@5` | | `openai` | `@ai-sdk/openai@4` | | `perplexity` | `@ai-sdk/perplexity@4` | For example, a project with Anthropic and OpenAI prompts: ```bash theme={null} npm install @ai-sdk/anthropic@4 @ai-sdk/openai@4 ``` A prompt that uses a provider whose package is missing fails with `Provider "" requires the "" package, which is not installed`. Providers added with `registerProvider()` are not affected. ### Re-check normalized LLM metering If you consume the `llm:generation:metering` event or the `llm:generation:usage` and `llm:generation:cost` trace attributes, account for native web search tool items: * Anthropic searches use the `web_search` label. * OpenAI searches use `web_search` or `web_search_preview`. An ambiguous variant is retained as unpriced `web_search_unknown`. * Tool charges appear in `cost.tools` and are included in `cost.total`. Code that expects only token items or calculates token spend from `cost.total` must handle them separately. * For context-tiered models, aggregate matching `items` instead of using `find()`: multi-step calls can contain the same `group` and `label` at different `ppm` and `tier` values. * `LLMGenerationCostItemStatus` now includes `uncertain` for items whose applicable tier cannot be determined precisely. Update exhaustive switches over this union. The legacy `cost:llm:request` event and `llm:usage` trace attribute still exclude tool charges. ### Re-check `sendHttpRequest()` response bodies This only affects calls with `responseOptions.includeBody: true`: | Response | Before | After | | - | - | - | | `application/xml`, `*+xml` | base64 string | text | | `application/x-www-form-urlencoded` | base64 string | text | | `application/javascript` | base64 string | text | | JSON content type with an empty body | throws | `''` | | JSON content type with an invalid body | throws | raw text | Remove any base64 decoding of those content types. If you relied on the error to detect a bad JSON response, check whether `body` is a string instead. ### Re-check trace file readers If you parse trace files recorded with `OUTPUT_TRACE_HTTP_VERBOSE` on, request and response bodies now follow the table above, and multipart request bodies are base64 strings. ## Worker defaults and telemetry No code changes are needed, but the worker behaves differently if you never set its concurrency variables, and one telemetry field is renamed. ### Workflow concurrency defaults The worker no longer sets defaults for these two variables. When they are unset, `@temporalio/worker` applies its own: | Variable | v0.15.0 | v0.16.0 | | - | - | - | | `TEMPORAL_MAX_CACHED_WORKFLOWS` | `1000` | Sized from the isolate's heap limit | | `TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS` | `200` | `40` | The cache size is `(heap limit in MiB - 200) * 600 / 1024`, with a minimum of 10. With `--max-old-space-size=4096` that is about 2,400 cached workflows. The formula assumes roughly 600 cached workflows per GB of heap, so if your workflows hold large inputs, outputs, or step results, set `TEMPORAL_MAX_CACHED_WORKFLOWS` explicitly. If you relied on 200 concurrent workflow tasks, set `TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS=200`. Keep it at or below `TEMPORAL_MAX_CACHED_WORKFLOWS`. The resolved values are logged at startup in the `Worker sizing` record, as `maxCachedWorkflows` and `workflowTaskSlots`. ### New startup warnings After the `Worker sizing` record, the worker logs a warning in either or both of these cases, each with the values it compared: | Warning | Cause | Fix | | - | - | - | | `Worker isolates may commit more heap than the host allows` | The heap limit times the isolate count exceeds the container's memory limit, or the machine's when there is no container. A `NODE_OPTIONS` heap cap applies to each isolate, and the worker runs one on its main thread plus one per workflow thread. | Lower the `NODE_OPTIONS` heap cap so the isolate count times the cap fits. | | `Worker runs more workflow tasks than it can cache, forcing replays` | `TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS` resolves above `TEMPORAL_MAX_CACHED_WORKFLOWS`. | Lower the task executions or raise the cache. | A project that only set `TEMPORAL_MAX_CACHED_WORKFLOWS` below `40` will now see the second warning, because task executions default to `40`. See [Memory and Isolates](/operations/worker-tuning#memory-and-isolates). A Dockerfile copied from an earlier version of the [Railway](/operations/deployment/railway) or [Render](/operations/deployment/render) guide sets `--max-old-space-size-percentage=80`, which triggers the first warning because the worker runs two isolates by default. Those guides now use `40`. ### Telemetry field rename If you enable `OUTPUT_WORKER_TELEMETRY_INTERVAL_MS` and parse the periodic `Worker` log, `memory.constrainedMemory` is now `memory.memoryLimit`. The old field reported `process.constrainedMemory()` directly, which returns a sentinel near 2^64 when the process has no memory limit. `memoryLimit` reports the container's limit, or the machine's total memory when there is none. Two fields were added to the same block: `memory.nonMainHeap` (`rss - heapUsed`) and `memory.heapSizeLimit`. ## Checklist * Replace the `@outputai/output` dependency with `@outputai/core` and, as a dev dependency, `@outputai/cli`, both at `0.16.0`. * Replace `@outputai/http` imports and mocks with `@outputai/core/http`, and remove the dependency. * Replace `@outputai/llm` imports and mocks with `@outputai/core/llm`, and remove the dependency. * Replace `@outputai/evals` imports and mocks with `@outputai/core/evals`, import the judges from `@outputai/core/llm`, and remove the dependency. * Install `zod@^4.6.6`, `ky@2`, `undici@^8.12.2` and `ai@7` if your package manager does not install peer dependencies. * Install the `@ai-sdk/*` provider packages your prompts use. * Update normalized LLM metering consumers to handle native web search tool items and charges. * Remove base64 decoding of XML, form-urlencoded, and JavaScript response bodies from `sendHttpRequest()`. * Update API response, trace and log consumers that read the previous duplicated failure cause level. * Set `TEMPORAL_MAX_CACHED_WORKFLOWS` and `TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS` explicitly if you relied on the old defaults or your workflows hold large state. * Lower `--max-old-space-size-percentage` to `40` if your Dockerfile uses the earlier Railway or Render value of `80`. * Rename `memory.constrainedMemory` to `memory.memoryLimit` in anything that parses worker telemetry. # v0.16.0 → v0.17.0 Source: https://docs.output.ai/migrations/v0.16.0-to-v0.17.0 Upgrading Output.ai projects from v0.16.0 to v0.17.0: worker exit code on a forced shutdown, shutdown and Temporal log changes, and OUTPUT_TEMPORAL_LOG_LEVEL validation in @outputai/core. This guide covers behavior changes in the `@outputai/core` worker shutdown. Nothing in your code needs to change, but a deploy that lands on steps still running now exits `0` instead of `1`, several shutdown log lines changed, and `OUTPUT_TEMPORAL_LOG_LEVEL` rejects invalid values. If you alert on worker exit codes or match worker log lines, read [Exit code on a forced shutdown](#exit-code-on-a-forced-shutdown) and [Shutdown logs](#shutdown-logs). ## What changed * A signal shutdown that abandons in-flight work at `TEMPORAL_SHUTDOWN_FORCE_TIME` exits `0` instead of `1`. * A service that fails to stop is logged as a warning and never changes the exit code. This was already true for every service except the worker. * The `... error` warning of a failed service stop is now `... failed`, and carries the time the stop took in `shutdownDurationMs`. * Every successful service stop logs `... complete` with `shutdownDurationMs`. * The worker logs `Shutting down` with its shutdown budget as soon as shutdown starts, and `Bye` carries `shutdownDurationMs`. * Temporal's `Worker failed` entry for an expired force time is logged as a warning, not an error. * Temporal log entries that carry an error now show its `name`, `message` and `stack` instead of `{}`. * The worker warns at startup when `TEMPORAL_SHUTDOWN_FORCE_TIME` is not bigger than `TEMPORAL_SHUTDOWN_GRACE_TIME`. * `OUTPUT_TEMPORAL_LOG_LEVEL` is validated when the worker starts. ## Exit code on a forced shutdown When a signal starts the shutdown and a step is still running at `TEMPORAL_SHUTDOWN_FORCE_TIME`, the worker abandons it and exits. v0.16.0 exited `1` for that, so a routine deploy looked like a crash. v0.17.0 exits `0`. | Scenario | v0.16.0 | v0.17.0 | | - | - | - | | A signal arrives and the drain finishes in time | Exits `0` | Unchanged | | A signal arrives and a step outlives `TEMPORAL_SHUTDOWN_FORCE_TIME` | Logs a `Stopping Worker error` warning and an error-level `Worker failed`. Exits `1` | Logs a `Worker failed` warning and a `Stopping Worker failed` warning. Exits `0` | | A service other than the worker fails to stop | Warns `... error`. Exit code unaffected | Warns `... failed`. Exit code unaffected | | Startup fails, the Temporal connection is lost, an uncaught error ends the process, or a second signal forces an exit | Exits `1` | Unchanged | The abandoned step is not lost. Temporal notices its worker is gone when the step's heartbeat times out, and retries it. See [Worker Shutdown](/operations/worker-shutdown#what-happens-to-work-that-does-not-finish). If you alert on a non-zero worker exit, those alerts no longer fire for a deploy that abandoned work. To tell that case apart, match the logs below. A worker that fails for any other reason while draining is not covered by the exit code. Temporal logs it as an error-level `Worker failed`, so alert on that line. ## Shutdown logs | Log line | v0.16.0 | v0.17.0 | | - | - | - | | `Stopping Worker error`, `Stopping Connection Monitor error`, `Interrupting Catalog Publisher error`, `Closing Connection error` (warn) | Carries `error` | Renamed to `... failed`. Carries `error` and `shutdownDurationMs` | | After each successful stop | Nothing | `... complete` with `shutdownDurationMs` | | Start of shutdown | Nothing | `Shutting down` with `shutdownForceTimeMs`, `shutdownGraceTimeMs` and `hookFlushTimeoutMs` | | `Bye` | `{ exitCode }` | `{ exitCode, shutdownDurationMs }` | | `Worker failed` after a forced stop | Error level, `error: {}` | Warn level, with the serialized `GracefulShutdownPeriodExpiredError` | An abandoned drain now reads like this in the logs: ```text theme={null} [warn] Temporal: Worker failed { error: { name: "GracefulShutdownPeriodExpiredError", ... } } [warn] Worker Shutdown: Stopping Worker failed { error: { name: "IllegalStateError", message: "Worker still in use: ...", ... }, shutdownDurationMs: 20004 } [info] Worker: Bye { exitCode: 0, shutdownDurationMs: 20190 } ``` The sample uses the development format, `[level] namespace: message { fields }`. Production logs are JSON with the same fields. Update log-based alerts and dashboards: * A matcher on the text `Stopping Worker error` (or another `... error` stop line) must use `... failed`. * A matcher on an error-level `Worker failed` stops matching a forced drain. If you baselined it as noise, remove it. * Anything that parses a Temporal log's `error` field now receives an object with `name`, `message` and `stack` instead of `{}`. `Shutting down` is logged before the drain starts, so the budget is in the log even if the platform kills the process mid-drain. `shutdownDurationMs` on `Bye` is the whole shutdown, hook flush included. Compare it with your platform's shutdown window. See [Reading the Shutdown Logs](/operations/worker-shutdown#reading-the-shutdown-logs). A force time that is not bigger than the grace time now logs `Temporal shutdown force time is not bigger than its grace time, so activities have no window to react to cancellation`, with both values. Raise `TEMPORAL_SHUTDOWN_FORCE_TIME` above `TEMPORAL_SHUTDOWN_GRACE_TIME`. ## `OUTPUT_TEMPORAL_LOG_LEVEL` is validated The variable takes `TRACE`, `DEBUG`, `INFO`, `WARN` or `ERROR`, in any letter case, and defaults to `INFO` when unset or empty. Any other value, such as `verbose` or a Winston level like `silly`, now fails worker startup with a message naming the allowed values. ```bash theme={null} # Before: not checked by Output OUTPUT_TEMPORAL_LOG_LEVEL=verbose # After OUTPUT_TEMPORAL_LOG_LEVEL=DEBUG ``` At `ERROR`, the `Worker failed` warning of a forced shutdown is not logged, since it is no longer an error. ## Checklist * Bump `@outputai/core` and `@outputai/cli` to `0.17.0`. * Remove or adjust alerts that treat a non-zero worker exit on a deploy as a failure. A forced drain exits `0`. * Change log matchers from `Stopping Worker error` (and the other `... error` stop lines) to `... failed`. * Remove an error-level `Worker failed` entry from your noise baseline. A forced drain logs it as a warning. * Update consumers of Temporal log entries that read an empty `error` object. * Check that `OUTPUT_TEMPORAL_LOG_LEVEL`, if set, is one of `TRACE`, `DEBUG`, `INFO`, `WARN` or `ERROR`. * If your deploys abandon work often, size `TEMPORAL_SHUTDOWN_GRACE_TIME`, `TEMPORAL_SHUTDOWN_FORCE_TIME` and your platform's shutdown window together. See [Worker Shutdown](/operations/worker-shutdown). # v0.2.0 → v0.3.0 Source: https://docs.output.ai/migrations/v0.2.0-to-v0.3.0 Upgrading Output.ai projects from v0.2.0 to v0.3.0: New LLM cost payload format and cost event name change. This release has two breaking changes: 1. The `llm:call_cost` hook event was renamed to `cost:llm:request`; 2. The `cost` object in events and LLM responses has a new format. ## Migration steps ### Event renaming Update each hook that listens for `llm:call_cost` to use `cost:llm:request`: #### Before ```js theme={null} import { on } from '@outputai/core/hooks'; on( 'llm:call_cost', async ( { modelId, cost, usage } ) => { ... } ); ``` #### After ```js theme={null} import { on } from '@outputai/core/hooks'; on( 'cost:llm:request', async ( { modelId, cost, usage } ) => { ... } ); ``` ### Cost payload On the `@outputai/llm` module, the `cost` field in both the `.generateText()` response and the `cost:llm:request` event has a new format: #### Before ```json theme={null} { "total": 0.002341, "components": { "input": { "value": 0.001302 }, "cachedInput": { "value": 0 }, "output": { "value": 0.001039 }, "reasoning": { "value": 0.00027 } } } ``` #### After ```json theme={null} { "total": 0.002341, "components": [ { "name": "input_tokens", "value": 0.001302 }, { "name": "input_cached_tokens", "value": 0 }, { "name": "output_tokens", "value": 0.001039 }, { "name": "reasoning_tokens", "value": 0.00027 } ] } ``` **Note:** `components` used to be an object; it is now an array. # v0.3.0 → v0.4.0 Source: https://docs.output.ai/migrations/v0.3.0-to-v0.4.0 Upgrading Output.ai projects from v0.3.0 to v0.4.0: New package.json config section. The dedicated `package.json` section for Output.ai settings changed from `output` to `outputai`. Only the top level has changed. ## Migration steps ### Rename field Replace `output` with `outputai`. #### Before *package.json* ```json theme={null} { ... "output": { "hookFiles": [ "./src/hooks.js" ] } } ``` #### After *package.json* ```json theme={null} { ... "outputai": { "hookFiles": [ "./src/hooks.js" ] } } ``` # v0.4.0 → v0.5.0 Source: https://docs.output.ai/migrations/v0.4.0-to-v0.5.0 Upgrading Output.ai projects from v0.4.0 to v0.5.0: HTTP and LLM cost API and cost event payload changes. This guide covers the `@outputai/http` and `@outputai/llm` cost tracking changes in v0.5.0. ## What changed * `addRequestCost` now accepts a numeric total instead of a `RequestCost` object. * The `RequestCost` type is removed. * The `cost:http:request` event now receives an HTTP request cost attribute instead of `{ requestId, url, cost }`. * LLM response `.cost` is now an LLM usage attribute instead of `{ total, components }`. * LLM usage entries only include available, finite dimensions; missing dimensions are omitted. * Missing LLM costs are returned as `null`, not as cost objects with `total: null` and `message`. * The `cost:llm:request` event now receives the LLM usage attribute instead of `{ modelId, cost, usage }`. ## Migration steps ### Update `addRequestCost` Pass the total request cost directly. #### Before ```ts theme={null} import { addRequestCost } from '@outputai/http'; addRequestCost( response, { total: inputCost + outputCost, components: [ { name: 'input', value: inputCost }, { name: 'output', value: outputCost } ] } ); ``` #### After ```ts theme={null} import { addRequestCost } from '@outputai/http'; addRequestCost( response, inputCost + outputCost ); ``` ### Remove `RequestCost` imports The `RequestCost` object shape is no longer part of the public API. #### Before ```ts theme={null} import { addRequestCost, type RequestCost } from '@outputai/http'; const cost: RequestCost = { total: 0.42 }; addRequestCost( response, cost ); ``` #### After ```ts theme={null} import { addRequestCost } from '@outputai/http'; const cost = 0.42; addRequestCost( response, cost ); ``` ### Update `cost:http:request` hooks The event payload is now the HTTP request cost attribute. #### Before ```js theme={null} import { on } from '@outputai/core/hooks'; on( 'cost:http:request', async ( { requestId, url, cost } ) => { console.log( requestId, url, cost.total ); } ); ``` #### After ```js theme={null} import { on } from '@outputai/core/hooks'; on( 'cost:http:request', async ( { workflowId, requestId, url, total, activityId, activityName } ) => { console.log( workflowId, requestId, url, total, activityId, activityName ); } ); ``` ### Update LLM response cost handling The `.cost` property on `generateText()` responses and `streamText()` `onFinish` responses is now an LLM usage attribute. #### Before ```js theme={null} const response = await generateText( { prompt: 'summarize@v1' } ); console.log( response.cost.total ); for ( const component of response.cost.components ) { console.log( component.name, component.value ); } ``` #### After ```js theme={null} const response = await generateText( { prompt: 'summarize@v1' } ); console.log( response.cost?.total ); console.log( response.cost?.tokensUsed ); for ( const usage of response.cost?.usage ?? [] ) { console.log( usage.type, usage.amount, usage.total ); } ``` When pricing cannot be computed, `response.cost` is `null`. ### Handle missing LLM costs When LLM pricing cannot be loaded or the model is missing from the pricing table, Output no longer returns a cost object with `total: null` and `message`. #### Before ```js theme={null} const response = await generateText( { prompt: 'summarize@v1' } ); if ( response.cost.total === null ) { console.warn( response.cost.message ); } ``` #### After ```js theme={null} const response = await generateText( { prompt: 'summarize@v1' } ); if ( response.cost === null ) { console.warn( 'LLM cost was not available for this response.' ); } ``` No `cost:llm:request` event or LLM usage trace attribute is emitted when cost is missing. ### Handle omitted LLM usage fields Cost usage entries now include only the dimensions that are available and priced. #### Before ```js theme={null} const cached = response.cost.components.find( c => c.name === 'input_cached_tokens' ); console.log( cached?.value ?? 0 ); ``` #### After ```js theme={null} const cached = response.cost?.usage.find( u => u.type === 'input_cached' ); console.log( cached?.total ?? 0 ); ``` Use these `usage[].type` values: | `type` | Description | | - | - | | `input` | Non-cached prompt tokens. | | `input_cached` | Cached prompt read tokens. | | `output` | Completion tokens. | | `reasoning` | Reasoning tokens, when separately priced. | ### Update `cost:llm:request` hooks The event payload is now the LLM usage attribute. #### Before ```js theme={null} import { on } from '@outputai/core/hooks'; on( 'cost:llm:request', async ( { modelId, cost, usage } ) => { console.log( modelId, usage.totalTokens, cost.total ); } ); ``` #### After ```js theme={null} import { on } from '@outputai/core/hooks'; on( 'cost:llm:request', async ( { workflowId, modelId, tokensUsed, total, usage, activityId, activityName } ) => { console.log( workflowId, modelId, tokensUsed, total, usage, activityId, activityName ); } ); ``` ## Cost attribute reference HTTP and LLM cost payloads are now trace attributes. Hook payloads include `workflowId`; workflow result attributes are nested under a result that already has `workflowId` and `runId`, so they do not repeat the workflow ID. ### HTTP request cost hook payload ```json theme={null} { "type": "http:request:cost", "workflowId": "workflow-123", "activityId": "activity-456", "activityName": "lookupCompany", "requestId": "request-789", "url": "https://api.example.com/companies", "total": 0.42 } ``` | Field | Description | | - | - | | `type` | Always `"http:request:cost"`. | | `workflowId` | Workflow execution ID. Present on hook payloads. | | `activityId` | Activity ID of the step that made the request, when available. | | `activityName` | Activity name of the step that made the request, when available. | | `requestId` | Internal ID linking the cost to the traced HTTP request. | | `url` | Final response URL. | | `total` | Dollar cost passed to `addRequestCost`. | ### LLM usage cost hook payload ```json theme={null} { "type": "llm:usage", "workflowId": "workflow-123", "activityId": "activity-456", "activityName": "generateSummary", "modelId": "anthropic/claude-3-5-sonnet", "total": 0.0084, "tokensUsed": 1200, "usage": [ { "type": "input", "ppm": 3, "amount": 800, "total": 0.0024 }, { "type": "output", "ppm": 15, "amount": 400, "total": 0.006 } ] } ``` | Field | Description | | - | - | | `type` | Always `"llm:usage"`. | | `workflowId` | Workflow execution ID. Present on hook payloads. | | `activityId` | Activity ID of the step that made the LLM request, when available. | | `activityName` | Activity name of the step that made the LLM request, when available. | | `modelId` | Model identifier used for the request. | | `total` | Total computed dollar cost. | | `tokensUsed` | Sum of token amounts included in `usage`. | | `usage` | Per-dimension token usage and cost entries. | Each `usage` entry includes `type`, `ppm`, `amount`, and `total`. Only available, finite usage dimensions are included. ## Checklist * Replace every `addRequestCost(response, { total, components })` call with `addRequestCost(response, total)`. * Remove `RequestCost` imports and annotations. * Update `cost:http:request` hook handlers to read `total` directly from the payload. * Remove any logic that expected HTTP cost `components`; HTTP request costs are now a single total value. * Replace LLM `response.cost.components` reads with `response.cost?.usage`. * Handle `response.cost === null` when pricing cannot be computed; do not expect a cost object with `total: null` and `message`. * Update `cost:llm:request` hook handlers to read the LLM usage attribute payload directly. # v0.5.2 → v0.6.0 Source: https://docs.output.ai/migrations/v0.5.2-to-v0.6.0 Upgrading Output.ai projects from v0.5.2 to v0.6.0: hook payload context objects and trace run ids. This guide covers the `@outputai/core` hook payload and activity context changes in v0.6.0. ## What changed * Hook payloads no longer expose flat `workflowId`, `runId`, `workflowName`, `activityId`, or `activityName` context fields. * Workflow lifecycle hooks now receive `workflowDetails` instead of `id`, `runId`, `name`, and `duration`. * Activity-scoped hooks and custom events now receive Temporal's `activityInfo`, Output's `workflowDetails`, and `outputActivityKind`. * The `on()` hook envelope now contains `eventId`, `eventDate`, `workflowDetails`, `activityInfo`, and `outputActivityKind`. * `getExecutionContext()` now returns `{ activityInfo, workflowFilename }` when activity context is available. * `HttpRequestHookPayload` was removed. Pass event attributes directly to `on()` instead. * Trace workflow node ids now use Temporal `runId`, improving traces for child workflows that continue as new. ## Migration steps ### Update workflow lifecycle hooks Use `workflowDetails` for workflow ids and type. #### Before ```js theme={null} import { onWorkflowStart } from '@outputai/core/hooks'; onWorkflowStart( ( { id, runId, name } ) => { console.log( 'Workflow started', { id, runId, name } ); } ); ``` #### After ```js theme={null} import { onWorkflowStart } from '@outputai/core/hooks'; onWorkflowStart( ( { workflowDetails } ) => { console.log( 'Workflow started', { workflowId: workflowDetails.workflowId, runId: workflowDetails.runId, workflowType: workflowDetails.workflowType } ); } ); ``` `onWorkflowEnd()` and `onWorkflowError()` use the same `workflowDetails` shape. The old lifecycle `duration` field is no longer part of the hook payload. ### Update error hooks Activity errors now expose Temporal activity info and workflow details instead of flat ids and names. #### Before ```js theme={null} import { onError } from '@outputai/core/hooks'; onError( ( payload ) => { if ( payload.source === 'activity' ) { console.error( payload.workflowName, payload.activityName, payload.error ); } } ); ``` #### After ```js theme={null} import { onError } from '@outputai/core/hooks'; onError( ( payload ) => { if ( payload.source === 'activity' ) { console.error( payload.workflowDetails.workflowType, payload.activityInfo.activityType, payload.error ); } } ); ``` `activityInfo` is Temporal's Activity execution info object. See Temporal's [`activity.Info`](https://typescript.temporal.io/api/interfaces/activity.Info) reference. `workflowDetails` is Output's serializable subset of Temporal's [`workflow.WorkflowInfo`](https://typescript.temporal.io/api/interfaces/workflow.WorkflowInfo). ### Update custom event hooks Events emitted with `emitEvent()` still include your custom payload, `eventId`, and `eventDate`. When emitted from an Output activity, the contextual fields are now `activityInfo`, `workflowDetails`, and `outputActivityKind`. `outputActivityKind` is one of `step`, `evaluator`, or `internal_step`. #### Before ```js theme={null} import { on } from '@outputai/core/hooks'; on( 'http:request', ( { workflowId, runId, activityId, requestId } ) => { console.log( workflowId, runId, activityId, requestId ); } ); ``` #### After ```js theme={null} import { on } from '@outputai/core/hooks'; on( 'http:request', ( { workflowDetails, activityInfo, requestId } ) => { console.log( workflowDetails.workflowId, workflowDetails.runId, activityInfo.activityId, requestId ); } ); ``` This affects built-in custom events such as `http:request`, `cost:http:request`, and `cost:llm:request`. ### Update TypeScript hook payload types The `on()` hook now lets you type event-specific attributes directly through its generic. Core still owns the common envelope (`eventId`, `eventDate`, `workflowDetails`, `activityInfo`, and `outputActivityKind`); event-emitting packages own their event attribute types. ```ts theme={null} import { on } from '@outputai/core/hooks'; import type { HttpRequestEvent } from '@outputai/http'; on( 'http:request', payload => { console.log( payload.workflowDetails.workflowId, payload.requestId ); } ); ``` Use `HttpRequestEvent` and `HttpRequestCostEvent` from `@outputai/http`, and `LLMUsageEvent` from `@outputai/llm`. | Event name | Import type from | Use with `on()` | | - | - | - | | `http:request` | `@outputai/http` | `on( 'http:request', handler )` | | `cost:http:request` | `@outputai/http` | `on( 'cost:http:request', handler )` | | `cost:llm:request` | `@outputai/llm` | `on( 'cost:llm:request', handler )` | For advanced type composition, the framework-managed envelope type is exported as `OnHookEnvelope`, and the full merged payload type is `OnHookPayload`. ### Update activity integration context usage If you use the internal `@outputai/core/sdk_activity_integration` helpers, `getExecutionContext()` now returns Temporal's activity info plus the workflow file path. #### Before ```js theme={null} const context = getExecutionContext(); console.log( context.workflowId, context.runId, context.activityId ); ``` #### After ```js theme={null} const context = getExecutionContext(); console.log( context?.activityInfo.workflowExecution?.workflowId, context?.activityInfo.workflowExecution?.runId, context?.activityInfo.activityId ); ``` ### Check trace consumers Trace file names still use `workflowId`, but workflow node ids inside trace entries now use `runId`. If you parse trace JSON directly, update code that assumed a workflow trace node id was the workflow id. This makes traces more accurate for child workflows that continue as new, because each Temporal run has a distinct node id. ## Checklist * Replace workflow lifecycle hook destructuring of `id`, `runId`, `name`, or `duration` with `workflowDetails`. * Replace activity hook destructuring of `activityId`, `activityName`, `workflowId`, or `workflowName` with `activityInfo` and `workflowDetails`. * Update `on('http:request')`, `on('cost:http:request')`, and `on('cost:llm:request')` handlers to read context from `activityInfo` and `workflowDetails`. * Replace `HttpRequestHookPayload` with package-owned event attribute types passed to `on()`. * Update any `getExecutionContext()` usage to read from `activityInfo`. * Update direct trace JSON consumers to use `runId` for workflow node ids. # v0.6.0 → v0.7.0 Source: https://docs.output.ai/migrations/v0.6.0-to-v0.7.0 Upgrading Output.ai projects from v0.6.0 to v0.7.0: removed web search tool re-exports and provider list helper rename. This guide covers the `@outputai/llm` export changes in v0.7.0. ## What changed * `@outputai/llm` no longer re-exports Tavily, Exa, or Perplexity search tool factories. * `@outputai/llm` `.getRegisteredProviders()` was renamed to `.getProviderNames()`. ## Migration steps ### Import web search tools from their packages `@outputai/llm` no longer re-exports third-party search tool factories. Import them directly from the package that owns them. #### Before ```ts theme={null} import { tavilySearch, tavilyExtract, tavilyCrawl, tavilyMap, exaSearch, perplexitySearch } from '@outputai/llm'; ``` #### After ```ts theme={null} import { tavilySearch, tavilyExtract, tavilyCrawl, tavilyMap } from '@tavily/ai-sdk'; import { webSearch as exaSearch } from '@exalabs/ai-sdk'; import { perplexitySearch } from '@perplexity-ai/ai-sdk'; ``` Install whichever search tool packages you use: ```bash theme={null} npm install @tavily/ai-sdk @exalabs/ai-sdk @perplexity-ai/ai-sdk ``` > [!NOTE] > > `provider: perplexity` uses the AI SDK provider package `@ai-sdk/perplexity`. The removed `perplexitySearch` export comes from the separate tool package `@perplexity-ai/ai-sdk`. ### Rename `getRegisteredProviders` to `getProviderNames` The provider list helper was renamed to better describe that it returns built-in provider names as well as custom providers registered with `registerProvider`. #### Before ```ts theme={null} import { getRegisteredProviders } from '@outputai/llm'; const providers = getRegisteredProviders(); ``` #### After ```ts theme={null} import { getProviderNames } from '@outputai/llm'; const providers = getProviderNames(); ``` ## Checklist * Replace Tavily imports from `@outputai/llm` with imports from `@tavily/ai-sdk`. * Replace `exaSearch` imports from `@outputai/llm` with `webSearch as exaSearch` from `@exalabs/ai-sdk`. * Replace `perplexitySearch` imports from `@outputai/llm` with imports from `@perplexity-ai/ai-sdk`. * Replace `getRegisteredProviders` imports and calls with `getProviderNames`. * Run your package manager install command and type checker. # v0.7.0 → v0.8.0 Source: https://docs.output.ai/migrations/v0.7.0-to-v0.8.0 Upgrading Output.ai projects from v0.7.0 to v0.8.0: workflow result aggregations removal, workflow invocation options, and child workflow execution semantics. This guide covers the `@outputai/core` workflow execution changes in v0.8.0. ## What changed * Workflows no longer aggregate usage data or expose `aggregations` in run results. * Workflow invocation options changed. * Calling a workflow from inside another workflow now always starts a Temporal child workflow. ## Migration steps ### Replace workflow result aggregations Workflows no longer collect usage events into workflow-level totals. As a result, workflow results now focus on the workflow output and trace metadata, and no longer expose `result.aggregations`. If your API or CLI consumers read usage totals from `result.aggregations`, move that aggregation into hooks. #### Before ```ts theme={null} const result = await client.runWorkflow( 'lead_enrichment', input ); console.log( result.aggregations.cost.total ); console.log( result.aggregations.tokens.total ); console.log( result.aggregations.httpRequests.total ); ``` #### After Record cost events as they happen, then aggregate them in your own store. Hook payloads include `workflowDetails`, so you can group totals by workflow id and run id. ```ts theme={null} // hooks.ts import { on } from '@outputai/core/hooks'; import type { HttpRequestCostEvent } from '@outputai/http'; import type { LLMUsageEvent } from '@outputai/llm'; type Totals = { cost: number, tokens: number, httpRequests: number }; const totalsByRun = new Map(); function getTotalsKey( payload: { workflowDetails: { workflowId: string, runId: string } } ) { return `${payload.workflowDetails.workflowId}:${payload.workflowDetails.runId}`; } function getTotals( key: string ) { const current = totalsByRun.get( key ) ?? { cost: 0, tokens: 0, httpRequests: 0 }; totalsByRun.set( key, current ); return current; } on( 'cost:http:request', payload => { const totals = getTotals( getTotalsKey( payload ) ); totals.cost += payload.total; totals.httpRequests += 1; } ); on( 'cost:llm:request', payload => { const totals = getTotals( getTotalsKey( payload ) ); totals.cost += payload.total; totals.tokens += payload.tokensUsed; } ); ``` For production systems, write the hook payloads to durable storage instead of an in-memory map. Use `eventId` as the idempotency key if your sink can receive retries or duplicate deliveries. ```ts theme={null} // hooks.ts import { on } from '@outputai/core/hooks'; import type { HttpRequestCostEvent } from '@outputai/http'; on( 'cost:http:request', async payload => { await usageEvents.insert( { id: payload.eventId, workflowId: payload.workflowDetails.workflowId, runId: payload.workflowDetails.runId, source: 'http', requestId: payload.requestId, cost: payload.total, occurredAt: new Date( payload.eventDate ) } ); } ); ``` If you previously displayed workflow-level totals in a run detail page, query your aggregation store by `workflowId` and `runId` alongside the workflow result. ### Update workflow invocation options The second argument to a workflow function is now named `WorkflowInvocationOptions`. If you imported the old invocation configuration type directly, update that import: ```ts theme={null} // Before import type { WorkflowInvocationConfiguration } from '@outputai/core'; // After import type { WorkflowInvocationOptions } from '@outputai/core'; ``` The shape also changed: invocation-level activity options are now passed as `activityOptions`. The old `options` property is no longer accepted for workflow calls. #### Before ```ts theme={null} await enrichCompanyWorkflow( { domain: input.domain }, { options: { retry: { maximumAttempts: 1 } } } ); ``` #### After ```ts theme={null} await enrichCompanyWorkflow( { domain: input.domain }, { activityOptions: { retry: { maximumAttempts: 1 } } } ); ``` The invocation options shape is: ```ts theme={null} type WorkflowInvocationOptions = { activityOptions?: TemporalActivityOptions, detached?: boolean, context?: DeepPartial }; ``` `detached` and `context` remain invocation options. The field to update for this migration is `activityOptions`. ### Review workflow-to-workflow calls Calling a workflow function from inside another workflow now always starts a Temporal child workflow. In older versions, some direct workflow calls were rewritten only in specific code paths. When that rewrite happened, the called workflow could effectively run as part of the parent workflow's execution path: its activities were scheduled from the parent workflow, and the child workflow did not necessarily appear as a distinct Temporal child execution. In v0.8.0, this is different by design. A direct call like this: ```ts theme={null} import enrichCompanyWorkflow from '../enrich_company/workflow.js'; export default workflow( { name: 'lead_enrichment', async fn( input ) { return enrichCompanyWorkflow( { domain: input.domain } ); } } ); ``` now starts `enrich_company` as a Temporal child workflow. That means: * The called workflow has its own Temporal workflow execution, run id, history, and retry/cancellation behavior. * Activities inside the called workflow are scheduled by the child workflow, not by the parent. * The parent receives the child workflow result when you `await` or return the call. * Errors from the called workflow cross a child workflow boundary. * The child appears as a child workflow in Temporal and in traces. Most awaited calls keep the same value-level behavior: ```ts theme={null} const childOutput = await enrichCompanyWorkflow( { domain: input.domain } ); ``` But operational behavior changes. Check code that depended on parent workflow activity history, parent-close behavior, or catching specific raw Temporal failure shapes. ## Checklist * Remove usage of workflow result `.attributes` and `.aggregations`. * Add hook handlers for `cost:http:request` and `cost:llm:request` if you still need usage totals. * Persist hook events or aggregated totals outside the workflow result. * Replace workflow invocation `options` with top-level `activityOptions`. * Review every workflow-to-workflow call and treat it as a Temporal child workflow boundary. * Update tests that assume workflow-to-workflow calls run inside the parent execution. # v0.8.0 → v0.9.0 Source: https://docs.output.ai/migrations/v0.8.0-to-v0.9.0 Upgrading Output.ai projects from v0.8.0 to v0.9.0: the CLI replaces --format json with the native --json flag. This guide covers the `@outputai/cli` output flag changes in v0.9.0. It only affects how you invoke the CLI and parse its output — no code changes are required in your workflows. ## What changed The old `--format json` flag still printed preamble to stdout (the version-check banner and lines like `Fetching result for workflow...`), which broke piping: ```bash theme={null} npx output workflow result --format json | jq # jq: parse error: Invalid numeric literal at line 3, column 0 ``` v0.9.0 drops `--format json` for the native `--json` flag from `@oclif` v4+, which guarantees stdout is valid JSON. Informational logs and the update banner now go to stderr, so `--json` pipes cleanly. ## Migration steps ### Replace `--format json` with `--json` On `workflow result`, `status`, `run`, `cost`, `debug`, and `test`, the `--format` flag is removed. Text stays the default; pass `--json` for JSON. ```bash theme={null} # Before npx output workflow result --format json | jq # After npx output workflow result --json | jq ``` ### Update list commands that kept `--format` `workflow list`, `runs list`, and `dataset list` still accept `--format` for their non-JSON layouts (`list` / `table` / `text`). Only the JSON value moved to `--json`. ```bash theme={null} npx output workflow list --json # JSON output npx output workflow list --format table # non-JSON layouts still use --format ``` > [!NOTE] > > If a script stripped the banner or `Fetching...` preamble before parsing, you can drop that workaround — `--json` stdout is now pure JSON. The update banner prints to stderr in every mode; redirect with `2>/dev/null` to hide it in interactive use. ## Checklist * Replace `--format json` with `--json` everywhere (`result`, `status`, `run`, `cost`, `debug`, `test`, `list`, `runs list`, `dataset list`). * Keep `--format` on the list commands for their `list` / `table` / `text` layouts. * Drop any preamble-stripping workarounds, and update CI jobs, aliases, and docs that reference `--format json`. # v0.9.0 → v0.10.0 Source: https://docs.output.ai/migrations/v0.9.0-to-v0.10.0 Upgrading Output.ai projects from v0.9.0 to v0.10.0: trace destinations now omit unavailable outputs and sendHttpRequest returns metadata by default. This guide covers the trace destination shape changes in v0.10.0 and the `sendHttpRequest` output change. Trace destination changes affect workflow result payloads returned by `@outputai/core`, the API workflow result endpoints, and CLI JSON output. ## What changed Trace destinations are now sparse. When a trace destination is unavailable, Output.ai omits that key instead of returning it as `null`. Before, workflow results always included both `local` and `remote` destination keys: ```json theme={null} { "output": { "ok": true }, "trace": { "destinations": { "local": null, "remote": "https://bucket.s3.amazonaws.com/runs/example.json" } } } ``` In v0.10.0, only available destinations are present: ```json theme={null} { "output": { "ok": true }, "trace": { "destinations": { "remote": "https://bucket.s3.amazonaws.com/runs/example.json" } } } ``` When tracing is disabled, or when no trace destinations are available, results now use an empty object: ```json theme={null} { "output": { "ok": true }, "trace": { "destinations": {} } } ``` This shape appears in: * `@outputai/core` workflow result envelopes * `POST /workflow/run` * `GET /workflow/{id}/result` * `GET /workflow/{id}/runs/{rid}/result` * `output workflow run ... --json` * `output workflow result --json` ## Migration steps ### Opt into `sendHttpRequest` response headers and body Breaking change: `sendHttpRequest` no longer returns response headers or body by default. The default response now includes only `url`, `status`, `statusText`, and `ok`. If your workflow reads `response.headers` or `response.body`, pass `responseOptions`. #### Before ```ts theme={null} const response = await sendHttpRequest( { url: 'https://api.example.com/data', method: 'GET' } ); return response.body; ``` #### After ```ts theme={null} const response = await sendHttpRequest( { url: 'https://api.example.com/data', method: 'GET', responseOptions: { includeBody: true, includeHeaders: true } } ); return response.body; ``` Response headers included with `includeHeaders: true` are redacted by header name. Response bodies are returned as-is, so only opt into `includeBody` when the body is safe to store in workflow history and trace files. ### Stop checking for `null` destinations If your code checks for `null`, switch to checking whether a destination key exists or has a truthy value. #### Before ```ts theme={null} const destinations = result.trace?.destinations; if ( destinations?.remote !== null ) { await fetchRemoteTrace( destinations.remote ); } if ( destinations?.local !== null ) { console.log( destinations.local ); } ``` #### After ```ts theme={null} const destinations = result.trace?.destinations ?? {}; if ( destinations.remote ) { await fetchRemoteTrace( destinations.remote ); } if ( destinations.local ) { console.log( destinations.local ); } ``` ### Treat an empty destination object as "no trace destination" If your UI or automation previously expected `{ local: null, remote: null }`, update it to treat `{}` the same way. #### Before ```ts theme={null} const hasTraceDestination = result.trace?.destinations?.local !== null || result.trace?.destinations?.remote !== null; ``` #### After ```ts theme={null} const destinations = result.trace?.destinations ?? {}; const hasTraceDestination = Object.keys( destinations ).length > 0; ``` ### Update API and CLI JSON consumers Scripts that parse API responses or CLI JSON output should not assume that `local` and `remote` are always present. ```bash theme={null} # These commands can now return trace.destinations as {} npx output workflow run simple basic_input --json npx output workflow result --json ``` For example, update `jq` filters to handle missing keys: ```bash theme={null} # Before npx output workflow result --json | jq -e '.trace.destinations.remote != null' # After npx output workflow result --json | jq -r '.trace.destinations.remote // empty' ``` The `// empty` filter works with both old `null` values and new omitted keys. If your script checks for exact object equality, update that assertion to accept `{}`. ## Other trace behavior changes When a workflow has `disableTrace: true`, Output.ai no longer invokes the internal `getTraceDestinations` activity. The result still includes `trace.destinations: {}`, but avoids scheduling work that cannot produce a trace destination. Trace files can now include internal activities such as `getTraceDestinations` and `sendHttpRequest`. These activities are visible in Temporal and can affect workflow behavior, so they are now represented in trace output. ## Checklist * Add `responseOptions.includeBody` and/or `responseOptions.includeHeaders` anywhere workflow code reads `sendHttpRequest` response body or headers. * Replace `destination === null` checks with truthy or key-existence checks. * Treat `trace.destinations: {}` as "no trace destination available." * Update API response assertions that expected both `local` and `remote` keys. * Update CLI `--json` parsing scripts that assumed `trace.destinations.local` and `trace.destinations.remote` always existed. * If you inspect trace files directly, expect internal activities to appear. # Deployment overview Source: https://docs.output.ai/operations/deployment Deploy your Output workflows to production This section covers deploying Output workflows to a production environment. Whether you're running a single worker or scaling across multiple instances, the deployment architecture stays the same. ## What you're deploying An Output deployment consists of two core services, with an optional third for remote tracing: | Service | Required | Purpose | | - | - | - | | **API** | Yes | HTTP endpoint for triggering workflows, listing available workflows, and retrieving results. Deployed from a pre-built Docker image — no custom code needed. | | **Worker** | Yes | Runs your workflows. Contains your workflow code, connects to the Temporal backend, and executes workflow steps. | | **Redis** | No | Enables remote trace file generation and S3 upload for debugging production runs. See [Tracing](/operations/tracing) for details. | The API is a lightweight HTTP server that accepts workflow execution requests, routes them to the Temporal backend, and returns results. It ships as a pre-built Docker image so there's no custom code to maintain. The Worker is the core of your deployment — it contains your workflow code and connects to the Temporal backend for orchestration. Workers scale horizontally; you can add more instances to handle increased load without changing your workflow code. > [!NOTE] > > These guides assume you're using **Temporal Cloud** for workflow orchestration. If you need help setting up Temporal Cloud, see the [Temporal Cloud documentation](https://docs.temporal.io/cloud). ## Prerequisites Before deploying to any platform, ensure you have: * A Temporal backend with a dedicated namespace (e.g. [Temporal Cloud](https://temporal.io/cloud)) * Your workflow repository on GitHub * API keys for any services your workflows use (Anthropic, OpenAI, etc.) * Any [search attributes](#search-attributes) your callers send, registered on that namespace ## Search attributes Callers can attach Temporal [search attributes](https://docs.temporal.io/search-attribute) to a run by sending a `searchAttributes` map alongside `input` on `/workflow/run` or `/workflow/start`. Search attributes make runs queryable in Temporal (for example, all runs for one customer) without knowing individual workflow IDs: ```json theme={null} { "workflowName": "lead_enrichment", "input": { "domain": "example.com" }, "searchAttributes": { "ClientId": "acme" } } ``` From the CLI, pass the same map with `--search-attributes`: `output workflow run lead_enrichment --input input.json --search-attributes '{"ClientId":"acme"}'`. Each attribute must be registered on the namespace before any caller sends it. This happens once per namespace, done by whoever administers it. On Temporal Cloud, use [`tcld`](https://docs.temporal.io/cloud/tcld/namespace): ```bash theme={null} tcld namespace search-attributes add \ --namespace \ --search-attribute "ClientId=Keyword" ``` On a self-hosted Temporal server, use the Temporal CLI: ```bash theme={null} temporal operator search-attribute create \ --address \ --namespace \ --name ClientId \ --type Keyword ``` Re-running the self-hosted command with the same name and type is a no-op. Before any caller sends `searchAttributes`, upgrade the API and every worker to a version that supports them. An older API ignores the field, and an older worker doesn't pass the attributes to hooks or child workflows. The type you register determines the JSON value callers send: | Type | JSON value | Example | | - | - | - | | `Keyword` | string (exact match) | `"acme"` | | `Text` | string (full-text search) | `"quarterly report"` | | `Int` | integer | `42` | | `Double` | number | `0.75` | | `Bool` | boolean | `true` | | `Datetime` | ISO 8601 string | `"2026-01-15T09:30:00Z"` | | `KeywordList` | array of strings | `["sales", "emea"]` | Validation is fail-fast. If an attribute isn't registered on the namespace, or its value doesn't match the registered type, the API returns 400 and the workflow is not started. Temporal's server-side limits on attribute count and size also apply; see the [Temporal search attribute docs](https://docs.temporal.io/search-attribute) for current values. Child workflows, including detached ones, inherit their parent's search attributes, and runs started with `continueAsNew` keep them, so every run in the tree is queryable by the same value. Temporal's own system attributes (names starting with `Temporal`, plus `BuildIds`) are not copied to children, so don't use the `Temporal` prefix for your own attributes. `./run.sh dev` registers a demo `WorkspaceId` (`Keyword`) attribute on the local Temporal server so you can try this locally. Projects created with `output init` don't register any attributes. > [!WARNING] > > Search attribute values are stored in Temporal's visibility store as plain values, not encoded or encrypted like workflow payloads. Don't put secrets or other sensitive data in them. ### Reading search attributes in hooks Hooks receive a run's search attributes in `workflowDetails.searchAttributes`, with each value as an array (`Datetime` values as ISO strings). When exporting them to a metrics system, pick specific approved keys rather than forwarding the whole map, because every distinct value becomes a tag and unbounded tag cardinality gets expensive. Search attributes are asserted by the caller: use them for attribution, not for authorization decisions. ## Platform guides Choose your deployment platform: > [card] [Railway](/operations/deployment/railway) > > **Railway.** Simple Docker-based deployments with automatic scaling. > [card] [Render](/operations/deployment/render) > > **Render.** Infrastructure-as-code deployments with a single render.yaml Blueprint. > [card] [Advanced](/operations/deployment/advanced) > > **Advanced.** Remote tracing with Redis and S3 for production debugging. ## Next steps > [card] [Tracing](/operations/tracing) > > **Tracing.** Configure production tracing and S3 storage. > [card] [Error Handling](/operations/error-handling) > > **Error Handling.** Handle failures gracefully in production. # Advanced configuration Source: https://docs.output.ai/operations/deployment/advanced Remote tracing, S3 upload, and other optional production features These features are not required for running workflows in production. Start with the [Railway](/operations/deployment/railway) or [Render](/operations/deployment/render) guides first, then come back here when you need production debugging visibility. ## Remote tracing with Redis By default, workers don't generate trace files in production. Local tracing writes to disk, which works in development but isn't practical when your worker runs in a container that gets replaced on every deploy. Remote tracing solves this. The worker streams trace events to Redis as workflows execute. When a run completes, the trace is assembled and optionally uploaded to S3 as a JSON file. You can then pull traces via the API or CLI to debug failures without SSH access to your worker. ### What you need * A **Redis instance** accessible from your worker. Most hosting providers offer managed Redis — check your provider's add-on marketplace or database options. * An **S3 bucket** (optional) if you want traces persisted beyond Redis TTL. Any S3-compatible storage works. ### Worker environment variables Add these to your worker service's environment: ```bash theme={null} # Required for remote tracing OUTPUT_REDIS_URL=redis://:6379 OUTPUT_TRACE_REMOTE_ON=true # Optional: persist traces to S3 OUTPUT_TRACE_REMOTE_S3_BUCKET= OUTPUT_AWS_REGION= OUTPUT_AWS_ACCESS_KEY_ID= OUTPUT_AWS_SECRET_ACCESS_KEY= ``` | Variable | Required | Description | | - | - | - | | `OUTPUT_REDIS_URL` | Yes | Redis connection string. The worker uses this to buffer trace events during workflow execution. | | `OUTPUT_TRACE_REMOTE_ON` | Yes | Set to `true` to enable remote tracing. | | `OUTPUT_REDIS_TRACE_TTL` | No | TTL in seconds for trace data in Redis. Default: 7 days (`604800`). | | `OUTPUT_TRACE_REMOTE_S3_BUCKET` | No | S3 bucket name. When set, completed traces are uploaded as JSON files. | | `OUTPUT_AWS_REGION` | With S3 | AWS region for the S3 bucket. | | `OUTPUT_AWS_ACCESS_KEY_ID` | With S3 | AWS access key with write access to the bucket. | | `OUTPUT_AWS_SECRET_ACCESS_KEY` | With S3 | AWS secret key. | > [!NOTE] > > The API service does **not** need Redis configuration. Only the worker streams trace events. ### Verifying it works 1. Deploy the worker with the new environment variables 2. Run a workflow through the API 3. Check that traces appear: ```bash theme={null} # Via the CLI npx output workflow debug # Via S3 (if configured) aws s3 ls s3:///traces/ ``` If traces don't appear, check the worker logs for Redis connection errors and verify `OUTPUT_REDIS_URL` is reachable from the worker. ### How it works The worker emits trace events to Redis as each step, LLM call, and HTTP request executes. Redis acts as a temporary buffer — events are keyed by workflow run ID and expire after the configured TTL. When a workflow completes (or fails), the worker assembles the full trace tree from Redis and uploads it to S3 if configured. This means traces are available in Redis immediately during execution, and in S3 shortly after completion. See [Tracing](/operations/tracing) for the full trace format and how to read trace files. # Deploy to Railway Source: https://docs.output.ai/operations/deployment/railway Step-by-step guide to deploying Output workflows on Railway [Railway](https://railway.com) is a great fit for Output deployments — it handles Docker builds automatically and scales horizontally out of the box. Here's what we'll do: * [**Set up Railway project**](#step-1-set-up-railway-project) — Create the project and connect your GitHub repo * [**Deploy the Output API**](#step-2-deploy-the-output-api) — Get the API running and verify it connects to Temporal * [**Create the worker Dockerfile**](#step-3-create-the-worker-dockerfile) — Add the `ops/` directory and Dockerfile to your repo * [**Deploy the worker**](#step-4-configure-and-deploy-the-worker) — Configure and deploy the worker service * [**Verify**](#step-5-verify) — Confirm everything is connected end-to-end ## Project structure After running `output init`, your repository looks like this: ``` your-workflows/ ├── config/ │ └── costs.yml ├── src/ │ └── workflows/ │ └── your_workflow/ │ ├── workflow.ts │ ├── steps.ts │ └── ... ├── package.json └── tsconfig.json ``` This is the default structure — it doesn't include any deployment configuration yet. During this guide, we'll add an `ops/` directory containing a Dockerfile for the worker. ## Step 1: Set up Railway project 1. Go to [Railway's dashboard](https://railway.com/dashboard) and click **New Project** 2. Select **Deploy from GitHub repo** and connect your repository 3. Railway will detect your project — don't deploy yet, we need to configure services first ## Step 2: Deploy the Output API The Output API is published as a Docker image. Deploy it first so you can verify the connection to Temporal before adding the worker. 1. Click **+ New** → **Docker Image** 2. Enter: `docker.io/outputai/api:latest` 3. Configure variables: ```bash theme={null} # Temporal connection TEMPORAL_ADDRESS=.aws.api.temporal.io:7233 TEMPORAL_NAMESPACE= TEMPORAL_API_KEY= # Task queue the worker will listen on. Must match the OUTPUT_CATALOG_ID used by the worker. OUTPUT_CATALOG_ID=main # Generate a secure token for API authentication OUTPUT_API_AUTH_TOKEN= ``` 4. Go to **Settings** → **Networking** and generate a Railway domain (or add your custom domain) 5. Configure scaling: | Setting | Recommended Value | | - | - | | Min Instances | 1 | | Max Instances | 3 (adjust based on load) | | Target CPU | 60% | | Target Memory | 60% | 6. Deploy the service and verify it's running: ```bash theme={null} curl https://your-api.railway.app/health ``` You should get a `200 OK` response. > [!TIP] > > Use the same `OUTPUT_API_AUTH_TOKEN` value when calling the API from your application. Railway can auto-generate secure values — click the dice icon next to the variable value. ## Step 3: Create the worker Dockerfile With the API running, we'll prepare the worker. First, add the `ops/` directory and a Dockerfile to your repository. Create `ops/Dockerfile`: ```dockerfile ops/Dockerfile theme={null} FROM node:24.15.0-slim ENV NODE_ENV=development WORKDIR /app # Required for Temporal's Rust-based client RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/* # Install dependencies COPY package.json package-lock.json ./ RUN npm run output:worker:install # Build the worker COPY src/ ./src/ COPY config/ ./config/ COPY tsconfig.json ./ RUN npm run output:worker:build # Clean up source files after build (config stays — credentials are needed at runtime) RUN rm -rf ./src tsconfig.json # Create non-root user for security RUN groupadd -r appuser && useradd -r -g appuser appuser RUN chown -R appuser:appuser /app USER appuser # Production settings ENV NODE_ENV=production ENV PATH="/app/node_modules/.bin:$PATH" # V8 heap per isolate = 40% of container memory (2 isolates by default, leaves room for Temporal Rust runtime + OS) ENV NODE_OPTIONS="--max-old-space-size-percentage=40 --heapsnapshot-signal=SIGUSR2" CMD ["output-worker"] ``` > [!TIP] > > The `NODE_OPTIONS` setting caps the V8 heap at 40% of container memory. The cap applies to each V8 isolate rather than to the process as a whole, and a worker runs one isolate on its main thread plus one per workflow thread, two by default. At 40%, both fit in the container with room left for the Temporal Rust runtime and OS overhead. If you raise `TEMPORAL_WORKFLOW_THREAD_POOL_SIZE`, lower the percentage so the isolate count times the percentage stays around 80. See [Memory and Isolates](/operations/worker-tuning#memory-and-isolates). Commit the new `ops/` directory and push to GitHub before continuing: ```bash theme={null} git add ops/ git commit -m "Add worker Dockerfile for Railway deployment" git push ``` ## Step 4: Configure and deploy the worker 1. Click on the service Railway created from your repo (or create a new one pointing to your repo) 2. Go to **Settings** and configure: | Setting | Value | | - | - | | **Root Directory** | `/` (or your monorepo path) | | **Dockerfile Path** | `ops/Dockerfile` | | **Watch Paths** | `src/**` (optional, for filtered deployments) | 3. Go to **Variables** and add: ```bash theme={null} # Temporal connection TEMPORAL_ADDRESS=.aws.api.temporal.io:7233 TEMPORAL_NAMESPACE= TEMPORAL_API_KEY= # Task queue for the worker to listen on. Must match the OUTPUT_CATALOG_ID used in the API. OUTPUT_CATALOG_ID=main # LLM API keys ANTHROPIC_API_KEY= OPENAI_API_KEY= # Add any other API keys your workflows need ``` > [!WARNING] > > Use Railway's **Raw Editor** to paste multiple variables at once. For sensitive values, Railway encrypts them automatically. 4. Configure **Scaling** (in Settings → Deploy): | Setting | Recommended Value | | - | - | | Min Instances | 1 | | Max Instances | 10 (adjust based on load) | | Target CPU | 60% | | Target Memory | 60% | 5. Deploy the worker service ## Step 5: Verify Now that the worker is deployed, verify it has connected to the API and your workflows are registered. 1. Check that the API can see your workflows via the catalog endpoint: ```bash theme={null} curl -H "Authorization: Basic " \ https://your-api.railway.app/workflow/catalog ``` You should see a JSON response listing your registered workflows. If the list is empty, the worker may still be starting up — check the worker logs in Railway and try again after a moment. 2. Run a workflow end-to-end: ```bash theme={null} curl -X POST https://your-api.railway.app/workflow/run \ -H "Content-Type: application/json" \ -H "Authorization: Basic " \ -d '{ "workflowName": "your_workflow", "input": { "key": "value" } }' ``` ## Config as code (optional) Railway supports configuration in a `railway.json` file. This is useful for reproducible deployments: ```json railway.json theme={null} { "$schema": "https://railway.com/railway.schema.json", "build": { "builder": "DOCKERFILE", "dockerfilePath": "ops/Dockerfile" }, "deploy": { "startCommand": "output-worker", "restartPolicyType": "ON_FAILURE", "restartPolicyMaxRetries": 3 } } ``` > [!NOTE] > > Railway's config-as-code only covers build/deploy settings for a single service, not full project scaffolding. Environment variables must still be set in the dashboard. ## Environment-specific configuration Use Railway's [environments](https://docs.railway.com/reference/environments) for staging vs production: ```json railway.json theme={null} { "$schema": "https://railway.com/railway.schema.json", "build": { "dockerfilePath": "ops/Dockerfile" }, "deploy": { "restartPolicyType": "ON_FAILURE" }, "environments": { "production": { "deploy": { "numReplicas": 3, "restartPolicyMaxRetries": 5 } }, "staging": { "deploy": { "numReplicas": 1, "restartPolicyMaxRetries": 1 } } } } ``` ## Tuning worker concurrency For high-throughput workloads, you can tune how aggressively the worker pulls and executes tasks from Temporal. Add these environment variables to the worker service: ```bash theme={null} TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_EXECUTIONS=150 TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS=50 TEMPORAL_MAX_CACHED_WORKFLOWS=50 TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_POLLS=10 TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_POLLS=10 ``` The defaults work for most workloads. Only tune these if you're seeing task queue backlog in the Temporal UI. See [Worker Tuning](/operations/worker-tuning) for the effect of each setting and Temporal Worker tuner examples. ## Monitoring ### Railway dashboard Railway provides built-in metrics for: * CPU and memory usage * Network traffic * Deployment history and logs ### Temporal Cloud Monitor workflow executions in the [Temporal Cloud UI](https://cloud.temporal.io): * Active workflows * Failed executions * Workflow history ### Traces If you've enabled [remote tracing](/operations/deployment/advanced#remote-tracing-with-redis), traces are stored in Redis and optionally uploaded to S3. ## Scaling considerations | Scenario | Recommendation | | - | - | | Low traffic | 1 worker, 1 API instance | | Moderate traffic | 2-5 workers, 2 API instances | | High traffic | 5-30 workers, 3+ API instances | | Burst workloads | Configure aggressive auto-scaling thresholds (40-50% CPU) | Workers scale independently from the API. If workflows are queuing up in Temporal, add more workers. If API response times are slow, add more API instances. ## Troubleshooting ### Worker not picking up jobs 1. Check the Temporal UI for pending workflows 2. Verify `TEMPORAL_ADDRESS`, `TEMPORAL_NAMESPACE`, and `TEMPORAL_API_KEY` are correct 3. Check worker logs in Railway for connection errors ### Trace files not appearing 1. Verify `OUTPUT_REDIS_URL` is set and Redis is running 2. Check `OUTPUT_TRACE_REMOTE_ON=true` is set 3. For S3, verify AWS credentials have write access to the bucket ### Out of memory errors 1. Read the `Worker sizing` log at startup. It warns when the isolates could together commit more heap than the container allows 2. If the container is being killed, lower the `NODE_OPTIONS` percentage or `TEMPORAL_MAX_CACHED_WORKFLOWS` 3. If Node reports `ERR_WORKER_OUT_OF_MEMORY` while the container has memory to spare, the per-isolate cap is too low - raise the percentage 4. Upgrade Railway plan for more resources 5. Check for memory leaks in workflow code (large payloads, unbounded arrays) ### Credentials not found 1. Verify `config/credentials.yml.enc` (or the environment-scoped equivalent) exists in your repo and is committed 2. Verify `OUTPUT_CREDENTIALS_KEY` (or the environment-scoped variant) is set in Railway with the correct master key 3. Verify the Dockerfile includes `COPY config/ ./config/` — without it, the encrypted file never reaches the container ### Build failures 1. Check Dockerfile path is correct 2. Verify all dependencies are in `package.json` 3. Review build logs for specific errors # Deploy to Render Source: https://docs.output.ai/operations/deployment/render Step-by-step guide to deploying Output workflows on Render [Render](https://render.com) is a cloud platform that supports infrastructure-as-code via a `render.yaml` Blueprint. You define your services in a single file, connect your GitHub repo, and Render handles the rest. Here's what we'll do: * [**Create the worker Dockerfile**](#step-1-create-the-worker-dockerfile) — Add the `ops/` directory and Dockerfile to your repo * [**Create the Render Blueprint**](#step-2-create-the-render-blueprint) — Define the API, worker, and optional Redis in `render.yaml` * [**Deploy**](#step-3-deploy) — Connect your repo and provision all services * [**Verify**](#step-4-verify) — Confirm everything is connected end-to-end ## Project structure After running `output init`, your repository looks like this: ``` your-workflows/ ├── config/ │ ├── costs.yml │ └── credentials.yml.enc # encrypted credentials (committed) ├── src/ │ └── workflows/ │ └── your_workflow/ │ ├── workflow.ts │ ├── steps.ts │ └── ... ├── package.json └── tsconfig.json ``` This is the default structure — it doesn't include any deployment configuration yet. During this guide, we'll add an `ops/` directory containing a Dockerfile for the worker, and a `render.yaml` Blueprint at the root. ## Step 1: Create the worker Dockerfile Create the `ops/` directory and add `ops/render.Dockerfile` for your worker: ```dockerfile ops/render.Dockerfile theme={null} FROM node:24.15.0-slim ENV NODE_ENV=development WORKDIR /app # Required for Temporal's Rust-based client RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/* # Install dependencies (copy first to leverage Docker cache) COPY package.json package-lock.json ./ RUN npm run output:worker:install # Build the worker COPY src/ ./src/ COPY config/ ./config/ COPY tsconfig.json ./ RUN npm run output:worker:build # Clean up source files after build (config stays — credentials are needed at runtime) RUN rm -rf ./src tsconfig.json # Create non-root user for security RUN groupadd -r appuser && useradd -r -g appuser appuser RUN chown -R appuser:appuser /app USER appuser # Production settings ENV NODE_ENV=production ENV PATH="/app/node_modules/.bin:$PATH" # V8 heap per isolate = 40% of container memory (2 isolates by default, leaves room for Temporal Rust runtime + OS) ENV NODE_OPTIONS="--max-old-space-size-percentage=40 --heapsnapshot-signal=SIGUSR2" CMD ["output-worker"] ``` > [!TIP] > > The `NODE_OPTIONS` setting caps the V8 heap at 40% of container memory. The cap applies to each V8 isolate rather than to the process as a whole, and a worker runs one isolate on its main thread plus one per workflow thread, two by default. At 40%, both fit in the container with room left for the Temporal Rust runtime and OS overhead. If you raise `TEMPORAL_WORKFLOW_THREAD_POOL_SIZE`, lower the percentage so the isolate count times the percentage stays around 80. See [Memory and Isolates](/operations/worker-tuning#memory-and-isolates). Don't commit yet — we'll add the `render.yaml` Blueprint next and commit everything together. ## Step 2: Create the Render Blueprint Render's [Blueprint Spec](https://docs.render.com/infrastructure-as-code) lets you define your entire infrastructure in a single `render.yaml` file. When you connect your repo, Render reads this file and provisions all services automatically. Create `render.yaml` at the root of your repository: ```yaml render.yaml theme={null} previews: generation: off services: # API Service - deploys from pre-built Docker image - type: web name: your-project-output-api runtime: image image: url: docker.io/outputai/api:latest plan: pro region: oregon envVars: - key: TEMPORAL_ADDRESS value: .aws.api.temporal.io:7233 - key: TEMPORAL_NAMESPACE value: - key: TEMPORAL_API_KEY sync: false # Task queue the worker will listen on. Must match the OUTPUT_CATALOG_ID used by the worker. - key: OUTPUT_CATALOG_ID value: main - key: OUTPUT_API_AUTH_TOKEN generateValue: true scaling: minInstances: 1 maxInstances: 3 targetCPUPercent: 60 targetMemoryPercent: 60 # Worker Service - builds from your GitHub repo - type: worker name: your-project-output-worker runtime: docker repo: https://github.com/your-org/your-workflows branch: main plan: pro region: oregon dockerfilePath: ./ops/render.Dockerfile envVars: # Must match the OUTPUT_CATALOG_ID used in the API - key: OUTPUT_CATALOG_ID value: main - key: TEMPORAL_ADDRESS value: .aws.api.temporal.io:7233 - key: TEMPORAL_NAMESPACE value: - key: TEMPORAL_API_KEY sync: false # Master key for decrypting config/credentials/production.yml.enc # The only real secret needed — all other API keys live in encrypted credentials - key: OUTPUT_CREDENTIALS_KEY_PRODUCTION sync: false # LLM API keys — resolved from encrypted credentials at worker boot - key: ANTHROPIC_API_KEY value: credential:anthropic.api_key - key: OPENAI_API_KEY value: credential:openai.api_key scaling: minInstances: 1 maxInstances: 10 targetCPUPercent: 60 targetMemoryPercent: 60 ``` ### Adding Redis for remote tracing For production debugging, you can add Redis as a Render service and reference it using `fromService`. This keeps everything in one Blueprint and Render handles the connection string automatically: ```yaml render.yaml theme={null} services: # ... API and Worker services from above ... # Redis for remote tracing - type: redis name: your-project-output-cache plan: pro region: oregon ipAllowList: [] maxmemoryPolicy: allkeys-lru ``` Then add these env vars to your worker service to enable remote tracing: ```yaml theme={null} envVars: # ... other env vars ... - key: OUTPUT_REDIS_URL fromService: type: redis name: your-project-output-cache property: connectionString - key: OUTPUT_TRACE_REMOTE_ON value: true # Optional: persist traces to S3 - key: OUTPUT_TRACE_REMOTE_S3_BUCKET value: your-traces-bucket - key: OUTPUT_AWS_REGION value: us-west-1 - key: OUTPUT_AWS_ACCESS_KEY_ID sync: false - key: OUTPUT_AWS_SECRET_ACCESS_KEY sync: false ``` The `fromService` reference automatically injects the Redis connection string — no need to manage it manually. See [Advanced configuration](/operations/deployment/advanced) for more on remote tracing. ### Blueprint key concepts **Service types:** * `type: web` — The API. Render assigns it a public URL and routes HTTP traffic to it. * `type: worker` — The worker. No public URL, just runs your Dockerfile. **Secret handling with `sync: false`:** Variables marked `sync: false` are secrets. Render prompts you to enter their values when you first deploy the Blueprint. They won't be committed to your repo. ```yaml theme={null} - key: TEMPORAL_API_KEY sync: false # Render prompts for this during setup ``` **Auto-generated values:** Use `generateValue: true` for tokens that just need to be a random secure string. Render generates and stores the value for you. ```yaml theme={null} - key: OUTPUT_API_AUTH_TOKEN generateValue: true # Render creates a random secure value ``` ### API keys and credentials in production Your workflows need API keys (Anthropic, OpenAI, etc.) to run. Instead of pasting each key into Render as a separate secret, Output lets you store **all** your keys in one encrypted file that lives in your repo. Render only needs **one** secret — the master key that unlocks the file. Here's how it works: #### 1. Put all your API keys into encrypted credentials If you haven't already, initialize credentials and add your keys: ```bash theme={null} npx output credentials init --environment production npx output credentials edit --environment production ``` This opens an editor. Add all the API keys your workflows need: ```yaml theme={null} anthropic: api_key: sk-ant-... openai: api_key: sk-proj-... # Add any other keys your workflows use geekbot: api_key: api_... beehiiv: api_key: hNga... ``` Save and close. This creates two files: * `config/credentials/production.yml.enc` — the encrypted file. **Commit this to your repo.** It's encrypted and safe to push. * `config/credentials/production.key` — the master key. **Never commit this.** It's already in `.gitignore`. #### 2. Add the master key to Render Copy the contents of `config/credentials/production.key` and add it to your worker service in Render as a secret env var: ``` OUTPUT_CREDENTIALS_KEY_PRODUCTION = ``` This is the **only secret** you need to manage in Render. Everything else comes from the encrypted file. #### 3. Reference keys in your Blueprint with `credential:` In `render.yaml`, instead of setting each API key as a separate secret, pass a `credential:` reference as a plain string. The SDK resolves these automatically when the worker starts: ```yaml theme={null} envVars: # These are NOT the real keys — they're references that the SDK # resolves at boot from the encrypted credentials file. - key: ANTHROPIC_API_KEY value: credential:anthropic.api_key - key: OPENAI_API_KEY value: credential:openai.api_key ``` When the worker starts, the SDK reads these env vars, sees they start with `credential:`, decrypts the credentials file using the master key, and replaces the values with the real API keys — before any workflow code runs. > [!NOTE] > > The `credential:` pattern works for any env var the AI SDK or your code reads from `process.env`. Just add the key to your encrypted credentials and reference it in `render.yaml`. #### Rotating a key To change an API key in production: ```bash theme={null} npx output credentials edit --environment production # Change the key value, save, close git add config/credentials/production.yml.enc git commit -m "rotate anthropic key" git push ``` Render redeploys automatically. No env var changes needed — the master key stays the same. Commit the new files and push to GitHub before continuing: ```bash theme={null} git add ops/ render.yaml config/ git commit -m "Add worker Dockerfile and Render Blueprint" git push ``` ## Step 3: Deploy 1. Go to [Render's dashboard](https://dashboard.render.com) and click **New** → **Blueprint** 2. Connect your GitHub repository 3. Render detects `render.yaml` and shows the services it will create 4. Enter values for any `sync: false` secrets when prompted 5. Click **Apply** to provision all services > [!NOTE] > > Render assigns a `.onrender.com` subdomain to web services automatically. You can add a custom domain in the service settings. ## Step 4: Verify Once both services are running, verify the API is up and the worker has registered your workflows. 1. Check the API is healthy: ```bash theme={null} curl https://your-project-output-api.onrender.com/health ``` You should get a `200 OK` response. 2. Confirm the worker has connected and your workflows are registered via the catalog endpoint: ```bash theme={null} curl -H "Authorization: Basic " \ https://your-project-output-api.onrender.com/workflow/catalog ``` You should see a JSON response listing your registered workflows. If the list is empty, the worker may still be starting up — check the worker logs in Render and try again after a moment. 3. Run a workflow end-to-end: ```bash theme={null} curl -X POST https://your-project-output-api.onrender.com/workflow/run \ -H "Content-Type: application/json" \ -H "Authorization: Basic " \ -d '{ "workflowName": "your_workflow", "input": { "key": "value" } }' ``` ## Tuning worker concurrency For high-throughput workloads, you can tune how aggressively the worker pulls and executes tasks from Temporal. Add these to your worker's `envVars`: ```yaml theme={null} - key: TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_EXECUTIONS value: 150 - key: TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS value: 50 - key: TEMPORAL_MAX_CACHED_WORKFLOWS value: 50 - key: TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_POLLS value: 10 - key: TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_POLLS value: 10 ``` The defaults work for most workloads. Only tune these if you're seeing task queue backlog in the Temporal UI. See [Worker Tuning](/operations/worker-tuning) for the effect of each setting and Temporal Worker tuner examples. ## Monitoring ### Render dashboard Render provides built-in metrics for: * CPU and memory usage per service * Deploy history and logs ### Temporal Cloud Monitor workflow executions in the [Temporal Cloud UI](https://cloud.temporal.io): * Active workflows * Failed executions * Workflow history ### Traces If you've enabled [remote tracing](/operations/deployment/advanced#remote-tracing-with-redis), traces are stored in Redis and optionally uploaded to S3. ## Scaling considerations | Scenario | Recommendation | | - | - | | Low traffic | 1 worker, 1 API instance | | Moderate traffic | 2-5 workers, 2 API instances | | High traffic | 5-30 workers, 3+ API instances | | Burst workloads | Configure aggressive auto-scaling thresholds (40-50% CPU/memory) | Workers scale independently from the API. If workflows are queuing up in Temporal, add more workers. If API response times are slow, add more API instances. ## Troubleshooting ### Worker not picking up jobs 1. Check the Temporal UI for pending workflows 2. Verify `TEMPORAL_ADDRESS`, `TEMPORAL_NAMESPACE`, and `TEMPORAL_API_KEY` are correct 3. Check worker logs in Render for connection errors ### Trace files not appearing 1. Verify `OUTPUT_REDIS_URL` is set and Redis is running 2. Check `OUTPUT_TRACE_REMOTE_ON=true` is set 3. For S3, verify AWS credentials have write access to the bucket ### Out of memory errors 1. Read the `Worker sizing` log at startup. It warns when the isolates could together commit more heap than the container allows 2. If the container is being killed, lower the `NODE_OPTIONS` percentage or `TEMPORAL_MAX_CACHED_WORKFLOWS` 3. If Node reports `ERR_WORKER_OUT_OF_MEMORY` while the container has memory to spare, the per-isolate cap is too low - raise the percentage 4. Upgrade Render plan for more resources 5. Check for memory leaks in workflow code (large payloads, unbounded arrays) ### Credentials not found (`MissingCredentialError`) 1. Verify `config/credentials/production.yml.enc` exists in your repo (not just `config/credentials.yml.enc` — the Dockerfile sets `NODE_ENV=production`, which makes the SDK look for the scoped path) 2. Verify `OUTPUT_CREDENTIALS_KEY_PRODUCTION` is set in Render with the correct master key 3. Verify the Dockerfile includes `COPY config/ ./config/` — without it, the encrypted file never reaches the container 4. If using `credential:` references for API keys (e.g. `ANTHROPIC_API_KEY=credential:anthropic.api_key`), make sure the encrypted credentials file actually contains that key path ### Build failures 1. Check Dockerfile path matches `dockerfilePath` in `render.yaml` 2. Verify all dependencies are in `package.json` 3. Review build logs in the Render dashboard # Error Handling Source: https://docs.output.ai/operations/error-handling How workflow and activity interceptors classify errors, when execution retries or stops, and how to match causes with hasErrorType When something throws in your workflow, Output handles it differently depending on where it happens. Steps and evaluators are retried automatically. In workflow code, only explicit fatal failures end the run immediately — other throws retry the Workflow Task. You can control this with retry options, non-retryable errors, and try/catch. ## How interceptors classify errors Output's workflow and activity interceptors decide whether a failure ends the execution, retries, or is rethrown as Temporal already classified it. ### Workflow | Error | Behavior | | - | - | | `ContinueAsNew` | Ends the trace as continued-as-new and rethrows | | Cancellation (`isCancellation`) | Sinks a serialized error (without `stack`) and rethrows | | `FatalError` / `ValidationError` / `TransparentFatalError` | Unwraps `TransparentFatalError` to its cause, sinks the serialized error, and throws a non-retryable `ApplicationFailure` with the serialized error in `.details[0].error` — the workflow **fails** | | Temporal failures (`ActivityFailure`, `ChildWorkflowFailure`, other `TemporalFailure`) | Sinks the serialized error and rethrows unchanged. (`CancelledFailure` usually matches `isCancellation` first.) | | Other errors (`TypeError`, bad `JSON.parse`, unexpected throws) | Rethrown unchanged **without** sinking — the **Workflow Task retries** (or stays open until timeout). The CLI can look "stuck" until the task succeeds, times out, or you throw `FatalError` / an `ApplicationFailure` | ### Activity (steps and evaluators) | Error | Behavior | | - | - | | `CompleteAsyncError` | Recorded as an async handoff in the trace (not an error). No activity error hook. Rethrown | | Temporal failures (`TemporalFailure`) | Activity error hook and trace error fire, then rethrown unchanged | | `FatalError` / `ValidationError` / `TransparentFatalError` | Activity error hook and trace error fire (using the unwrapped cause for `TransparentFatalError`), then converted to `ApplicationFailure` with serialized error in `.details[0].error`. Always `nonRetryable: true`. User `nonRetryableErrorTypes` cannot make these retryable | | Other errors | Activity error hook and trace error fire, then converted to `ApplicationFailure` with serialized error in `.details[0].error`. `nonRetryable` when the error class name is listed in the activity retry policy's `nonRetryableErrorTypes` | `ValidationError` and `TransparentFatalError` both extend `FatalError`, so they share the fatal rows above. `TransparentFatalError` is only a transport: interceptors use its `.cause` for logs, traces, hooks, and failure details. See [FatalError, ValidationError, and TransparentFatalError](#fatalerror-validationerror-and-transparentfatalerror) for when to throw each. ## Steps and Evaluators When a step or evaluator throws, we retry it automatically with exponential backoff. After all retries are exhausted, the error propagates to the workflow (typically as an `ActivityFailure` cause chain). Default retry behavior: | Setting | Default | | - | - | | `initialInterval` | 10s | | `backoffCoefficient` | 2.0 | | `maximumAttempts` | 3 | | `nonRetryableErrorTypes` | `['FatalError']` | This means a failing step waits 10s, then 20s, then fails for good. You can override these per step via the `options.activityOptions` property — see [Step Options](/steps#options). Custom `nonRetryableErrorTypes` are added alongside `FatalError`; Output always keeps `FatalError` non-retryable. ## Workflows Errors in the workflow `fn` itself are classified as in the table above. Throw `FatalError` or `ValidationError` when the run must fail immediately. Ordinary bugs (for example a bad `JSON.parse`) retry the Workflow Task instead of failing the execution right away. You can catch step errors with try/catch and handle them however you want: ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { lookupCompany, generateSummary } from './steps.js'; import { EnrichmentInput, EnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', inputSchema: EnrichmentInput, outputSchema: EnrichmentOutput, fn: async (input) => { const company = await lookupCompany(input.companyDomain); let summary; try { summary = await generateSummary(company); } catch (error) { // Step failed after all retries — use a fallback summary = `${company.name} is a company in the ${company.industry} industry.`; } return { company: company.name, summary }; } }); // types.ts // import { z } from '@outputai/core'; // // export const EnrichmentInput = z.object({ // companyDomain: z.string() // }); // // export const EnrichmentOutput = z.object({ // company: z.string(), // summary: z.string() // }); ``` If you don't catch a step failure, it surfaces to the workflow as a Temporal failure and the workflow fails (unless you handle it). ### Checking error types in workflows Errors thrown by steps and evaluators cross Temporal's Activity boundary before they reach workflow code. Temporal serializes them into a failure cause chain, so a direct `error instanceof CustomError` check is not reliable inside a workflow. The same applies when Output wraps a failure in `ApplicationFailure` or `TransparentFatalError` — the error you care about is often on `.cause`, not the outer object. Use `hasErrorType(error, CustomError)` from `@outputai/core` to walk the complete cause chain. It matches native instances as well as Temporal's serialized `type` and `name` fields. Define the custom error in a shared module imported by both the step and workflow: ```typescript types.ts theme={null} export class CompanyNotFoundError extends Error {} ``` ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { CompanyNotFoundError } from './types.js'; export const lookupCompany = step({ name: 'lookup_company', fn: async () => { throw new CompanyNotFoundError('Company not found'); } }); ``` ```typescript workflow.ts theme={null} import { hasErrorType, workflow } from '@outputai/core'; import { lookupCompany } from './steps.js'; import { CompanyNotFoundError } from './types.js'; export default workflow({ name: 'company_lookup', fn: async () => { try { return await lookupCompany(); } catch (error) { if (hasErrorType(error, CompanyNotFoundError)) { return null; } // Preserve unexpected failures. throw error; } } }); ``` Always rethrow errors that do not match the type the workflow explicitly handles. ### Error metadata Trace destinations are stored in Temporal memo and exposed as the workflow result's `trace` field. They are available independently of whether the workflow succeeds or fails. Current API responses expose failures as a serialized `error` object with `name`, `message`, and any additional diagnostic properties captured from the original error. Activity failures also include `activityType` when available. If you inspect Temporal errors directly, workflow failures remain native Temporal errors such as `ApplicationFailure` or `ChildWorkflowFailure`. Output may store the serialized original error under `details[0].error` on a nested failure in the `.cause` chain. ```typescript theme={null} function getSerializedWorkflowError(error: unknown) { let current = error as { cause?: unknown; details?: unknown[] } | null; while (current) { const detail = current.details?.find((value) => value && typeof value === 'object' && 'error' in value ); if (detail && typeof detail === 'object' && 'error' in detail) { return detail.error; } current = current.cause as typeof current; } return null; } ``` ## FatalError, ValidationError, and TransparentFatalError Sometimes retrying won't help — the API key is invalid, the resource doesn't exist, or the data is fundamentally wrong. For these cases, throw `FatalError` or `ValidationError` to fail immediately without retries. `ValidationError` and `TransparentFatalError` extend `FatalError`. The entire `FatalError` family is always non-retryable and cannot be made retryable through activity options. Throw a regular or custom `Error` when retry configuration should control the behavior. | Error | Use when | | - | - | | `FatalError` | The failure is not recoverable. Retrying would not help (e.g. invalid API key, resource not found, business rule violation). | | `ValidationError` | The data is invalid. Use for custom validation checks alongside the framework's built-in schema validation. | | `TransparentFatalError` | An existing error must be non-retryable, but its original type, message, cause chain, and diagnostic properties should remain visible. | All three are exported from `@outputai/core`: ```typescript steps.ts theme={null} import { step, FatalError, ValidationError } from '@outputai/core'; import { getContact } from '../../clients/hubspot.js'; import { LookupContactInput, LookupContactOutput } from './types.js'; export const lookupContact = step({ name: 'lookupContact', description: 'Look up a contact in HubSpot', inputSchema: LookupContactInput, outputSchema: LookupContactOutput, fn: async (email) => { const contact = await getContact(email); if (contact.error === 'INVALID_API_KEY') { // Don't retry — the key won't fix itself throw new FatalError('HubSpot API key is invalid'); } if (!contact.properties?.email) { // Data doesn't match what we need throw new ValidationError('Contact has no email address'); } return { exists: true, contactId: contact.id, lifecycleStage: contact.properties.lifecyclestage }; } }); ``` `TransparentFatalError` accepts an existing `Error` as its cause. It has the same non-retryable behavior as `FatalError`, but Output removes the wrapper when reporting or propagating the failure. Logs, traces, hooks, and workflow results therefore show the original error rather than a generic fatal-error message. ```typescript theme={null} import { TransparentFatalError } from '@outputai/core'; try { await callProvider(); } catch (error) { if (error instanceof ProviderError && !error.isRetryable) { throw new TransparentFatalError(error); } throw error; } ``` ## Schema Validation The framework validates inputs and outputs automatically using your Zod schemas. When validation fails, it throws a `ValidationError` with a message that tells you exactly what went wrong. **Steps and evaluators:** Input is validated against `inputSchema` before `fn` runs. The return value is validated against `outputSchema` after `fn` returns. If either fails, the step fails immediately (no retries). **Workflows:** Input is validated against `inputSchema` before the workflow starts. Output is validated against `outputSchema` after the workflow returns. If either fails, the execution fails. The error message includes context like `"Step lookupContact input validation failed: ..."` so you can trace exactly where and why validation failed. # Error Hooks Source: https://docs.output.ai/operations/error-hooks Observe workflow, activity, and runtime errors without affecting execution Error hooks let you run code whenever a workflow, activity (step/evaluator), or runtime error occurs. Use them for logging, metrics, or alerting. When an error is emitted, all registered handlers are triggered at the same time (concurrently). Handler code is invoked asynchronously and never throws — any error in your handler is caught and logged by the framework. ## Setup ### 1. Create a hook file Create a file that registers your handler. Import `onError` from `@outputai/core/hooks`. ```javascript theme={null} // src/error_hooks.js import { onError } from '@outputai/core/hooks'; onError(async (payload) => { console.log('Error', payload); }); ``` ### 2. Register the file in package.json List your hook file(s) under `outputai.hookFiles`. Paths are relative to the package root. The worker loads these files at startup. ```json theme={null} { "name": "my-workflows", "outputai": { "hookFiles": ["./src/error_hooks.js"] } } ``` You can register multiple files: `"hookFiles": ["./src/error_hooks.js", "./src/other_hooks.js"]`. ## The three sources Errors are emitted from three origins. Every payload includes `eventId`, `eventDate`, `source`, and `error`. Activity- and workflow-scoped errors also include Temporal execution details. | Source | When it fires | Fields besides `eventId`, `eventDate`, `source`, and `error` | | - | - | - | | `activity` | A step, evaluator, or internal activity attempt fails (including attempts that Temporal will retry). | `activityInfo`, `workflowDetails`, `outputActivityKind` | | `workflow` | The workflow function itself throws (e.g. uncaught step error or logic error). | `workflowDetails` | | `runtime` | An error outside workflow/activity scope (e.g. in the worker/runtime). | — | So: * **Activity** — `eventId`, `eventDate`, `source: 'activity'`, `activityInfo`, `workflowDetails`, `outputActivityKind`, `error`. This includes internal activities. * **Workflow** — `eventId`, `eventDate`, `source: 'workflow'`, `workflowDetails`, `error` (no activity fields). * **Runtime** — `eventId`, `eventDate`, `source: 'runtime'`, and `error` only. `activityInfo` is Temporal's Activity execution info object; see Temporal's [`activity.Info`](https://typescript.temporal.io/api/interfaces/activity.Info) reference. `workflowDetails` is Output's serializable subset of Temporal's [`workflow.WorkflowInfo`](https://typescript.temporal.io/api/interfaces/workflow.WorkflowInfo), with fields such as `workflowId`, `runId`, `workflowType`, `parent`, and `root`. `outputActivityKind` identifies the Output activity type. Possible values are `step`, `evaluator`, and `internal_step`. Activity, runtime, and workflow error hooks all receive `Error` instances. Workflow errors are still serialized to cross Temporal's sandbox boundary, then rehydrated before hooks run — so `name`, `message`, an optional recursive `cause`, and other enumerable diagnostic properties survive. The value is always a bare `Error`, not the original subclass (`instanceof FatalError` is false even when `error.name === 'FatalError'`). Use `error.name`, or `hasErrorType(error, FatalError)` from `@outputai/core`, to distinguish failure kinds. `eventId` is a UUID v4 stamped per emit — use it as a stable idempotency key when forwarding errors to external systems (Sentry, PagerDuty, your own incident pipeline). `eventDate` is the millisecond epoch timestamp for when the event was emitted. Use `source` to branch in one handler, or ignore payload fields that are undefined for that source. Errors from the internal `$catalog` workflow are excluded. ## Handler safety: no throws Your handler is wrapped in a try/catch. If the handler throws or rejects, the framework catches it, logs it (e.g. `onError hook error` with the error), and does not rethrow. Execution of the workflow and worker continues. You can focus on side effects (logging, metrics, alerts) without worrying about breaking the run. ## Example ```javascript theme={null} // src/error_hooks.js import { onError } from '@outputai/core/hooks'; onError(async (payload) => { const { source, error } = payload; if (source === 'activity') { const { activityInfo, workflowDetails } = payload; console.error( `Step/evaluator failed: ${workflowDetails.workflowType} (${workflowDetails.workflowId}) / ${activityInfo.activityType} (${activityInfo.activityId})`, error ); } else if (source === 'workflow') { const { workflowDetails } = payload; console.error(`Workflow failed: ${workflowDetails.workflowType} (${workflowDetails.workflowId})`, error); } else { console.error('Runtime error', error); } }); ``` # External Workflow Packages Source: https://docs.output.ai/operations/external-workflow-packages Publish workflows as npm packages and call them from local Output workflows External workflow packages let you share reusable workflows across projects. Publish a normal npm package that exposes Output workflows, install it in another Output project, and call those workflows from your local workflow code. This is useful for workflow catalogs, shared internal automations, or reusable domain-specific workflows that multiple teams call as child workflows. ## What you'll build In this guide, we'll create an npm package with a post-call follow-up workflow, mark it as discoverable by Output, publish it, then install and call it from another project. ## Package requirements An external workflow package should: * Follow the standard Output file conventions: `workflow.js`, `steps.js`, `evaluators.js`, `shared/steps/*.js`, `shared/evaluators/*.js`, and so on. * Export workflows from the package entry point using static ESM re-exports. * Set `outputai.workflows.expose` to `true` in `package.json`. * Publish JavaScript files. If the package is authored in TypeScript, build `.js` files and matching `.d.ts` files before publishing. * Declare `@outputai/core` as a peer dependency. If your declaration files import `zod`, declare `zod` too. ## Step 1: Create the workflow package Create a package with the same shape as a regular Output project: ```text theme={null} sales-workflows/ ├── package.json └── src/ ├── index.ts ├── shared/ │ └── steps/ │ └── normalize_transcript.ts └── workflows/ └── post_call_followup/ ├── prompts/ │ └── draft_followup_email@v1.prompt ├── steps.ts └── workflow.ts ``` The workflow can call local child workflows, local steps, or package-level shared steps: ```typescript src/workflows/post_call_followup/workflow.ts theme={null} import { workflow, z } from '@outputai/core'; import { normalizeTranscript } from '../../shared/steps/normalize_transcript.js'; import { draftFollowUpEmail } from './steps.js'; export default workflow({ name: 'acmePostCallFollowup', description: 'Draft a follow-up email from a sales call transcript', inputSchema: z.object({ transcript: z.string(), accountName: z.string().optional() }), outputSchema: z.object({ subject: z.string(), body: z.string(), actionItems: z.array(z.string()) }), fn: async (input) => { const transcript = await normalizeTranscript(input.transcript); return draftFollowUpEmail({ transcript, accountName: input.accountName }); } }); ``` Workflow-specific steps stay next to the workflow: ```typescript src/workflows/post_call_followup/steps.ts theme={null} import { step, z } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; const followUpSchema = z.object({ subject: z.string(), body: z.string(), actionItems: z.array(z.string()) }); export const draftFollowUpEmail = step({ name: 'acmeDraftFollowUpEmail', description: 'Draft a concise follow-up email and action item list', inputSchema: z.object({ transcript: z.string(), accountName: z.string().optional() }), outputSchema: followUpSchema, fn: async ({ transcript, accountName }) => { const { output } = await generateText({ prompt: 'draft_followup_email@v1', variables: { transcript, accountName }, output: aiSdk.Output.object({ schema: followUpSchema }) }); return output; } }); ``` Shared activities live under `shared/steps` or `shared/evaluators` when more than one workflow in the package can use them: ```typescript src/shared/steps/normalize_transcript.ts theme={null} import { step, z } from '@outputai/core'; export const normalizeTranscript = step({ name: 'acmeNormalizeTranscript', description: 'Normalize whitespace in a call transcript', inputSchema: z.string(), outputSchema: z.string(), fn: async (transcript) => transcript.replace(/\s+/g, ' ').trim() }); ``` ## Step 2: Export the workflow Export workflows from the package entry point with static ESM re-exports: ```typescript src/index.ts theme={null} export { default as postCallFollowup } from './workflows/post_call_followup/workflow.js'; ``` Consumers import from this package entry point: ```javascript theme={null} import { postCallFollowup } from '@acme/sales-workflows'; ``` Avoid namespace imports when calling workflows from a package: ```javascript theme={null} // Not supported import * as salesWorkflows from '@acme/sales-workflows'; // Supported import { postCallFollowup } from '@acme/sales-workflows'; ``` ## Step 3: Mark the package as exposing workflows Add `outputai.workflows.expose` to `package.json`: ```json package.json theme={null} { "name": "@acme/sales-workflows", "version": "1.0.0", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": ["dist"], "scripts": { "build": "tsc" }, "peerDependencies": { "@outputai/core": ">=0.16.0", "zod": "^4.3.0" }, "outputai": { "workflows": { "expose": true } } } ``` This flag tells the Output worker that the package is intended to expose workflows for external discovery. Without it, the worker skips the package during automatic discovery. ## Step 4: Build and publish If the package is written directly in JavaScript, make sure the published files are included in npm. If the package is written in TypeScript, compile it before publishing: ```bash theme={null} pnpm build pnpm publish ``` Your published package should contain runnable `.js` files. `.d.ts` files are strongly recommended so consumer projects get correct types. ## Step 5: Install the package In the project that will call the external workflow: ```bash theme={null} pnpm add @acme/sales-workflows ``` Use your package manager of choice. The important part is that the package is installed in the workflow project's `node_modules`. ## Step 6: Call the workflow directly through the API When the worker starts, it discovers exposed workflow packages, registers their workflows, and loads package-level shared activities. You can call an external workflow by its `name` without writing a local wrapper workflow. For example, the package above registers `acmePostCallFollowup`: ```bash theme={null} curl -X POST http://localhost:3001/workflow/run \ -H "Content-Type: application/json" \ -d '{ "workflowName": "acmePostCallFollowup", "input": { "transcript": "Customer asked for pricing and implementation timeline.", "accountName": "Acme Corp" } }' ``` This is useful for shared internal automations and workflow catalogs where consumers should not need to write local workflow code just to run a packaged workflow. ## Step 7: Call from another workflow You can also import an external workflow and call it from local workflow code. Use this when the packaged workflow is one part of a larger local orchestration. Import the workflow from the npm package and call it inside your local workflow: ```typescript src/workflows/customer_call_review/workflow.ts theme={null} import { workflow, z } from '@outputai/core'; import { postCallFollowup } from '@acme/sales-workflows'; export default workflow({ name: 'customerCallReview', description: 'Review a customer call and prepare the next follow-up', inputSchema: z.object({ transcript: z.string(), accountName: z.string() }), outputSchema: z.object({ followUpSubject: z.string(), followUpBody: z.string(), nextSteps: z.array(z.string()) }), fn: async (input) => { const followUp = await postCallFollowup({ transcript: input.transcript, accountName: input.accountName }); return { followUpSubject: followUp.subject, followUpBody: followUp.body, nextSteps: followUp.actionItems }; } }); ``` Calls to imported workflows run as child workflows. ## Caveats ### Workflow names must be unique External workflow names share the same catalog as local workflow names. If two workflows use the same `name`, they collide. Choose stable, package-specific workflow names when publishing reusable workflows: ```javascript theme={null} workflow({ name: 'acmePostCallFollowup', // ... }); ``` ### Shared activity names can collide Package-level shared steps and evaluators are registered in the same shared namespace as local shared activities. If two shared activities use the same `name`, the later registration can overwrite the earlier one. Use descriptive shared activity names for published packages: ```javascript theme={null} step({ name: 'acmeNormalizeTranscript', // ... }); ``` ### Only exposed packages are auto-discovered The worker only scans packages with: ```json theme={null} { "outputai": { "workflows": { "expose": true } } } ``` If a workflow import rewrites successfully but the package is not exposed, the workflow may fail at runtime with a "workflow does not exist" error because it was not discovered by the worker. ### Use static ESM re-exports The worker resolves external workflow imports by statically following package entry point exports until it reaches `workflow.js` files. Use explicit ESM re-exports with relative paths: ```javascript theme={null} export { default as postCallFollowup } from './workflows/post_call_followup/workflow.js'; export * from './workflows/renewal_reminder/workflow.js'; ``` Dynamic exports, CommonJS re-exports, computed paths, and runtime export assembly are not supported for workflow discovery: ```javascript theme={null} // Not supported module.exports = { postCallFollowup }; exports.postCallFollowup = require('./workflows/post_call_followup/workflow.js'); ``` Namespace imports from workflow packages are also not supported. Import each workflow directly by name so the worker can map the local binding to the workflow runtime name. ### Keep workflow package code workflow-safe Workflow code runs in Temporal's workflow runtime. Avoid importing Node-only APIs or non-deterministic code from workflow files. ## Next steps After installing an external workflow package: * Start the worker and verify the external workflows appear in the catalog. * Trigger a local workflow that calls the external workflow. * Check traces to confirm the external workflow runs as a child workflow. # Testing Workflows and Steps Source: https://docs.output.ai/operations/testing Write deterministic unit tests for workflows, steps, and evaluators by calling them as plain functions Most of the interesting work in an Output app happens inside LLM calls — and LLM output is non-deterministic by nature. The same prompt can produce different results every time. That's why the primary quality tools for LLM-heavy apps are [evaluators](/evaluators) (LLM-as-a-judge) and humans reviewing [trace files](/operations/tracing) to annotate failure modes. Those are your first line of defense. But there's still plenty of deterministic logic worth testing the traditional way: data transformations, branching logic, schema validation, retry loops, and the glue code that ties your steps together. This page covers how to write those unit tests. Every exported step, evaluator, and workflow is a callable async function. Import it and call it — no Temporal server needed. ## Testing Steps Import the step and call it with input that matches its `inputSchema`. The return value is validated against `outputSchema` automatically. ```typescript steps.spec.ts theme={null} import { describe, it, expect } from 'vitest'; import { lookupCompany } from './steps.js'; describe('lookupCompany', () => { it('returns company data for a valid domain', async () => { const result = await lookupCompany('acme.com'); expect(result).toHaveProperty('name'); expect(result).toHaveProperty('industry'); expect(result.size).toBeGreaterThan(0); }); }); ``` If the input doesn't match `inputSchema` or the return value doesn't match `outputSchema`, it throws a `ValidationError` — see [Error Handling](/operations/error-handling). > [!NOTE] > > This test calls the real step implementation, including any API calls it makes. For fast, isolated tests, mock the external dependencies — see [Mocking Steps and Dependencies](#mocking-steps-and-dependencies) below. ## Testing Evaluators Same pattern. Import the evaluator and call it with input. The result is an `EvaluationResult` with `value`, `confidence`, and optional `reasoning`. Deterministic evaluators are especially good candidates for unit tests since they have predictable outputs: ```typescript evaluators.spec.ts theme={null} import { describe, it, expect } from 'vitest'; import { checkSummaryStructure } from './evaluators.js'; describe('checkSummaryStructure', () => { it('passes a well-formed summary', async () => { const result = await checkSummaryStructure({ summary: 'Acme Corp is a B2B SaaS company that provides CRM tools for mid-market sales teams. Founded in 2018, they have 250 employees and recently raised a Series B.', companyName: 'Acme Corp' }); expect(result.value).toBe(true); expect(result.confidence).toBe(1.0); }); it('fails a summary that is too short', async () => { const result = await checkSummaryStructure({ summary: 'Acme Corp sells software.', companyName: 'Acme Corp' }); expect(result.value).toBe(false); expect(result.reasoning).toContain('too short'); }); }); ``` You can test LLM-based evaluators the same way — just know that each test run makes a real API call, so it costs money and it will be unpredictable. If your judge prompt is well-designed (temperature set, clear criteria — see [Best Practices](/evaluators/best-practices)), the results should be somewhat consistent enough to assert against. Just keep these tests separate from your fast unit tests. ## Testing Workflows When a workflow runs outside Temporal (like in Vitest), it executes as a plain async function with a mock context. You'll typically want to mock your steps so the workflow logic runs without real API calls — this is where deterministic testing shines. You're testing your branching logic, retry loops, and data flow, not the LLM output. ```typescript workflow.spec.ts theme={null} import { describe, it, expect, vi, beforeEach } from 'vitest'; import { lookupCompany, generateSummary } from './steps.js'; vi.mock('./steps.js', () => ({ lookupCompany: vi.fn(), generateSummary: vi.fn() })); import leadEnrichmentWorkflow from './workflow.js'; describe('lead_enrichment workflow', () => { beforeEach(() => { vi.clearAllMocks(); }); it('enriches a company and generates a summary', async () => { vi.mocked(lookupCompany).mockResolvedValue({ name: 'Acme Corp', industry: 'SaaS', size: 250 }); vi.mocked(generateSummary).mockResolvedValue( 'Acme Corp is a SaaS company with 250 employees.' ); const result = await leadEnrichmentWorkflow({ companyDomain: 'acme.com' }); expect(lookupCompany).toHaveBeenCalledWith('acme.com'); expect(generateSummary).toHaveBeenCalled(); expect(result.company).toBe('Acme Corp'); expect(result.summary).toBeDefined(); }); }); ``` With mocked steps, you're testing that the workflow calls the right steps in the right order with the right data — and that it assembles the final output correctly. The LLM quality itself is handled by evaluators in production. ### Mock Context Outside Temporal, the framework injects a default mock context: * `context.info.workflowId` → `'test-workflow'` * `context.control.continueAsNew` → no-op async function * `context.control.isContinueAsNewSuggested()` → `false` You can override these by passing a `context` in the second argument. This is useful when your workflow logic depends on the workflow ID or other context values: ```typescript theme={null} const result = await leadEnrichmentWorkflow( { companyDomain: 'acme.com' }, { context: { info: { workflowId: 'test-run-123' } } } ); expect(result.workflowId).toBe('test-run-123'); ``` The `context` override only applies outside Temporal. When running in production, the real Temporal context is used. ### Mocking Steps and Dependencies In workflow tests, mock your step modules so no real I/O happens: ```typescript theme={null} vi.mock('./steps.js', () => ({ lookupCompany: vi.fn(), generateSummary: vi.fn() })); ``` If your workflow uses `sleep` or other utilities from `@outputai/core`, mock those too: ```typescript theme={null} vi.mock('@outputai/core', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, sleep: vi.fn().mockResolvedValue(undefined) }; }); ``` ### Testing Retry Logic If your workflow has a generate-evaluate-retry loop, you can test the branching by controlling what the mocked evaluator returns: ```typescript workflow.spec.ts theme={null} import { describe, it, expect, vi, beforeEach } from 'vitest'; import { lookupCompany, generateSummary } from './steps.js'; import { judgeSummaryQuality } from './evaluators.js'; vi.mock('./steps.js', () => ({ lookupCompany: vi.fn(), generateSummary: vi.fn() })); vi.mock('./evaluators.js', () => ({ judgeSummaryQuality: vi.fn() })); import leadEnrichmentWorkflow from './workflow.js'; describe('lead_enrichment retry logic', () => { beforeEach(() => { vi.clearAllMocks(); vi.mocked(lookupCompany).mockResolvedValue({ name: 'Acme Corp', industry: 'SaaS', size: 250 }); }); it('retries when the evaluator fails', async () => { vi.mocked(generateSummary) .mockResolvedValueOnce('Bad summary') .mockResolvedValueOnce('Acme Corp is a SaaS company with 250 employees.'); vi.mocked(judgeSummaryQuality) .mockResolvedValueOnce({ value: false, confidence: 0.3, reasoning: 'Too vague' }) .mockResolvedValueOnce({ value: true, confidence: 0.9, reasoning: 'Looks good' }); const result = await leadEnrichmentWorkflow({ companyDomain: 'acme.com' }); expect(generateSummary).toHaveBeenCalledTimes(2); expect(judgeSummaryQuality).toHaveBeenCalledTimes(2); expect(result.summary).toBe('Acme Corp is a SaaS company with 250 employees.'); }); }); ``` This is the sweet spot for deterministic testing in an LLM app — you're verifying that your workflow responds correctly to different evaluator outcomes without involving any actual LLM calls. ## What to Test vs. What to Evaluate | What you're checking | Best tool | | - | - | | Data transformations, schema validation | Unit tests | | Workflow branching and retry logic | Unit tests (mock steps + evaluators) | | Step calls the right API with the right params | Unit tests (mock the client) | | LLM output quality (accuracy, tone, relevance) | [Evaluators](/evaluators) (LLM-as-a-judge) | | End-to-end behavior across multiple LLM calls | [Tracing](/operations/tracing) + human review | | Regressions in LLM output over time | [Offline evals](/packages/core/evals) with saved datasets | The general rule: if the outcome is predictable, write a unit test. If it depends on LLM output, use evaluators and tracing instead. ## Offline Evaluation with Datasets Unit tests verify deterministic logic. But how do you catch regressions in LLM output quality across a set of known inputs? That's what offline evaluation is for. The [`@outputai/core/evals`](/packages/core/evals) module lets you run your workflow against saved datasets and check output quality using typed evaluators — without modifying your workflow code. You define evaluators with `verify()`, write dataset YAML files with expected inputs and ground truth, and run them via the CLI: ```bash theme={null} # Run evaluations using cached output (no workflow re-execution) output workflow test blog_generator --cached # Run with fresh execution and save results back to datasets output workflow test blog_generator --save ``` Evaluators can be deterministic (checking length, format, required fields) or use LLM judges for subjective quality. Results are reported as pass/partial/fail per dataset case, with a summary showing the overall acceptable rate. See the [Evals docs](/packages/core/evals) for the full guide on creating evaluators, writing datasets, and configuring eval workflows. See [CLI Evaluation Commands](/packages/cli#evaluation-commands) for the command reference. # Tracing: Full Visibility Source: https://docs.output.ai/operations/tracing How workflow execution is traced, where traces are stored, and how to enable local or remote tracing When an LLM workflow fails or produces bad output, you need to understand what happened — what data each step received, what the LLM returned, and where things went wrong. Tracing gives you that visibility. When tracing is enabled, each workflow run produces a trace: a tree of events showing the workflow and every step, evaluator, child workflow, LLM call, and HTTP call with their inputs, outputs, errors, and timing. Traces are written automatically when the worker runs. You don't need to add any instrumentation to your code — just turn tracing on and tell it where to write. ## What Gets Traced Each traced workflow execution produces a trace tree. The root is the workflow, and children are everything that ran inside it: * **Steps and evaluators** — input, output (or error), start/end timestamps. A step that is retried appears once per attempt, as sibling nodes, each with its own input, output or error, timing, and children; * **LLM calls** - the loaded prompt (`name`, `fileDir`, `variables`, rendered config/messages), the result, raw token usage, and normalized usage/cost attributes. Text calls also include merged `sources`; image calls do not; * **HTTP calls** — method, URL, status code. Requests made with `@outputai/core/http` appear as `http` events; workflow `sendHttpRequest` calls appear as internal activities; * **Internal activities** — Output-managed activities such as trace destination lookup and workflow HTTP requests; * **Child workflows** — nested as their own trees with the same structure This means you can open a trace file and see the full picture: which steps ran, what the LLM received and returned, how many tokens it used, and exactly where a failure happened. For prompts with skills, LLM trace `input.prompt` contains the loaded source prompt, including `config.skills`, but not the runtime-generated skill listing or `load_skill` tool added to the provider request. > [!WARNING] > > Trace files are not a secure storage boundary. They can include workflow inputs and outputs, step inputs and outputs, LLM prompts and results, activity inputs and outputs, URLs, payloads, and opt-in HTTP response bodies. Misconfigured HTTP requests can leak keys, tokens, cookies, signed URLs, or other sensitive data into trace files and Temporal history. Avoid putting secrets directly in workflow inputs, URLs, payloads, or literal headers; use the documented `$ENV_VAR_NAME` header placeholders for `sendHttpRequest` request header secrets. ## Enabling Tracing Tracing is **off by default**. You enable it with environment variables. Local tracing writes JSON files to disk — no extra services needed. Remote tracing uploads to S3 when a run completes (requires Redis to correlate events). You can disable trace generation for specific workflows with `options.disableTrace: true` — see [Workflow options](/workflows#native-options). **Local only (recommended to start):** ```bash theme={null} OUTPUT_TRACE_LOCAL_ON=true ``` Trace files appear at `logs/runs//_.json` under your project root. **Local + remote:** ```bash theme={null} OUTPUT_TRACE_LOCAL_ON=true OUTPUT_TRACE_REMOTE_ON=true OUTPUT_REDIS_URL=redis://localhost:6379 OUTPUT_TRACE_REMOTE_S3_BUCKET=my-traces OUTPUT_AWS_REGION=us-east-1 OUTPUT_AWS_ACCESS_KEY_ID=... OUTPUT_AWS_SECRET_ACCESS_KEY=... ``` ### All Environment Variables | Variable | Required when | Description | | - | - | - | | `OUTPUT_TRACE_LOCAL_ON` | Local tracing | Set to `true` to write trace files to disk | | `OUTPUT_TRACE_REMOTE_ON` | Remote tracing | Set to `true` to upload traces to S3 on run completion | | `OUTPUT_REDIS_URL` | Remote tracing | Redis address for correlating events before S3 upload | | `OUTPUT_REDIS_TRACE_TTL` | Remote tracing | TTL in seconds for Redis keys that accumulate trace events before a workflow is uploaded. Default: 7 days (`604800`). | | `OUTPUT_TRACE_REMOTE_S3_BUCKET` | Remote tracing | S3 bucket name | | `OUTPUT_AWS_REGION` | Remote tracing | AWS region for the bucket | | `OUTPUT_AWS_ACCESS_KEY_ID` | Remote tracing | AWS access key | | `OUTPUT_AWS_SECRET_ACCESS_KEY` | Remote tracing | AWS secret key | | `OUTPUT_TRACE_HOST_PATH` | Docker setups | Host path where trace files are mounted. The worker writes inside the container; this tells the API and CLI what path to report so you can open files on the host | | `OUTPUT_TRACE_HTTP_VERBOSE` | HTTP client tracing | Set to `true` or `1` to include request/response headers and bodies for `@outputai/core/http` trace events. Headers are redacted by header name, but bodies are recorded as-is. | ### AWS Credential Permissions The worker uploads each trace to S3 when the run completes, so its credentials (`OUTPUT_AWS_ACCESS_KEY_ID` / `OUTPUT_AWS_SECRET_ACCESS_KEY`) must allow **write** access to the trace bucket: | Action | Resource | Why | | - | - | - | | `s3:PutObject` | `arn:aws:s3:::/*` | Upload the trace file | | `s3:AbortMultipartUpload` | `arn:aws:s3:::/*` | Clean up an incomplete multipart upload if one fails partway | ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:AbortMultipartUpload" ], "Resource": "arn:aws:s3:::my-traces/*" } ] } ``` The API server reads those same traces back to serve `output workflow debug`, `cost`, and `dataset generate --download` — see [API Configuration](/api/configuration#aws-credential-permissions) for the read-side policy. The worker and API can share one key pair or use two identities each scoped to their own actions. ## Reading a Trace Each trace file is a single JSON object — the root workflow node. Every node in the tree has the same shape: | Field | Description | | - | - | | `id` | Unique identifier for this node. Workflow nodes use the run id. Steps, evaluators, and internal activities use `::`, so each attempt of a step, in each run, is a distinct node | | `kind` | Event kind. Common values include `workflow`, `step`, `evaluator`, `llm`, `http`, and `internal_step`. Other event kinds, such as `webhook`, can appear for specific workflow helpers. | | `name` | Workflow name or activity type | | `startedAt` / `endedAt` | Unix timestamps (ms) | | `input` | What the node received | | `output` | What the node returned (absent on error) | | `attributes` | Structured metadata keyed by attribute type, including normalized LLM usage and cost | | `error` | Error details with `name`, `message`, `stack` (absent on success) | | `children` | Array of child nodes (same shape) | ### Step with an LLM Call This is the most common trace shape you'll see. The step has the LLM call as a child, so you can see the loaded prompt (including interpolation variables), what the LLM returned, and how many tokens it used: ```json theme={null} { "id": "019a3c1f-8e4d-7a52-b0c6-1f7d9e2a4b83:1:1", "kind": "step", "name": "lead_enrichment#generateSummary", "startedAt": 1761952643861, "endedAt": 1761952649808, "input": { "name": "Acme Corp", "industry": "SaaS", "size": 250 }, "output": "Acme Corp is a B2B SaaS company...", "children": [ { "id": "generateText-1761952643867", "kind": "llm", "name": "generateText", "startedAt": 1761952643867, "endedAt": 1761952649806, "input": { "prompt": { "name": "generate_summary@v1", "fileDir": "/prompts", "variables": { "companyName": "Acme Corp", "industry": "SaaS" }, "config": { "provider": "anthropic", "model": "claude-sonnet-4-20250514" } } }, "output": { "result": "Acme Corp is a B2B SaaS company...", "usage": { "inputTokens": 38, "outputTokens": 204, "totalTokens": 242 }, "sources": [] }, "attributes": { "llm:generation:usage": { "type": "llm:generation:usage", "providerId": "anthropic", "modelId": "claude-sonnet-4-20250514", "promptName": "generate_summary@v1", "requestDetails": { "ids": ["req_011CgzuBM7cVrch6VjNcepAx"], "count": 1, "duration": 5939 }, "status": "complete", "input": 38, "output": 204, "total": 242, "items": [ { "group": "input", "label": null, "amount": 38 }, { "group": "output", "label": null, "amount": 204 } ] }, "llm:generation:cost": { "type": "llm:generation:cost", "providerId": "anthropic", "modelId": "claude-sonnet-4-20250514", "promptName": "generate_summary@v1", "requestDetails": { "ids": ["req_011CgzuBM7cVrch6VjNcepAx"], "count": 1, "duration": 5939 }, "status": "precise", "pricingFreshness": "cached", "input": 0.000114, "output": 0.00306, "total": 0.003174, "items": [ { "group": "input", "label": null, "amount": 38, "ppm": 3, "total": 0.000114, "status": "ok" }, { "group": "output", "label": null, "amount": 204, "ppm": 15, "total": 0.00306, "status": "ok" } ] }, "llm:usage": { "type": "llm:usage", "modelId": "claude-sonnet-4-20250514", "usage": [ { "type": "input", "ppm": 3, "amount": 38, "total": 0.000114 }, { "type": "output", "ppm": 15, "amount": 204, "total": 0.00306 } ], "total": 0.003174, "tokensUsed": 242 } }, "children": [] } ] } ``` The deprecated `llm:usage` attribute remains on priced LLM traces for compatibility. New trace readers should use `llm:generation:usage` and `llm:generation:cost`, which preserve normalized usage and detailed pricing separately. Both also record the `promptName` and the `requestDetails` of the call: provider request IDs, request count, and duration in milliseconds. See [Request details](/costs/cost-events#request-details). ### Failed Step When a step fails, it has an `error` object instead of `output`. The error includes the name, message, and stack trace: ```json theme={null} { "id": "019a3c1f-8e4d-7a52-b0c6-1f7d9e2a4b83:1:1", "kind": "step", "name": "lead_enrichment#lookupCompany", "startedAt": 1766083745644, "endedAt": 1766083745645, "error": { "name": "FatalError", "message": "HubSpot API key is invalid", "stack": "FatalError: HubSpot API key is invalid\n at fn (...steps.js:7:15)\n..." }, "children": [] } ``` The parent workflow node also gets an `error` when the run fails, so you can see at the root level that something went wrong. When a failed step is retried, each attempt is traced separately: you get one node per attempt, sharing the same `name` but differing in the trailing attempt number of the `id`. This lets you compare what each attempt received, how it failed, and how long the backoff between attempts was. ### Full Workflow Trace A complete trace puts it all together — the workflow root with all its step children: ```json theme={null} { "id": "019a3c1f-8e4d-7a52-b0c6-1f7d9e2a4b83", "kind": "workflow", "name": "lead_enrichment", "startedAt": 1769527009211, "endedAt": 1769527009265, "input": { "companyDomain": "acme.com" }, "output": { "company": "Acme Corp", "summary": "Acme Corp is a B2B SaaS company..." }, "children": [ { "id": "019a3c1f-8e4d-7a52-b0c6-1f7d9e2a4b83:1:1", "kind": "step", "name": "lead_enrichment#lookupCompany", "startedAt": 1769527009222, "endedAt": 1769527009223, "input": "acme.com", "output": { "name": "Acme Corp", "industry": "SaaS", "size": 250 }, "children": [] }, { "id": "019a3c1f-8e4d-7a52-b0c6-1f7d9e2a4b83:2:1", "kind": "step", "name": "lead_enrichment#generateSummary", "input": { "name": "Acme Corp", "industry": "SaaS", "size": 250 }, "output": "Acme Corp is a B2B SaaS company...", "children": [{ "kind": "llm", "..." : "..." }] }, { "id": "019a3c1f-8e4d-7a52-b0c6-1f7d9e2a4b83:3:1", "kind": "evaluator", "name": "lead_enrichment#judgeSummaryQuality", "input": { "summary": "Acme Corp is a B2B SaaS company...", "companyName": "Acme Corp" }, "output": { "value": true, "confidence": 0.92, "reasoning": "Meets all criteria" }, "children": [{ "kind": "llm", "..." : "..." }] } ] } ``` ### Child Workflows Child workflows appear as `kind: "workflow"` children with their own nested tree of steps: ```json theme={null} { "id": "019a3c1f-9b21-7c07-8d4a-5e6f0a1b2c34", "kind": "workflow", "name": "child_workflow", "startedAt": 1766179342625, "endedAt": 1766179342636, "input": { "companyDomain": "acme.com" }, "output": { "result": "..." }, "children": [ { "id": "019a3c1f-9b21-7c07-8d4a-5e6f0a1b2c34:1:1", "kind": "step", "name": "child_workflow#someStep", "..." : "..." } ] } ``` A child workflow shares its parent's trace file, and Temporal numbers activity ids per run, so a parent step and a child step can both be activity `1`. The run id in each step's `id` is what keeps them apart. ### Continue-as-New When a workflow calls [continueAsNew](/workflows/context#continueasnew), the trace records `"<>"` as the output for that run. The new run keeps the same workflow ID but gets a new start time — each run produces its own trace file. To see the full chain, list trace files for that workflow name and match by workflow ID; sort by timestamp for order. ## Accessing Traces You can access traces in three ways: * **Directly** — Open the JSON files at `logs/runs//` * **Via API** — See [Get workflow trace log](/api#get-workflow-trace-log) * **Via CLI** — See [output workflow debug](/packages/cli#output-workflow-debug) The CLI never reads S3 itself. `output workflow debug`, `output workflow cost`, and `output workflow dataset generate --download` all fetch traces through the API's trace-log endpoint, and the API reads remote traces from S3. The API's AWS credentials therefore need `s3:GetObject` and `s3:ListBucket` on the trace bucket — see [API Configuration](/api/configuration#aws-credential-permissions). # Worker Shutdown Source: https://docs.output.ai/operations/worker-shutdown How an Output worker stops on a deploy, how to size the shutdown settings against your platform, and how to read the shutdown logs After this page you can size the worker's shutdown settings against your platform's kill window, and tell from the logs whether a deploy drained cleanly or abandoned work. Every deploy sends your worker `SIGTERM`. The worker stops taking new work, gives in-flight steps time to finish, then exits. Three settings control that sequence, and together they have to fit inside the time your platform allows before it sends `SIGKILL`. ## What Happens on SIGTERM `SIGTERM`, `SIGINT`, and `SIGUSR2` start a graceful shutdown. With the defaults, counted from the signal: | Time | What happens | | - | - | | `0s` | The worker stops polling and starts draining. In-flight steps keep running. | | `15s` (`TEMPORAL_SHUTDOWN_GRACE_TIME`) | Steps still running are asked to cancel. The worker keeps waiting for them. | | `20s` (`TEMPORAL_SHUTDOWN_FORCE_TIME`) | The worker gives up draining and abandons whatever is still running. | | after the drain | The worker closes its Temporal connection, then awaits pending hook callbacks for up to `OUTPUT_HOOK_FLUSH_TIMEOUT_MS` (`5s`), and exits. | Grace and force are both measured from the moment shutdown starts. They run in parallel and are not added together. Grace is when cancellation is requested, and force is the cap on how long the drain can take. A second signal more than a second after the first exits immediately and abandons the drain. ## The Settings | Variable | Default | Effect | | - | - | - | | `TEMPORAL_SHUTDOWN_GRACE_TIME` | `15s` | Time steps get to finish on their own before they are asked to cancel. | | `TEMPORAL_SHUTDOWN_FORCE_TIME` | `20s` | Time before the worker stops waiting and abandons running work. Keep it above the grace time, otherwise cancellation has no window to take effect. | | `OUTPUT_HOOK_FLUSH_TIMEOUT_MS` | `5000` | Time to await pending hook callbacks once the drain is over. | The time variables accept milliseconds or duration strings such as `90s`. An empty value falls back to the default. The worker warns at startup when force time is not bigger than grace time. For the underlying options see Temporal's [`WorkerOptions`](https://typescript.temporal.io/api/interfaces/worker.WorkerOptions). ## Sizing Against Your Platform The worst case is the drain running to its bound, then the flush running to its own: ```text theme={null} TEMPORAL_SHUTDOWN_FORCE_TIME + OUTPUT_HOOK_FLUSH_TIMEOUT_MS < platform window ``` The defaults total 25 seconds against the 30 seconds Render and Kubernetes allow by default. A clean shutdown usually finishes well before that, so the bound only matters when work is still running. If your slowest step takes 90 seconds, give it that long to finish and raise the platform window with it. Raise the window first, because values above it never take effect: the platform terminates the process before they expire. ```bash .env theme={null} TEMPORAL_SHUTDOWN_GRACE_TIME=90s TEMPORAL_SHUTDOWN_FORCE_TIME=120s ``` The worst case is now 125 seconds, so allow 150: ```yaml render.yaml theme={null} services: - type: worker name: research-worker runtime: docker maxShutdownDelaySeconds: 150 ``` ```yaml deployment.yaml theme={null} spec: template: spec: terminationGracePeriodSeconds: 150 ``` See Render's [Blueprint spec](https://render.com/docs/blueprint-spec) for `maxShutdownDelaySeconds` and [Deploys](https://render.com/docs/deploys) for the deploy lifecycle. On Kubernetes, `terminationGracePeriodSeconds` is described in [Pod lifecycle](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/). > [!NOTE] > > Uncaught exceptions and unhandled rejections start the same drain, but it is capped at 60 seconds regardless of `TEMPORAL_SHUTDOWN_FORCE_TIME`. Raising the settings only extends shutdowns started by a signal. ## What Happens to Work That Does Not Finish When grace expires, Temporal sends a cancellation request to every step still running. That is all it does: Output does not pass the cancellation signal to your step's HTTP or LLM calls, so a step stops only when its own code observes it. See Temporal's [cancellation guide](https://docs.temporal.io/develop/typescript/cancellation) and the activity [`Context`](https://typescript.temporal.io/api/classes/activity.Context). * **A step that honors cancellation** ends its attempt as failed, and Temporal retries it on another worker right away. * **A step that ignores it** keeps running until force time. The worker then abandons it and exits. Temporal only learns that an abandoned step died when its heartbeat times out. By default steps heartbeat every 2 minutes (`OUTPUT_ACTIVITY_HEARTBEAT_INTERVAL_MS`) against a `heartbeatTimeout` of 5 minutes, so the retry starts within about 5 minutes of the deploy, on a worker that is still up. A step whose options set a longer `heartbeatTimeout` waits that long instead. `OUTPUT_ACTIVITY_HEARTBEAT_ENABLED=false` only stops the worker from sending heartbeats. The step's `heartbeatTimeout` still applies, so it does not delay the retry. See Temporal's [activity failure detection](https://docs.temporal.io/encyclopedia/detecting-activity-failures) and [retry policies](https://docs.temporal.io/encyclopedia/retry-policies). > [!WARNING] > > An abandoned step is retried from the start, so its side effects can run twice. Make steps that write to external systems idempotent. Workflow code is not affected. A workflow task the worker abandons times out and Temporal reschedules it on another worker, which replays the workflow from its history. See Temporal's [workflow task timeout](https://docs.temporal.io/encyclopedia/detecting-workflow-failures#workflow-task-timeout). ## Exit Codes | Exit code | Meaning | | - | - | | `0` | A signal requested the shutdown. This holds even when work was abandoned at force time, because a drain that is cut off at force time is the expected outcome of a deploy, not a failure. | | `1` | Startup failed, the Temporal connection was lost, an uncaught error ended the process, or a second signal forced an immediate exit. | A service failing to stop is logged as a warning and never changes the exit code. If you alert on non-zero worker exits, a deploy no longer triggers one just because steps were still running. The exit code does not report a worker that failed for another reason while draining. Temporal logs that as an error-level `Worker failed`, and only the expired force timer is demoted to a warning. Alert on that log line, not on the exit code. ## Reading the Shutdown Logs The worker logs its budget when shutdown starts, so the numbers are in the log even if the platform kills the process before it exits: ```text theme={null} [info] Worker: Shutting down { shutdownForceTimeMs: 20000, shutdownGraceTimeMs: 15000, hookFlushTimeoutMs: 5000 } [info] Worker Shutdown: Stopping Worker... [info] Worker Shutdown: Stopping Worker complete { shutdownDurationMs: 3120 } [info] Worker: Flushing hook callbacks... [info] Worker: Bye { exitCode: 0, shutdownDurationMs: 3340 } ``` The samples use the development format, `[level] namespace: message { fields }`. Production logs are JSON with the same level, namespace, message and fields. The `Bye` line is the last one, and its `shutdownDurationMs` is the time the whole shutdown took, hook flush included. Compare it with `maxShutdownDelaySeconds` or `terminationGracePeriodSeconds` to see how much margin you have. When work was abandoned at force time you see this instead: ```text theme={null} [warn] Temporal: Worker failed { error: { name: "GracefulShutdownPeriodExpiredError", ... } } [warn] Worker Shutdown: Stopping Worker failed { error: { name: "IllegalStateError", message: "Worker still in use: ...", ... }, shutdownDurationMs: 20004 } [info] Worker: Bye { exitCode: 0, shutdownDurationMs: 20190 } ``` `Worker failed` is Temporal reporting that the force timer expired. Output logs it as a warning, since an expired force timer is an expected outcome of a deploy. `IllegalStateError: Worker still in use` follows from it: the abandoned steps still hold native calls, so Temporal cannot finish closing the worker. A `shutdownDurationMs` near `shutdownForceTimeMs` on `Stopping Worker failed` confirms the drain hit its bound. `OUTPUT_TEMPORAL_LOG_LEVEL` controls these Temporal logs. At `ERROR` the `Worker failed` warning is not logged, because it is no longer an error. If this happens on most deploys, your steps run longer than the window. Raise grace and force together with the platform window as shown above, or make long steps observe cancellation so they end at grace instead of at force. ## Next Steps > [card] [Deployment](/operations/deployment) > > Deploy workers to Render, Railway, or your own platform. > [card] [Worker Tuning](/operations/worker-tuning) > > Concurrency, polling, and memory settings for the worker. # Worker Tuning Source: https://docs.output.ai/operations/worker-tuning Configure Temporal worker concurrency, polling, cache size, and Worker tuners Output workers run workflows and activities through Temporal. These settings control compute, memory, and IO behavior: * **Compute:** how many Workflow and Activity Tasks can execute concurrently. * **Memory:** how many Workflow Executions stay in the sticky cache. * **IO:** how many pollers long-poll Temporal for new tasks. Start with the defaults. Tune only when you see backlog in Temporal, high memory use, underused CPU, or task timeouts. ## Concurrency and Polling These env vars map to Temporal worker execution slots, cache, and pollers. See Temporal's [Worker performance guide](https://docs.temporal.io/develop/worker-performance), [Worker tuning quick reference](https://docs.temporal.io/develop/worker-tuning-reference), and [`WorkerOptions`](https://typescript.temporal.io/api/interfaces/worker.WorkerOptions). | Variable | Default | Resource | Effect | | - | - | - | - | | `TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_EXECUTIONS` | `40` | Compute | Maximum Activity Task executions running at once. Each Output step, evaluator, LLM call wrapper, or API call is usually an activity. Raise this to process more activities concurrently; lower it to reduce memory, CPU, or outbound API pressure. | | `TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS` | Temporal's (`40`) | Compute | Maximum Workflow Task executions running at once. Workflow Tasks are usually lightweight state-machine work. Raise this if Workflow Task backlog grows and CPU is low; lower it if Workflow Task timeouts increase. | | `TEMPORAL_MAX_CACHED_WORKFLOWS` | Temporal's (from heap) | Memory | Maximum Workflow Executions kept in Temporal's [sticky workflow cache](https://docs.temporal.io/sticky-execution). Higher values reduce workflow replay work; lower values free memory sooner after traffic spikes. Unset, Temporal sizes it from the isolate's heap limit, assuming roughly 600 cached Workflow Executions per GB - set it explicitly where payloads are heavier. | | `TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_POLLS` | `5` | IO | Number of concurrent Activity Task pollers. Raise this if activity execution slots are available but the worker is not fetching tasks fast enough. Keep it lower than activity execution slots. | | `TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_POLLS` | `5` | IO | Number of concurrent Workflow Task pollers. Raise this if workflow execution slots are available but polling is the bottleneck. Keep it lower than workflow execution slots. | | `TEMPORAL_WORKFLOW_THREAD_POOL_SIZE` | Temporal's (`1`) | Memory | Number of threads running workflow sandboxes. Each one is a separate V8 isolate, so this multiplies the heap the process can commit. See [Memory and isolates](#memory-and-isolates). | Example: ```bash theme={null} TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_EXECUTIONS=150 TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS=50 TEMPORAL_MAX_CACHED_WORKFLOWS=50 TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_POLLS=10 TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_POLLS=10 ``` ## Memory and Isolates A worker runs one V8 isolate on its main thread and one more per workflow thread, so the isolate count is `1 + TEMPORAL_WORKFLOW_THREAD_POOL_SIZE`. A `NODE_OPTIONS` heap cap applies to each isolate separately, not to the process as a whole. On a 4 GB container, `--max-old-space-size-percentage=85` lets every isolate grow to about 3.4 GB, so two isolates can commit well past what the container holds. Size the cap against the isolate count rather than the container. The worker logs a `Worker sizing` record at startup with the isolate count, the heap limit it resolved, the heap all isolates could commit together, and the container limit. It warns when that projection exceeds the container, and when there are more Workflow Task slots than cached Workflow Executions - in which case tasks evict each other and the worker replays history to recover. ## Worker Tuner `TEMPORAL_WORKER_TUNER` accepts a JSON-encoded Temporal [`WorkerOptions.tuner`](https://typescript.temporal.io/api/interfaces/worker.WorkerOptions#tuner). Use it when fixed concurrency limits are too rigid and you want Temporal's slot suppliers to control how many tasks the worker accepts. Resource-based auto-tuning is most useful for avoiding out-of-memory failures and absorbing bursts of low-resource work, such as Activities that spend most of their time waiting on external HTTP or I/O. Temporal recommends validating it by monitoring host CPU and memory under full load and confirming they settle near your configured targets. See Temporal's [resource-based auto-tuning announcement](https://temporal.io/blog/resource-based-auto-tuning-for-workers) for the model behind the feature. Choose exactly one tuner shape: * **Resource-based tuner:** one set of `tunerOptions`, plus optional `*SlotOptions`. * **Mixed slot suppliers:** one `*SlotSupplier` object for each task type. Do not mix `tunerOptions` / `*SlotOptions` with `*SlotSupplier` fields in the same JSON object. When `TEMPORAL_WORKER_TUNER` is set, Output passes it to Temporal as `tuner` and does not pass these incompatible execution options: * `TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_EXECUTIONS` * `TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS` Polling and cache settings still apply: * `TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_POLLS` * `TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_POLLS` * `TEMPORAL_MAX_CACHED_WORKFLOWS` * `TEMPORAL_WORKFLOW_THREAD_POOL_SIZE` ### Resource-Based Tuner Use a [`ResourceBasedTuner`](https://typescript.temporal.io/api/interfaces/worker.ResourceBasedTuner) to let Temporal adjust slots based on target CPU and memory usage. This is the simpler tuner shape. You can provide only workflow and activity slot options; Temporal applies defaults for local activity and Nexus slots. ```bash theme={null} TEMPORAL_WORKER_TUNER='{ "tunerOptions": { "targetMemoryUsage": 0.8, "targetCpuUsage": 0.9 }, "workflowTaskSlotOptions": { "minimumSlots": 2, "maximumSlots": 1000, "rampThrottle": "10ms" }, "activityTaskSlotOptions": { "minimumSlots": 1, "maximumSlots": 100, "rampThrottle": "50ms" } }' ``` Resource-based fields: | Field | Effect | | - | - | | `targetMemoryUsage` | Target process memory usage as a fraction from `0` to `1`. | | `targetCpuUsage` | Target process CPU usage as a fraction from `0` to `1`. | | `minimumSlots` | Slots issued regardless of current resource checks. | | `maximumSlots` | Upper bound for slots of that task type. | | `rampThrottle` | Minimum delay before issuing another slot after `minimumSlots` is reached. | ### Mixed Slot Suppliers Use a [`TunerHolder`](https://typescript.temporal.io/api/interfaces/worker.TunerHolder) to choose a slot supplier per task type. This is useful when workflow tasks should remain fixed but activities should scale with CPU and memory. ```bash theme={null} TEMPORAL_WORKER_TUNER='{ "workflowTaskSlotSupplier": { "type": "fixed-size", "numSlots": 10 }, "activityTaskSlotSupplier": { "type": "resource-based", "tunerOptions": { "targetMemoryUsage": 0.8, "targetCpuUsage": 0.9 }, "minimumSlots": 1, "maximumSlots": 100, "rampThrottle": "50ms" }, "localActivityTaskSlotSupplier": { "type": "fixed-size", "numSlots": 10 }, "nexusTaskSlotSupplier": { "type": "fixed-size", "numSlots": 10 } }' ``` > [!NOTE] > > When using the per-task supplier form, Temporal requires all four supplier fields: `workflowTaskSlotSupplier`, `activityTaskSlotSupplier`, `localActivityTaskSlotSupplier`, and `nexusTaskSlotSupplier`. Omitting local activity or Nexus suppliers can fail worker startup. Supplier types: | Type | Fields | Effect | | - | - | - | | `fixed-size` | `numSlots` | Always allows up to a fixed number of slots for that task type. | | `resource-based` | `tunerOptions`, `minimumSlots`, `maximumSlots`, `rampThrottle` | Dynamically adjusts slots based on CPU and memory targets. | Temporal also supports custom slot suppliers in code, but `TEMPORAL_WORKER_TUNER` is JSON and should be used only for fixed-size and resource-based suppliers. ## What to Watch Use Temporal metrics before changing values. The main question is whether the worker has no execution capacity left, or whether it has capacity but is not polling fast enough. See Temporal's [SDK metrics reference](https://docs.temporal.io/references/sdk-metrics), [Worker health](https://docs.temporal.io/cloud/worker-health), and [performance bottlenecks guide](https://docs.temporal.io/troubleshooting/performance-bottlenecks). | Signal | Meaning | Tuning response | | - | - | - | | High `temporal_workflow_task_schedule_to_start_latency` or `temporal_activity_schedule_to_start_latency` | Tasks are waiting in the queue before a worker starts them. | Check slots, pollers, worker count, and host CPU/memory. | | `temporal_worker_task_slots_available` near zero | Worker execution slots are full. | Increase execution slots, add workers, or use resource-based slots if host resources are available. | | High schedule-to-start latency while slots are often available | The worker may not be polling fast enough. | Increase the matching poller count. | | High host memory | Worker process or workflow cache is too large for the host. | Lower activity slots, lower `TEMPORAL_MAX_CACHED_WORKFLOWS`, or use a resource-based tuner with a lower `targetMemoryUsage`. | | Low CPU/memory with growing backlog | The worker has host capacity but is not accepting enough work. | Raise execution slots, raise pollers, or add resource-based activity slots with a higher `maximumSlots`. | ## Choosing Values If memory is high, lower activity slots first. Activities usually hold network responses, LLM payloads, browser state, or other heavier objects. If Temporal shows activity backlog and the worker has spare CPU and memory, raise activity execution slots or use a resource-based tuner with a higher `maximumSlots`. If workflow task backlog grows while CPU is low, check `temporal_worker_task_slots_available` first. If workflow slots are depleted, raise workflow task execution slots. If slots are available but schedule-to-start latency is high, raise workflow task pollers. If workflow task timeouts increase, lower workflow task execution slots. If CPU and memory vary heavily by workload, prefer `TEMPORAL_WORKER_TUNER` with resource-based activity slots over a large fixed activity concurrency. Tune incrementally and load test before applying large production changes. Temporal's [Introduction to Worker Tuning](https://temporal.io/blog/an-introduction-to-worker-tuning) is a good overview of when to scale workers horizontally versus increasing per-worker slots or pollers. ## Useful Links * [Worker performance](https://docs.temporal.io/develop/worker-performance) — Temporal's main guide for slots, pollers, task queue metrics, and tuning process. * [Worker tuning quick reference](https://docs.temporal.io/develop/worker-tuning-reference) — compute, memory, and IO settings by SDK. * [Resource-based auto-tuning for Workers](https://temporal.io/blog/resource-based-auto-tuning-for-workers) — explanation of resource-based slot suppliers and when to use them. * [An introduction to Worker tuning](https://temporal.io/blog/an-introduction-to-worker-tuning) — conceptual guide to worker capacity, schedule-to-start latency, pollers, and slots. * [Worker deployment and performance](https://docs.temporal.io/best-practices/worker) — production worker best practices and monitoring guidance. * [Temporal SDK metrics reference](https://docs.temporal.io/references/sdk-metrics) — metric names for slots, pollers, request latency, and schedule-to-start latency. * [Performance bottlenecks troubleshooting](https://docs.temporal.io/troubleshooting/performance-bottlenecks) — how to diagnose worker capacity and schedule-to-start issues. * [Monitor worker health](https://docs.temporal.io/cloud/worker-health) — Temporal Cloud monitoring signals for workers and task queues. # @outputai/cli Source: https://docs.output.ai/packages/cli Command-line interface for creating, running, and debugging Output workflows The `output` CLI is how you create projects, start development services, run workflows, and debug executions. It's the main way you interact with Output during development. ## Quick Start ```bash theme={null} # Create a new project npx @outputai/cli init cd # Start development services (Temporal, API, worker) npx output dev # Run a workflow with a test scenario npx output workflow run lead_enrichment acme ``` ## Command Reference | Command | Description | | - | - | | `output init` | Create a new project | | `output dev` | Start development services | | `output dev down` | Stop development services | | `output update` | Update CLI and agent configuration | | `output fix` | Align `package.json` with the current project template | | `output workflow plan` | Generate a workflow plan from a description | | `output workflow generate` | Generate workflow code from a plan | | `output workflow list` | List available workflows | | `output workflow runs list` | List recent workflow runs | | `output workflow run` | Run a workflow and wait for the result | | `output workflow start` | Start a workflow without waiting (`--monitor` to attach and stream) | | `output workflow status` | Check workflow execution status | | `output workflow monitor` | Attach to a run and stream status updates until it ends | | `output workflow result` | Get a completed workflow's result | | `output workflow stop` | Stop a workflow gracefully | | `output workflow terminate` | Force-stop a workflow | | `output workflow reset` | Rerun a workflow from after a completed step | | `output workflow debug` | Show the execution trace | | `output workflow cost` | Calculate execution cost from a trace | | `output workflow test` | Run evaluations against a workflow | | `output workflow dataset list` | List datasets for a workflow | | `output workflow dataset generate` | Generate a dataset from a scenario or trace | | `output credentials init` | Create an encryption key and encrypted credentials file | | `output credentials edit` | Edit encrypted credentials in `$EDITOR` | | `output credentials set` | Set a credential value by dot-notation path | | `output credentials get` | Print a credential value by dot-notation path | | `output credentials show` | Print all decrypted credentials | ## Project Commands ### output init Create a new Output project with the standard file structure: ```bash theme={null} output init [folder-name] ``` **folder-name** `string` Name of the project folder to create | Flag | Default | Description | | - | - | - | | `--skip-env` | false | Skip interactive environment variable setup | ### output dev Start all development services via Docker Compose: ```bash theme={null} output dev ``` This starts: | Service | URL | Description | | - | - | - | | **Temporal UI** | [http://localhost:8080](http://localhost:8080) | Monitor and debug workflows | | **API Server** | [http://localhost:3001](http://localhost:3001) | REST API for running workflows | | **Worker** | — | Processes workflows with auto-reload on `src/` changes | | **PostgreSQL** | — | Temporal persistence (container-internal) | | **Redis** | — | Caching layer (container-internal) | | **Temporal Server** | — | gRPC endpoint (container-internal) | | Flag | Default | Description | | - | - | - | | `--compose-file, -f` | — | Path to custom docker-compose file | | `--detached, -d` | false | Start services in the background and exit immediately | | `--image-pull-policy` | `always` | Image pull policy: `always`, `missing`, or `never` | > [!NOTE] > > Worker hot-reload does not watch `package.json`. After adding or changing dependencies, run `npm install`, then bring the stack down and start `output dev` again so the worker container reinstalls into its `node_modules` volume. Quitting a foreground `output dev` that owns the stack tears it down and is enough; if the stack is still running (an attached session, or one started with `output dev -d`), run `output dev down` first, then `output dev` again. #### Running multiple dev stacks You can run multiple isolated Output stacks on the same machine — useful when working across several projects simultaneously or testing against different versions. Each stack needs a unique project name and non-conflicting host ports. Set these in the project's `.env`: ```bash theme={null} # Project A (.env) — defaults, no changes needed DOCKER_SERVICE_NAME=project-a # Project B (.env) DOCKER_SERVICE_NAME=project-b OUTPUT_CATALOG_ID=project-b OUTPUT_API_HOST_PORT=3002 OUTPUT_TEMPORAL_UI_HOST_PORT=8081 OUTPUT_TEMPORAL_HOST_PORT=7234 ``` `DOCKER_SERVICE_NAME` isolates Docker networks, volumes, and container names so the stacks don't interfere with each other. `OUTPUT_CATALOG_ID` keeps each stack's workflow catalog separate. The three `OUTPUT_*_HOST_PORT` vars control which ports are exposed on your machine — the container-internal ports are unchanged, so workers in either stack still reach Temporal at `temporal:7233`. Run `npx output dev` in each project directory. Project A's API is at `http://localhost:3001` and Project B's at `http://localhost:3002`. If a port is already in use, `output dev` names the conflicting port and the env var to override. #### Attaching to a running stack If services are already running for this project, `output dev` attaches and monitors them instead of reporting a port collision on our own containers. An attached session does not own the stack: quitting the dashboard leaves the services running. The footer reads `ctrl+c detach (keeps running)` so you can tell which mode you're in. Stop an attached stack explicitly: ```bash theme={null} output dev down ``` A stack whose containers are all stopped is not an attach — `output dev` starts it in the foreground and tears it down on quit, as a fresh start would. ### output dev down Stop the development services started by `output dev`: ```bash theme={null} output dev down ``` Use this after `output dev -d`, or when an attached `output dev` session left the services running on quit. | Flag | Default | Description | | - | - | - | | `--compose-file, -f` | — | Path to custom docker-compose file | ### output dev eject Export the Docker Compose configuration so you can customize it: ```bash theme={null} output dev eject ``` | Flag | Default | Description | | - | - | - | | `--output, -o` | docker-compose.yml | Output path | | `--force, -f` | false | Overwrite existing file | ### output update Update the Output CLI and agent configuration: ```bash theme={null} output update ``` With no flags, updates everything. Use flags to update specific components: | Flag | Description | | - | - | | `--cli` | Update CLI packages only | | `--agents` | Update Claude Code agent configuration only | ### output fix Align the project's `package.json` with the current project template: ```bash theme={null} output fix ``` The command adds missing Output scripts, replaces outdated ones, removes deprecated ones, replaces an `@outputai/output` dependency with `@outputai/core` (dependency) and `@outputai/cli` (dev dependency) at the same version, and drops `outputai.hookFiles` entries that point to `@outputai/credentials`. It prints the planned changes and asks for confirmation before writing. If dependencies changed, reinstall afterwards. ## Workflow Commands ### output workflow plan Generate a workflow plan from a natural language description. The command prompts for a description, generates a plan using AI, and lets you iterate on it interactively. Type `ACCEPT` to save. ```bash theme={null} output workflow plan output workflow plan --description "Enrich leads by looking up company data and generating a summary" ``` | Flag | Default | Description | | - | - | - | | `--description, -d` | — | Workflow description (prompts if not provided) | | `--force-agent-file-write` | false | Force overwrite agent templates | ### output workflow generate Generate workflow code from a plan or description: ```bash theme={null} output workflow generate ``` **name** `string` *required* Name of the workflow to generate | Flag | Default | Description | | - | - | - | | `--skeleton, -s` | false | Generate minimal skeleton without examples | | `--description, -d` | — | Workflow description | | `--output-dir, -o` | workflows/ | Output directory | | `--force, -f` | false | Overwrite existing directory | | `--plan-file, -p` | — | Path to plan file for AI-assisted implementation | ```bash theme={null} # Generate a skeleton workflow output workflow generate lead_enrichment --skeleton # Generate from a saved plan output workflow generate lead_enrichment --plan-file .outputai/plans/2025_01_15_lead_enrichment/PLAN.md ``` ### output workflow list List available workflows from the catalog: ```bash theme={null} output workflow list output workflow list --format json --detailed ``` | Flag | Default | Description | | - | - | - | | `--format, -f` | list | Output format: list, table, json | | `--detailed, -d` | false | Show schemas and descriptions | | `--filter` | — | Filter by name | ### output workflow runs list List recent workflow runs, optionally filtered by workflow name: ```bash theme={null} output workflow runs list output workflow runs list lead_enrichment --limit 10 output workflow runs list lead_enrichment --format json ``` **workflowName** `string` Filter by workflow name (optional) | Flag | Default | Description | | - | - | - | | `--limit, -l` | 100 | Maximum runs to return | | `--format, -f` | table | Output format: table, json, text | ### output workflow run Run a workflow synchronously and wait for the result: ```bash theme={null} output workflow run [scenario] ``` **workflowName** `string` *required* Name of the workflow to execute **scenario** `string` Scenario name — resolved from the workflow's scenarios/ directory | Flag | Default | Description | | - | - | - | | `--input, -i` | — | JSON input or file path (overrides scenario) | | `--catalog, -c` | `OUTPUT_CATALOG_ID` | Catalog name (the deprecated `--task-queue, -q` aliases still work) | | `--search-attributes, -a` | — | Temporal [search attributes](/operations/deployment#search-attributes) as a JSON object or file path | | `--format, -f` | text | Output format: json, text | ```bash theme={null} # Using a scenario file (recommended for repeatable tests) output workflow run lead_enrichment acme # Using inline JSON output workflow run lead_enrichment --input '{"companyDomain": "acme.com"}' # Using a file path output workflow run lead_enrichment --input ./test_input.json ``` ### output workflow start Start a workflow asynchronously — returns the workflow ID immediately without waiting: ```bash theme={null} output workflow start [scenario] ``` **workflowName** `string` *required* Name of the workflow to start **scenario** `string` Scenario name — resolved from the workflow's scenarios/ directory | Flag | Default | Description | | - | - | - | | `--input, -i` | — | JSON input or file path (overrides scenario) | | `--catalog, -c` | `OUTPUT_CATALOG_ID` | Catalog name (the deprecated `--task-queue, -q` aliases still work) | | `--search-attributes, -a` | — | Temporal [search attributes](/operations/deployment#search-attributes) as a JSON object or file path | | `--monitor, -m` | false | Attach after starting and stream status updates until the workflow ends | Add `--monitor` to start a workflow and watch it in one command, instead of copying the workflow ID into a separate [`workflow monitor`](#output-workflow-monitor) call: ```bash theme={null} output workflow start lead_enrichment --input ./test_input.json --monitor ``` ```text theme={null} Starting workflow: lead_enrichment... Workflow started successfully Workflow ID: wf-12345 Monitoring wf-12345 (run 2fe0b36b-...)... (Ctrl+C to detach) ● Fetch Company running… ✓ Fetch Company 1.2s ● Score Lead running… ✓ Score Lead 3.4s ✓ workflow completed · 4.8s Use "workflow result wf-12345" to get the workflow result ``` Monitoring attaches to the exact run that was just started, so a rapid re-start can't leave you watching a different execution. Everything else matches `workflow monitor` — Ctrl+C detaches without stopping the workflow (exit `130`), and the command exits `1` if the workflow fails. The stream reports progress, not the return value, so the command closes by naming the follow-up: [`workflow result`](#output-workflow-result) after a run that completed, [`workflow debug`](#output-workflow-debug) after one that failed. If monitoring itself drops — the API restarts, the connection resets — a transient failure is retried a few times before the command gives up. Once it does, the workflow it started keeps running, so the command says so and exits `3` rather than `1`. Retry logic keyed on a failed workflow therefore can't re-submit a workflow that is already in flight: ```text theme={null} Warning: Poll failed (1/5), retrying: fetch failed Warning: Poll failed (2/5), retrying: fetch failed Warning: Poll failed (3/5), retrying: fetch failed Warning: Poll failed (4/5), retrying: fetch failed Error: Workflow wf-12345 started, but monitoring stopped: Connection refused to http://localhost:3001. Is the API server running? The workflow is still running. Use "workflow status wf-12345" to check on it. ``` `--monitor` cannot be combined with `--json`. Under `--json` the CLI suppresses progress output and prints a single JSON object when the command finishes, which would silently swallow every streamed update and leave the command looking hung until the workflow ended. Use `workflow run --json` to wait for a result as JSON, or `workflow monitor --format json` to stream newline-delimited JSON. These flags tune the stream and require `--monitor`: | Flag | Default | Description | | - | - | - | | `--interval` | 2500 | Poll interval in milliseconds | | `--include-payloads` | false | Include decoded step input/output payloads | | `--color` | true | Colorize status output (`--no-color` to disable) | ### output workflow status Check whether a workflow is still running, completed, or failed: ```bash theme={null} output workflow status ``` **workflowId** `string` *required* The workflow execution ID | Flag | Default | Description | | - | - | - | | `--format, -f` | text | Output format: json, text | ### output workflow monitor Attach to a workflow run and stream status updates until it ends — a step starts, completes, or fails is printed as it happens, so you don't have to re-run `workflow status` in a loop to watch a long-running workflow: ```bash theme={null} output workflow monitor ``` **workflowId** `string` *required* The workflow execution ID | Flag | Default | Description | | - | - | - | | `--run-id, -r` | latest run | Monitor a specific run (continue-as-new chains are followed regardless of this flag) | | `--format, -f` | text | Output format: json, text | | `--include-payloads` | false | Include decoded step input/output payloads | | `--interval` | 2500 | Poll interval in milliseconds. Also bounds the resumed long-poll's server-side wait, so an idle workflow's update cadence is roughly twice this value, not a longer separate server default. | | `--color` | true | Colorize status output (`--no-color` to disable) | Exits `0` when the workflow completes, `1` when it fails, is canceled, terminated, or times out, and `130` if you detach with Ctrl+C — detaching never stops the workflow itself. `monitor` also exits `1` after 5 consecutive transient poll failures (network errors, 5xx/408/429 responses), printing a warning before each retry — this is API/network trouble, not a workflow outcome, but shares the same exit code. ```bash theme={null} output workflow monitor wf-12345 output workflow monitor wf-12345 --run-id 2fe0b36b-... output workflow monitor wf-12345 --format json ``` To start a workflow and attach in a single step, use [`workflow start --monitor`](#output-workflow-start) instead of copying the ID between two commands. > [!NOTE] > > `--format json` here is **not** the same thing as the native `--json` flag used by `workflow run`, `workflow status`, and other commands migrated in OUT-419 (see the [changelog](/changelog)). Native `--json` suppresses all in-progress log output and prints a single JSON object once the command finishes. `monitor` has no single final result to print — it's a long-running command that emits a stream of discrete events (a step starting or finishing, a continue-as-new notice, a final summary) while the workflow is still running. `--format json` prints each event as its own line of newline-delimited JSON as it happens, so the output can be piped into `jq` or read incrementally by another process — often another automated or agent process rather than a person, which is the primary reason this command keeps its own JSON mode instead of adopting `--json`. ### output workflow result Get the output of a completed workflow: ```bash theme={null} output workflow result ``` **workflowId** `string` *required* The workflow execution ID #### Workflow result JSON format Use `--json` with `output workflow run` or `output workflow result` to print the full structured workflow result: ```json theme={null} { "v": "2", "workflowId": "lead_enrichment-a1b2c3d4-5678-90ab-cdef-1234567890ab", "runId": "b5c6d7e8-9012-3456-7890-abcdef123456", "status": "completed", "input": { "companyDomain": "acme.com" }, "output": { "company": "Acme Corp", "summary": "Enterprise software company focused on..." }, "trace": { "local": "/path/to/trace.json", "remote": "s3://trace-bucket/path/to/trace.json" }, "error": null } ``` | Field | Description | | - | - | | `v` | Workflow result payload version. Current responses use `"2"`. | | `workflowId` | Workflow execution ID. | | `runId` | Specific Temporal run ID. | | `status` | Current or final execution status. | | `input` | Original workflow input. | | `output` | Value returned by the workflow on success, or `null` on failure. | | `trace` | Trace metadata for the run, or `null` when unavailable. | | `error` | Serialized error object on failure, otherwise `null`. It includes `name` and `message` and may contain `activityType`, `cause`, and other diagnostic properties. | #### JSON error format When a command run with `--json` fails, it writes a JSON error to **stderr** and leaves stdout empty, so a script can read results from stdout and failures from stderr without mixing them. This applies to `run`, `start`, `status`, `result`, `list`, `runs list`, `cost`, `debug`, `input`, `test`, and `dataset list`. ```json theme={null} { "error": { "message": "Workflow not found. Check the workflow ID.", "status": 404 } } ``` | Field | Description | | - | - | | `message` | Human-readable description of the failure. Always present. | | `status` | HTTP status returned by the API. Present only when the API responded. | | `code` | System error code, such as a network error code. Present only when the failure has one. | The exit code tells you what kind of failure it was, and is the same as in text mode: `1` for API and network failures, and `2` for usage errors such as invalid flag combinations on `workflow start`. Without `--json`, errors are printed as plain text, as before. ### output workflow stop Stop a running workflow gracefully: ```bash theme={null} output workflow stop ``` **workflowId** `string` *required* The workflow execution ID ### output workflow terminate Force-stop a workflow immediately. Use this for stuck workflows or cleaning up after branch switches: ```bash theme={null} output workflow terminate output workflow terminate wf-12345 --reason "Cleaning up old workflows" ``` **workflowId** `string` *required* The workflow execution ID | Flag | Default | Description | | - | - | - | | `--reason, -r` | — | Reason for termination | Unlike `stop` (which cancels gracefully), `terminate` kills the workflow immediately. ### output workflow reset Rerun a workflow from after a specific completed step. The current run is terminated and a new run is created that replays up to the given step (reusing its output), then re-executes every step after it. Useful when iterating on a late step without re-paying the cost of earlier LLM or API calls: ```bash theme={null} output workflow reset --step output workflow reset lead_enrichment-a1b2c3d4 --step consolidateCompetitors --reason "Retry with updated prompt" ``` **workflowId** `string` *required* The workflow execution ID | Flag | Default | Description | | - | - | - | | `--step, -s` | — | **Required.** Name of the completed step to reset after. The step itself is not re-executed; every step after it is. | | `--reason, -r` | — | Free-text reason, recorded in Temporal history for auditability | The command prints the original `workflowId` and a new `runId` for the fresh execution. Use `output workflow status ` and `output workflow result ` to track it. > [!TIP] > > Find valid step names with `output workflow debug --format json` — the step name you pass to `--step` is the one shown on completed step entries. ### output workflow debug Show the execution trace for a workflow — what steps ran, what they received and returned, and where failures happened. See [Tracing](/operations/tracing) for details on trace format. ```bash theme={null} output workflow debug output workflow debug wf-12345 --format json ``` **workflowId** `string` *required* The workflow execution ID | Flag | Default | Description | | - | - | - | | `--format, -f` | text | Output format: json, text | > [!TIP] > > Use `--format json` to get the full untruncated trace. The text format truncates long values for readability, but the JSON format preserves everything. ### output workflow cost Calculate the estimated dollar cost of a workflow execution from its trace. Covers LLM token costs and API service costs. See [Cost Estimation](/costs) for details on pricing configuration and the `config/costs.yml` override file. ```bash theme={null} output workflow cost [tracePath] ``` **workflowId** `string` *required* Workflow ID to calculate cost for **tracePath** `string` Path to a local trace JSON file. If omitted, fetches the latest trace for the workflow. | Flag | Default | Description | | - | - | - | | `--format, -f` | text | Output format: json, text | | `--verbose` | false | Show per-call breakdown with token counts and individual step costs | ```bash theme={null} # Cost from latest trace output workflow cost lead_enrichment_QlcADmOM # Cost from a specific trace file output workflow cost lead_enrichment_QlcADmOM logs/runs/lead_enrichment/2026-03-01_trace.json # Detailed per-call breakdown output workflow cost lead_enrichment_QlcADmOM --verbose # Machine-readable output output workflow cost lead_enrichment_QlcADmOM --format json ``` > [!TIP] > > If the report shows "Unknown models", add them to `config/costs.yml` in your project root. See [Cost Estimation — Pricing Configuration](/costs#pricing-configuration) for the format. ## Evaluation Commands These commands run offline evaluations against your workflows using the [`@outputai/core/evals`](/packages/core/evals) module. You define evaluators, write dataset YAML files, and use these commands to execute and manage them. ### output workflow test Run evaluations against a workflow using its datasets: ```bash theme={null} output workflow test ``` **workflowName** `string` *required* Name of the workflow to test | Flag | Default | Description | | - | - | - | | `--cached` | false | Use cached output from dataset files (skip workflow execution). Exclusive with `--save` | | `--save` | false | Run workflow and save output back to dataset files. Exclusive with `--cached` | | `--dataset, -d` | — | Comma-separated list of dataset names to run | | `--format, -f` | text | Output format: text, json | ```bash theme={null} # Run evals using cached output (fast — no workflow execution) output workflow test simple --cached # Run evals with fresh execution and save results back to datasets output workflow test simple --save # Run specific datasets only output workflow test simple --dataset basic_input,edge_case # Get JSON output for CI integration output workflow test simple --cached --format json ``` ### Dataset Commands ### output workflow dataset list List datasets for a workflow: ```bash theme={null} output workflow dataset list ``` **workflowName** `string` *required* Workflow name to list datasets for | Flag | Default | Description | | - | - | - | | `--format, -f` | table | Output format: table, json, text | ```bash theme={null} output workflow dataset list simple output workflow dataset list simple --format json ``` ### output workflow dataset generate Generate a dataset for a workflow from a scenario, inline JSON, a local trace file, or recent runs: ```bash theme={null} output workflow dataset generate [scenario] ``` **workflowName** `string` *required* Name of the workflow **scenario** `string` Scenario name — resolved from the workflow's scenarios/ directory | Flag | Default | Description | | - | - | - | | `--input, -i` | — | Workflow input as JSON string or file path (overrides scenario) | | `--name, -n` | — | Dataset name (defaults to scenario name or trace filename) | | `--trace, -t` | — | Path to a local trace file to extract dataset from. Exclusive with `--download` | | `--download, -d` | false | Generate datasets from recent workflow runs, fetched via the Output API. Exclusive with `--trace` | | `--limit, -l` | 5 | Maximum number of recent runs to fetch | | `--catalog, -c` | `OUTPUT_CATALOG_ID` | Catalog to scope runs to (used with `--download`) | ```bash theme={null} # Generate from a scenario output workflow dataset generate simple basic_input # Generate with inline JSON input output workflow dataset generate simple --input '{"values": [1, 2, 3]}' --name custom_case # Generate from a local trace file output workflow dataset generate simple --trace logs/runs/simple/trace.json --name from_trace # Generate datasets from the most recent runs (traces fetched via the API) output workflow dataset generate simple --download --limit 10 ``` ## Credentials Commands These commands manage the encrypted credentials files read by [`@outputai/core/credentials`](/packages/core/credentials). Every command targets the global credentials by default and accepts these flags to pick another scope: | Flag | Default | Description | | - | - | - | | `--environment, -e` | - | Target environment (e.g. `production`, `development`) | | `--workflow, -w` | - | Target a specific workflow directory | > [!NOTE] > > `--environment` and `--workflow` are mutually exclusive. ### output credentials init Create an encryption key and an encrypted credentials file: ```bash theme={null} output credentials init ``` | Flag | Default | Description | | - | - | - | | `--force, -f` | false | Overwrite existing credentials | ### output credentials edit Decrypt the credentials file, open it in `$EDITOR`, and re-encrypt it on save: ```bash theme={null} output credentials edit ``` | Flag | Default | Description | | - | - | - | | `--force, -f` | false | When the current key can't decrypt the file, start from an empty file and re-encrypt with the current key (discards existing values) | ### output credentials set Set a credential value by dot-notation path: ```bash theme={null} output credentials set ``` **path** `string` *required* Dot-notation path to the credential (e.g. `anthropic.api_key`) **value** `string` *required* Value to set | Flag | Default | Description | | - | - | - | | `--yes, -y` | false | Skip the confirmation prompt when overwriting a value of a different shape | | `--force, -f` | false | Re-encrypt with the current key even if it can't decrypt the existing file (discards existing values) | ### output credentials get Print a single credential value by dot-notation path: ```bash theme={null} output credentials get ``` **path** `string` *required* Dot-notation path to the credential (e.g. `anthropic.api_key`) ### output credentials show Print all decrypted credentials, for debugging: ```bash theme={null} output credentials show ``` ```bash theme={null} # Initialize production credentials output credentials init --environment production # Initialize workflow-specific credentials output credentials init --workflow payment_processing # Edit production credentials output credentials edit -e production # Set a value without opening an editor output credentials set anthropic.api_key sk-ant-xxxxx # Get a workflow-specific credential output credentials get stripe.secret_key --workflow payment_processing ``` ## Environment Configuration By default, the CLI loads environment variables from `.env` in the current directory. To use a different env file: ```bash theme={null} # Use production environment OUTPUT_CLI_ENV=.env.prod output workflow list # Use staging environment OUTPUT_CLI_ENV=.env.staging output workflow run lead_enrichment acme ``` | Variable | Default | Description | | - | - | - | | `OUTPUT_CLI_ENV` | `.env` | Path to custom env file (relative or absolute) | | `OUTPUT_API_URL` | `http://localhost:3001` | Output API server URL used by workflow commands | | `OUTPUT_API_AUTH_TOKEN` | — | API auth token for requests (required in production) | | `OUTPUT_DEBUG` | — | Set to `true` to enable CLI debug mode | | `DOCKER_SERVICE_NAME` | `output-sdk` | Docker Compose project name for `output dev` — isolates containers, networks, and volumes | | `OUTPUT_API_HOST_PORT` | `3001` | Host port for the Output API server | | `OUTPUT_TEMPORAL_UI_HOST_PORT` | `8080` | Host port for the Temporal UI | | `OUTPUT_TEMPORAL_HOST_PORT` | `7233` | Host port for the Temporal gRPC endpoint. Override to run multiple dev stacks side-by-side | | `OUTPUT_API_VERSION` | Installed CLI version | API Docker image tag. Set to `dev` for local builds | | `OUTPUT_WORKFLOWS_DIR` | `.` | Workflows subdirectory relative to project root. Set to `test_workflows` for monorepo dev | | `ANTHROPIC_API_KEY` | — | Anthropic API key for AI-assisted workflow generation (`workflow plan`, `workflow generate`) | # @outputai/core Source: https://docs.output.ai/packages/core Workflow orchestration, worker runtime, and the building blocks for every Output app The `@outputai/core` package is the foundation of every Output app. It gives you `workflow`, `step`, and `evaluator` — the three building blocks for defining what your app does. It also provides the worker runtime that connects to Temporal and runs your workflows in production. ## What's in the Package ```typescript theme={null} import { // Building blocks workflow, step, evaluator, // Evaluation result types EvaluationBooleanResult, EvaluationNumberResult, EvaluationStringResult, EvaluationFeedback, // HTTP from workflows sendHttpRequest, sendPostRequestAndAwaitWebhook, // Logging from workflows and steps Logger, // Error types FatalError, TransparentFatalError, ValidationError, hasErrorType, // Zod (re-exported for convenience) z } from '@outputai/core'; ``` | Export | Description | | - | - | | `workflow` | Define orchestration logic that coordinates steps | | `step` | Define units of work that handle I/O (API calls, database queries, etc.) | | `evaluator` | Define steps that score content and return evaluation results | | `EvaluationBooleanResult` | Pass/fail evaluation result | | `EvaluationNumberResult` | Numeric score evaluation result | | `EvaluationStringResult` | Category/label evaluation result | | `EvaluationFeedback` | Structured feedback (issue + suggestion + priority) | | `sendHttpRequest` | Send HTTP requests from within workflows | | `sendPostRequestAndAwaitWebhook` | Send a POST and pause until a webhook responds | | `Logger` | Structured logger that works from workflows, steps, and hook callbacks | | `FatalError` | Non-retryable error — stops immediately | | `TransparentFatalError` | Non-retryable wrapper that surfaces its original error | | `ValidationError` | Schema validation failure — stops immediately | | `hasErrorType` | Match an error class across a Temporal failure cause chain | | `z` | Zod schema library for input/output validation | For full details on `workflow`, `step`, and `evaluator`, see [Workflows](/workflows), [Steps](/steps), and [Evaluators](/evaluators). ## Worker Runtime When you run `output dev`, the CLI starts Docker Compose which launches a worker container. The worker: 1. **Scans your project** for workflow files (`workflow.js`), step files (`steps.js`), evaluator files (`evaluators.js`), and shared components in `shared/steps/` and `shared/evaluators/` 2. **Creates a catalog** of all discovered workflows and their activities with metadata (name, description, schemas) 3. **Connects to Temporal** at the configured address 4. **Publishes the catalog** so the API can resolve workflow names for this version of your code 5. **Starts processing** workflow executions Publishing the catalog gates step 5. If the worker cannot publish a catalog matching its own source code, it retries and then exits rather than serving requests against an outdated catalog. ### Shutdown `SIGTERM`, `SIGINT`, and `SIGUSR2` start a graceful shutdown: the worker stops polling, lets in-flight activities run for `TEMPORAL_SHUTDOWN_GRACE_TIME` before asking them to cancel, gives up draining after `TEMPORAL_SHUTDOWN_FORCE_TIME`, closes its Temporal connection, then awaits pending hook callbacks for up to `OUTPUT_HOOK_FLUSH_TIMEOUT_MS`. A second signal forces an immediate exit. Those three values are a single budget, and it has to fit inside the window your platform allows between `SIGTERM` and `SIGKILL`. The worst case is `TEMPORAL_SHUTDOWN_FORCE_TIME` plus `OUTPUT_HOOK_FLUSH_TIMEOUT_MS`, since the drain runs to its bound and then the flush runs to its own. The defaults total 25 seconds against the 30 seconds Render and Kubernetes allow by default, leaving 5 seconds of margin. Raise the platform window before raising any of them - on Render that is `maxShutdownDelaySeconds`, on Kubernetes `terminationGracePeriodSeconds` - or the platform terminates the process mid-flush and the hook data is lost. Uncaught exceptions and unhandled rejections take the same path, so in-flight work still drains. That drain is capped at 60 seconds: a worker still shutting down when the cap expires force quits. The cap is fixed, independent of `TEMPORAL_SHUTDOWN_FORCE_TIME`, and applies only to this path - a shutdown started by a signal is bounded by `TEMPORAL_SHUTDOWN_FORCE_TIME`, a second signal, or your platform's kill window. | Exit code | Meaning | | - | - | | `0` | A signal requested the shutdown. This includes in-flight work that did not finish before `TEMPORAL_SHUTDOWN_FORCE_TIME`, which is abandoned and logged as a warning. A service failing to stop never changes the code | | `1` | Startup failed, the Temporal connection was lost, an uncaught error ended the process, or a second signal forced an immediate exit | See [Worker Shutdown](/operations/worker-shutdown) for sizing these values and reading the shutdown logs. ### File Discovery The worker scans your `src/` directory for these file patterns: | Location | Purpose | | - | - | | `workflows/*/workflow.js` | Workflow definition | | `workflows/*/steps.js` | Step implementations | | `workflows/*/evaluators.js` | Evaluator implementations | | `shared/steps/*.js` | Shared steps (importable by any workflow) | | `shared/evaluators/*.js` | Shared evaluators (importable by any workflow) | Each discovered component is logged during startup: ``` [Scanner] [info] Workflow loaded {"name":"lead_enrichment","path":"src/workflows/lead_enrichment/workflow.js"} [Scanner] [info] Component loaded {"type":"step","name":"lookupCompany","path":"src/workflows/lead_enrichment/steps.js"} ``` ### Architecture Output is built on [Temporal.io](https://temporal.io) for durable execution. Your abstractions map to Temporal primitives: | Output.ai | Temporal | | - | - | | `workflow()` | Workflow | | `step()` | Activity | | `evaluator()` | Activity | When you call a step from a workflow, Output executes it as a durable activity with automatic retries, schema validation, and tracing. If the worker crashes mid-execution, Temporal replays the workflow and skips already-completed steps. ## Hooks Register handlers in hook files that the worker loads at startup (list paths under `outputai.hookFiles` in `package.json`). Import from `@outputai/core/hooks`. The framework wraps each handler in a try/catch: failures are logged and do not stop the worker or workflow runs. **Keep handlers fast.** Every handler is tracked while it runs, and a [shutdown](#shutdown) awaits all the pending ones together under a single `OUTPUT_HOOK_FLUSH_TIMEOUT_MS` budget. There is no opt-out, so one handler awaiting a slow network call spends the allowance every other pending handler needs, and they can all be dropped together. Write to stdout or an in-process buffer and let your log pipeline or a sidecar ship the data. If a handler genuinely has to await remote I/O, batch it and raise `OUTPUT_HOOK_FLUSH_TIMEOUT_MS` along with your platform's shutdown window. Every hook payload includes an **`eventId`** — a UUID v4 stamped per emit — and an **`eventDate`**, the millisecond epoch timestamp for when the event was emitted. Use `eventId` as a stable per-emit idempotency key for downstream dedup (webhook retry handling, ClickHouse `ReplacingMergeTree`, audit logs, etc.). Distinct emits — including `http:request` and `cost:http:request` for the same fetch — receive distinct `eventId`s. | Function | When it runs | Payload | | - | - | - | | `onError` | Activity, workflow, or runtime error | Object always includes `eventId`, `eventDate`, `source`, and `error`. Other fields depend on `source` — see below and [Error Hooks](/operations/error-hooks) | | `onWorkflowStart` | A user workflow execution starts | `eventId`, `eventDate`, `workflowDetails` | | `onWorkflowEnd` | A user workflow execution completes successfully | `eventId`, `eventDate`, `workflowDetails` | | `onWorkflowError` | A user workflow execution fails | `eventId`, `eventDate`, `workflowDetails`, `error` | | `onActivityStart` | An Output activity starts, including internal activities | `eventId`, `eventDate`, `activityInfo`, `workflowDetails`, `outputActivityKind` | | `onActivityEnd` | An Output activity completes successfully, including internal activities | `eventId`, `eventDate`, `activityInfo`, `workflowDetails`, `outputActivityKind` | | `onActivityError` | An Output activity fails, including internal activities | `eventId`, `eventDate`, `activityInfo`, `workflowDetails`, `outputActivityKind`, `error` | | `on(eventName, handler)` | SDK and custom events | An envelope containing `eventId`, `eventDate`, and your original value under `payload`; activity context fields are included when available | **Context objects on hook payloads** * `activityInfo` is Temporal's Activity execution info object. See Temporal's [`activity.Info`](https://typescript.temporal.io/api/interfaces/activity.Info) reference for all fields. * `workflowDetails` is Output's serializable subset of Temporal's [`workflow.WorkflowInfo`](https://typescript.temporal.io/api/interfaces/workflow.WorkflowInfo). It includes `workflowId`, `runId`, `workflowType`, `parent`, `root`, `firstExecutionRunId`, `continuedFromExecutionRunId`, `startTime`, `runStartTime`, `attempt`, and `searchAttributes` (omitted when the run has none). * `outputActivityKind` is Output metadata for activity hooks and custom events emitted from activities. Possible values are `step`, `evaluator`, and `internal_step`. **SDK and custom event envelopes** Events received with `on(eventName, handler)` keep framework context separate from event-specific data: ```typescript theme={null} { eventId: string; eventDate: number; activityInfo?: Info; workflowDetails?: WorkflowDetails; outputActivityKind?: string; payload: unknown; } ``` Use `emit(eventName, payload)` from a step or evaluator to publish a custom event. The payload is optional and can be any JavaScript value. If you call `emit()` outside a step or evaluator (and therefore outside an activity context), the event still includes `eventId`, `eventDate`, and `payload`, but it does not include `activityInfo`, `workflowDetails`, or `outputActivityKind`. ```typescript theme={null} import { emit, on } from '@outputai/core/hooks'; emit('company:enriched', { companyId: 'company-123', domain: 'example.com' }); on<{ companyId: string; domain: string }>('company:enriched', ({ eventId, workflowDetails, payload }) => { if (!workflowDetails || !payload) { return; } console.log('Company enriched', { eventId, workflowId: workflowDetails.workflowId, companyId: payload.companyId, domain: payload.domain }); }); ``` SDK events use the same envelope. For example, `http:request` stores its request fields under `payload`, while `eventId` and activity context remain at the top level. ```typescript theme={null} type WorkflowDetails = { workflowId: string; runId: string; workflowType: string; parent?: { workflowId: string; runId: string; namespace: string }; root?: { workflowId: string; runId: string }; firstExecutionRunId: string; continuedFromExecutionRunId?: string; startTime: number; runStartTime: number; attempt: number; searchAttributes?: Record; }; ``` **`onError` payload by `source`** * **`activity`** — `eventId`, `eventDate`, `source`, `activityInfo`, `workflowDetails`, `outputActivityKind`, `error` * **`workflow`** — `eventId`, `eventDate`, `source`, `workflowDetails`, `error` * **`runtime`** — `eventId`, `eventDate`, `source`, `error` Activity, runtime, and workflow error hooks all receive `Error` instances. Workflow errors are still serialized to cross Temporal's sandbox boundary, then rehydrated before hooks run — so `name`, `message`, an optional recursive `cause`, and other enumerable diagnostic properties survive. The value is always a bare `Error`, not the original subclass (`instanceof FatalError` is false even when `error.name === 'FatalError'`). Use `error.name`, or `hasErrorType(error, FatalError)` from `@outputai/core`, to distinguish failure kinds. The internal `$catalog` workflow is excluded from lifecycle and error hooks. Activity hooks include internal activities, identified by `outputActivityKind: 'internal_step'`. ## HTTP from Workflows ### sendHttpRequest Send HTTP requests directly from workflow code (not from steps): ```typescript workflow.ts theme={null} import { workflow, sendHttpRequest } from '@outputai/core'; import { EnrichmentInput, EnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', inputSchema: EnrichmentInput, outputSchema: EnrichmentOutput, fn: async (input) => { const response = await sendHttpRequest({ url: 'https://api.example.com/companies', method: 'GET', headers: { Authorization: 'Bearer $ENRICHMENT_API_TOKEN' }, responseOptions: { includeBody: true } }); return { company: response.body.name, summary: response.body.description }; } }); ``` For POST or PUT requests, include a `payload`: ```typescript theme={null} const response = await sendHttpRequest({ url: 'https://api.example.com/companies', method: 'POST', payload: { domain: 'acme.com' }, responseOptions: { includeBody: true } }); ``` > [!WARNING] > > `sendHttpRequest` is only callable from within workflows. Steps and evaluators can make HTTP requests directly using fetch or any HTTP client. By default, `sendHttpRequest` returns only response metadata: `url`, `status`, `statusText`, and `ok`. Use `responseOptions.includeHeaders` to include response headers and `responseOptions.includeBody` to include the body. Included response headers are redacted automatically. Response bodies are parsed by content type: JSON is parsed (empty or invalid JSON is returned as raw text), text-like types (`text/*`, XML, form-urlencoded, and JavaScript) are returned as text, and anything else is returned as a base64 string. Use `$ENV_VAR_NAME` placeholders for secret header values: ```typescript theme={null} await sendHttpRequest({ url: 'https://api.example.com/companies', method: 'GET', headers: { Authorization: 'Bearer $ENRICHMENT_API_TOKEN' } }); ``` The worker resolves `$ENRICHMENT_API_TOKEN` from `process.env.ENRICHMENT_API_TOKEN` inside the activity. Workflow history and trace files store the placeholder, not the token value. > [!WARNING] > > `sendHttpRequest` is not primarily designed for secure or sensitive HTTP exchanges. Misconfigured requests can leak keys, tokens, cookies, signed URLs, payload data, or response bodies into Temporal history and trace files. Use `$ENV_VAR_NAME` placeholders for request header secrets, avoid secrets in URLs and payloads, and only set `responseOptions.includeBody: true` when the response body is safe to persist. ### sendPostRequestAndAwaitWebhook Send a POST request and pause the workflow until a webhook response comes back. See [External Integration](/workflows/external-integration#pattern-1-workflow-initiates-the-request) for the full guide. ```typescript theme={null} import { sendPostRequestAndAwaitWebhook } from '@outputai/core'; const response = await sendPostRequestAndAwaitWebhook({ url: 'https://your-app.com/callback', payload: { data: 'value' }, headers: { Authorization: 'Bearer $CALLBACK_API_TOKEN' } }); ``` The workflow pauses after sending the request and waits for a response at `/workflow/:id/feedback`. Once the external system sends feedback via the API, the workflow resumes with the received payload. > [!WARNING] > > `sendPostRequestAndAwaitWebhook` is not primarily designed for secure or sensitive HTTP exchanges. Its request arguments are stored in Temporal history and can appear in trace files, so secrets can leak if they are placed directly in URLs, payloads, or literal headers. Use `$ENV_VAR_NAME` placeholders for request header secrets and avoid secrets in URLs and payloads. ## Credentials The `@outputai/core/credentials` subpath reads encrypted secrets from `credentials.yml.enc` files, scoped globally, per environment, or per workflow. Use it in steps and other worker-side code: ```typescript theme={null} import { credentials } from '@outputai/core/credentials'; const apiKey = credentials.require('anthropic.api_key'); ``` The worker also resolves `credential:` values in environment variables at startup. See [Credentials](/packages/core/credentials) for setup, key management, and deployment. ## HTTP Clients The `@outputai/core/http` subpath provides traced HTTP clients for steps and other worker-side code. Requests are recorded in the trace and emit `http:request` events: ```typescript theme={null} import { createKyClient } from '@outputai/core/http'; const client = createKyClient({ prefix: 'https://api.example.com' }); ``` It also exports `outputFetch`, a traced drop-in for `fetch`, and `addRequestCost` to attach a cost to a request. See [HTTP](/packages/core/http) for the full API. ## LLM The `@outputai/core/llm` subpath calls LLMs from steps and evaluators using [prompt files](/prompts). Generations are recorded in the trace with their usage and cost, and emit `llm:generation:metering` events: ```typescript theme={null} import { generateText } from '@outputai/core/llm'; const { result } = await generateText({ prompt: 'summarize@v1', variables: { content } }); ``` It also exports `generateTextWithStreaming`, `streamText`, `generateImage`, `Agent`, and the `judge*` LLM judges for evaluators. Install the `@ai-sdk/*` provider packages your prompts use. See [LLM](/packages/core/llm) for the full API. ## Evals The `@outputai/core/evals` subpath runs offline evaluations: an eval workflow feeds saved dataset cases through evaluators built with `verify()` and reports pass/partial/fail verdicts per case: ```typescript theme={null} import { verify, Verdict } from '@outputai/core/evals'; export const evaluateSum = verify( { name: 'evaluate_sum' }, ({ input, output }) => Verdict.equals(output.result, input.values.reduce((a, b) => a + b, 0)) ); ``` It also exports `evalWorkflow`, `VERDICT`, `CRITICALITY`, `DatasetSchema`, and `EvalOutputSchema`. Run eval workflows with `output workflow test`. See [Evals](/packages/core/evals) for the full guide. ## Temporal Access in the Worker The `@outputai/core/temporal` subpath gives worker-side code direct access to the Temporal layer, sharing the worker's live connection — no extra configuration, TLS, or credentials handling. Temporal Activities can additionally access the workflow execution that invoked them. ### getCurrentWorkflowHandle Get a handle pinned to the exact workflow run that invoked the current step. The primary use case is signaling incremental results — e.g. LLM token batches — back to a workflow that buffers them for a client-facing update handler: ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { getCurrentWorkflowHandle } from '@outputai/core/temporal'; import { generateTextWithStreaming } from '@outputai/core/llm'; export const draftWithProgress = step({ name: 'draftWithProgress', inputSchema: DraftInput, outputSchema: DraftOutput, fn: async (input) => { const handle = getCurrentWorkflowHandle(); const result = await generateTextWithStreaming({ prompt: 'draft@v1', variables: input, async onChunk({ chunk }) { if (chunk.type === 'text-delta') { await handle.signal('progressToken', chunk.text); } } }); return { text: result.result }; } }); ``` `generateTextWithStreaming` reports chunks as they arrive but returns a complete result like `generateText`. Stream failures reject the step, allowing Temporal to record the failed activity attempt and apply its retry policy. The handle is resolved from the activity context and pinned to the exact `workflowId` + `runId`, so a stale activity from a retried or superseded run can never signal a newer run reusing the same workflow id. If the invoking run has already completed, operations on the handle reject and the activity fails — surfacing the problem instead of signaling into the void. ### createTemporalClient For operations on other workflows, `createTemporalClient()` creates a full Temporal [`Client`](https://typescript.temporal.io/api/classes/client.Client) that shares the running worker's connection and namespace: ```typescript theme={null} import { createTemporalClient } from '@outputai/core/temporal'; const client = createTemporalClient(); const handle = client.workflow.getHandle(someWorkflowId); await handle.signal('resume', payload); ``` Each call creates a lightweight client while reusing the worker's live connection. Do not close `client.connection`; the worker owns its lifecycle. > [!WARNING] > > `createTemporalClient()` is available after the worker establishes its Temporal connection; code that runs while hook files load runs before that point. `getCurrentWorkflowHandle()` additionally requires a Temporal Activity context. Elsewhere (e.g. unit tests), they throw a non-retryable `FatalError`; mock the helpers in those tests. Never import `@outputai/core/temporal` from `workflow.ts` — workflows run in Temporal's isolated sandbox and cannot hold connections, so the import would fail the workflow bundle. > [!WARNING] > > Prefer normal dataflow (step return values) whenever the workflow only needs the final result. Signal-per-chunk streaming adds one history event per signal; batch chunks aggressively, and for high-frequency token streams consider an out-of-band channel (e.g. Redis pub/sub) with only the final result returned through Temporal. ## File Structure Each workflow lives in its own directory: ```text theme={null} src/workflows/ └── lead_enrichment/ ├── workflow.ts # Workflow definition ├── steps.ts # Step implementations ├── evaluators.ts # Evaluators (optional) ├── types.ts # Zod schemas ├── prompts/ # LLM prompt templates │ └── generate_summary@v1.prompt └── scenarios/ # Test scenarios └── test_input.json ``` ## Environment Variables The worker reads these environment variables: ### Connection and catalog | Variable | Default | Description | | - | - | - | | `OUTPUT_CATALOG_ID` | — | **Required.** Name of the local catalog (use your email) | | `TEMPORAL_ADDRESS` | `localhost:7233` | Temporal backend address | | `TEMPORAL_NAMESPACE` | `default` | Temporal namespace | | `TEMPORAL_API_KEY` | — | API key for remote Temporal (blank for local) | ### Worker concurrency and polling These map to Temporal worker slots, pollers, and tuners. See [Worker Tuning](/operations/worker-tuning) for details and examples. | Variable | Default | Description | | - | - | - | | `TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_EXECUTIONS` | `40` | Max Activity Task executions at once. | | `TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS` | Temporal's (`40`) | Max Workflow Task executions at once. | | `TEMPORAL_MAX_CACHED_WORKFLOWS` | Temporal's (from heap) | Max number of Workflow Executions in the sticky workflow cache. Unset, Temporal sizes it from the isolate's heap limit. | | `TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_POLLS` | `5` | Max concurrent pollers for Activity Task Queues. | | `TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_POLLS` | `5` | Max concurrent pollers for Workflow Task Queues. | | `TEMPORAL_WORKFLOW_THREAD_POOL_SIZE` | Temporal's (`1`) | Threads running workflow sandboxes. Each is a separate V8 isolate. | | `TEMPORAL_WORKER_TUNER` | — | JSON-encoded Temporal Worker tuner configuration. | ### Activity heartbeating The worker sends [Activity Heartbeats](https://docs.temporal.io/develop/typescript/failure-detection#activity-heartbeats) to the Temporal Service so it knows the activity is still making progress. If no heartbeat is received within the activity’s **Heartbeat Timeout** (set per activity in workflow options, e.g. `heartbeatTimeout` in `proxyActivities`), the server considers the activity timed out and may schedule another [Activity Task Execution](https://docs.temporal.io/tasks#activity-task-execution) per the retry policy. That makes heartbeats important during deploys: when a worker restarts, the server detects missing heartbeats and retries on another worker instead of waiting for the full Start-To-Close Timeout. Set each activity’s Heartbeat Timeout longer than `OUTPUT_ACTIVITY_HEARTBEAT_INTERVAL_MS` so the server does not time out before the next heartbeat. | Variable | Default | Description | | - | - | - | | `OUTPUT_ACTIVITY_HEARTBEAT_INTERVAL_MS` | `120000` (2 min) | How often the worker sends a heartbeat while an activity is running. Must be less than the activity’s Heartbeat Timeout. | | `OUTPUT_ACTIVITY_HEARTBEAT_ENABLED` | `true` | Whether to send heartbeats. Set to `false` only if you do not use long-running activities or Heartbeat Timeouts. | ### Tracing | Variable | Default | Description | | - | - | - | | `OUTPUT_TRACE_LOCAL_ON` | — | Enable local trace files — see [Tracing](/operations/tracing) | | `OUTPUT_TRACE_REMOTE_ON` | — | Enable S3 trace upload (requires Redis + AWS) | | `OUTPUT_TRACE_HOST_PATH` | — | Host path for Docker trace file mounting | | `OUTPUT_TRACE_REMOTE_S3_BUCKET` | — | S3 bucket for remote traces | | `OUTPUT_REDIS_URL` | — | Redis address (required for remote tracing) | | `OUTPUT_REDIS_TRACE_TTL` | `604800` (7 days) | TTL in seconds for Redis keys holding workflow trace data before S3 upload | | `OUTPUT_AWS_REGION` | — | AWS region for S3 bucket | | `OUTPUT_AWS_ACCESS_KEY_ID` | — | AWS access key | | `OUTPUT_AWS_SECRET_ACCESS_KEY` | — | AWS secret key | ### Monitoring | Variable | Default | Description | | - | - | - | | `OUTPUT_WORKER_TELEMETRY_INTERVAL_MS` | `0` | Interval between worker telemetry log messages. `0` means off. | | `TEMPORAL_SHUTDOWN_GRACE_TIME` | `15s` | Time to let in-flight work drain before activities are asked to cancel. Accepts milliseconds or duration strings like `15s`. | | `TEMPORAL_SHUTDOWN_FORCE_TIME` | `20s` | Time before the worker gives up draining and terminates. Accepts milliseconds or duration strings like `15s`. | | `OUTPUT_HOOK_FLUSH_TIMEOUT_MS` | `5000` (5s) | Time to await pending hook callbacks after the drain, before exiting without them. Spent after `TEMPORAL_SHUTDOWN_FORCE_TIME`, so both count against your platform's shutdown window. | ## Logging `@outputai/core` exports a `Logger` object that you can call from workflows, steps, and hook callbacks. Use the same shape as the internal worker logger: a string message plus an optional metadata object. Under the hood, Output routes all logs into the worker's Winston logger. Workflow logs cross the Temporal sandbox through workflow sinks, while step logs use an activity-scoped bridge. Hooks that fire outside an activity, such as workflow hooks and runtime errors, log straight to the worker, while activity hooks and `on()` handlers run inside the activity and use the activity bridge. All paths end up in the same worker log hooks, so the output format, namespaces, and log level filtering stay consistent with the rest of the runtime. ```typescript workflow.ts theme={null} import { workflow, Logger, z } from '@outputai/core'; export default workflow({ name: 'lead_enrichment', outputSchema: z.object({ summary: z.string() }), fn: async () => { Logger.info('Starting enrichment', { source: 'crm' }); // ... Logger.debug('Generated summary', { tokenCount: 842 }); return { summary: 'Acme Corp is a B2B SaaS company...' }; } }); ``` ```typescript steps.ts theme={null} import { step, Logger, z } from '@outputai/core'; export const lookupCompany = step({ name: 'lookup_company', inputSchema: z.object({ domain: z.string() }), outputSchema: z.object({ name: z.string() }), fn: async ({ domain }) => { Logger.info('Looking up company', { domain }); const response = await fetch(`https://api.example.com/companies/${domain}`); Logger.http('Company lookup response', { status: response.status }); return response.json(); } }); ``` ### Log levels Output exposes Winston's default npm log levels: `error`, `warn`, `info`, `http`, `verbose`, `debug`, and `silly`. See Winston's [logging levels](https://github.com/winstonjs/winston#logging-levels) documentation for the priority order. Lower-priority logs are filtered according to the configured worker log level. Use `OUTPUT_LOG_LEVEL` to control what the worker emits: ```bash theme={null} OUTPUT_LOG_LEVEL=debug ``` When unset, development defaults to `debug` and production defaults to `info`. Use `OUTPUT_TEMPORAL_LOG_LEVEL` for Temporal SDK / Core runtime logs. It takes Temporal levels (`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`), not Winston levels, in any letter case. Any other value fails worker startup. Default: `INFO`. ### Metadata The second logger argument is metadata. It should be a plain object with fields you want attached to the log record: ```typescript theme={null} Logger.warn('Retrying provider request', { provider: 'anthropic', attempt: 2, requestId: 'lead-enrichment-123' }); ``` Output automatically adds execution fields such as `workflowId`, `workflowType`, `runId`, `activityId`, and `activityType` when it writes the log. Some metadata field names are reserved because Winston, Output log hooks, or log formatting use them internally. Output drops these fields from logger metadata before building the final log message: * `activityId` * `activityType` * `environment` * `label` * `level` * `message` * `metadata` * `runId` * `service` * `splat` * `stack` * `timestamp` * `workflowId` * `workflowType` If you need to include a value with one of those meanings, use a domain-specific name instead, such as `providerMessage`, `errorStack`, or `sourceTimestamp`. ### Namespace Logs from within workflows have the "Workflow" namespace, while those from activity context have "Activity". Logs from hooks that run outside an activity (`onWorkflowStart`, `onWorkflowEnd`, `onWorkflowError`, and `onError` for workflow or runtime errors) have the "Worker" namespace. Activity hooks and `on()` handlers keep "Activity" and include the activity fields. Namespace is a discrete field in the JSON output in production, and a prefix for the string message in development. The namespace can be customized by setting it in the metadata: ```js theme={null} Logger.warn('My awesome message', { namespace: 'Custom' }); ``` Use `Logger.createLogger()` when several logs should share the same namespace: ```js theme={null} const log = Logger.createLogger('LLM'); log.info('Generating completion', { model: 'claude-sonnet-4' }); log.warn('Provider request retrying', { attempt: 2 }); ``` Metadata on an individual log call can still override the logger's default namespace: ```js theme={null} const log = Logger.createLogger('LLM'); log.info('Using fallback provider', { namespace: 'LLM Fallback' }); ``` ### Worker output The worker uses Winston for structured logging. **Development** (colorized, human-readable): ``` [info] Worker: Loading workflows... { callerDir: "/app/src" } [info] Scanner: Workflow loaded { name: "lead_enrichment", path: "..." } ``` **Production** (`NODE_ENV=production`, JSON): ```json theme={null} {"level":"info","message":"Loading workflows...","namespace":"Worker","service":"output-worker","environment":"production","timestamp":"..."} ``` The same logger calls are formatted as human-readable logs in development and JSON logs in production. ## API Reference For complete TypeScript API documentation, see the [Core Module API Reference](https://output-ai-reference-code-docs.onrender.com/modules/core_src.html). # Credentials Source: https://docs.output.ai/packages/core/credentials Manage encrypted secrets across environments and workflows with scoped access and secure key resolution AI apps need a lot of API keys, database passwords, and third-party tokens. Sharing `.env` files is risky, and coding agents shouldn't see your secrets. The credentials system keeps these secrets encrypted at rest in your repository as YAML files that you commit alongside your code — no external vault subscription needed. At runtime, a single encryption key decrypts everything. Each workflow can have its own scoped credentials that override shared defaults, giving you both team-wide consistency and per-workflow flexibility. You manage credentials through the [CLI](/packages/cli#credentials-commands) and read them in your steps with a simple dot-notation API. ## Setting Up Credentials Initialize credentials for your project: ```bash theme={null} output credentials init ``` This generates two files: * `config/credentials.key` — your 256-bit encryption key (never commit this) * `config/credentials.yml.enc` — the encrypted YAML file (safe to commit) Add your secrets by opening the encrypted file in your editor: ```bash theme={null} output credentials edit ``` The CLI decrypts the file, opens it in `$EDITOR`, and re-encrypts when you save. Fill in your secrets: ```yaml theme={null} # config/credentials.yml.enc (decrypted view) anthropic: api_key: sk-ant-xxxxx openai: api_key: sk-xxxxx stripe: secret_key: sk_live_xxxxx ``` Then read them in any step: ```typescript theme={null} // src/workflows/billing/steps.ts import { step, z } from '@outputai/core'; import { credentials } from '@outputai/core/credentials'; export const chargeCustomer = step({ name: 'chargeCustomer', inputSchema: z.object({ customerId: z.string(), amount: z.number() }), outputSchema: z.object({ chargeId: z.string() }), fn: async (input) => { const stripeKey = credentials.require('stripe.secret_key'); // use stripeKey to call the Stripe API... } }); ``` `credentials.require()` throws a `MissingCredentialError` if the path doesn't exist. Use `credentials.get(path, defaultValue)` when you want a safe fallback instead: ```typescript theme={null} const region = credentials.get('aws.region', 'us-east-1'); ``` ## Wiring LLM Keys to Environment Variables LLM SDKs like the Anthropic and OpenAI clients read their API keys from environment variables. Rather than duplicating these keys in both your `.env` file and your encrypted credentials, you can wire credentials directly into environment variables using the `credential:` prefix. In your `.env` file, set the variable to `credential:` instead of the actual key: ```bash theme={null} # .env ANTHROPIC_API_KEY=credential:anthropic.api_key OPENAI_API_KEY=credential:openai.api_key ``` When the worker starts, every env var set to `credential:` is replaced with the value at that path in the global credentials for the current environment: `config/credentials/.yml.enc` when it exists, otherwise `config/credentials.yml.enc`. Workflow-scoped credentials are not used for env vars. By the time your first workflow runs, `ANTHROPIC_API_KEY` contains the real key — no code changes needed. The worker logs confirmation on startup: ``` [info] Credentials: Resolved credential env vars { vars: [ "ANTHROPIC_API_KEY", "OPENAI_API_KEY" ] } ``` Real environment variable values are never overwritten. If `ANTHROPIC_API_KEY` is already set in the shell or injected by your CI/CD pipeline, the credential reference is ignored. This gives you a safe override path for production deployments without touching files. ## Scoping Credentials to Environments You likely need different API keys for development and production. The credentials system supports environment-specific files that sit alongside the global defaults: ```bash theme={null} # Initialize production credentials output credentials init --environment production # Initialize development credentials output credentials init --environment development ``` This creates a `config/credentials/` directory with per-environment files: ```text theme={null} config/ ├── credentials.yml.enc # Global (shared defaults) ├── credentials.key # Global key └── credentials/ ├── production.yml.enc # Production overrides ├── production.key # Production key ├── development.yml.enc # Development overrides └── development.key # Development key ``` At runtime, the system checks `NODE_ENV` and loads the matching environment file. Only `"production"` and `"development"` are recognized — other values fall back to the global file. Edit environment-specific credentials the same way: ```bash theme={null} output credentials edit --environment production ``` ## Scoping Credentials to Workflows Sometimes a single workflow needs its own secrets — a dedicated API key with different permissions, or a third-party token that only one workflow uses. You can scope credentials to a specific workflow: ```bash theme={null} output credentials init --workflow payment_processing ``` This creates credentials files inside the workflow directory: ```text theme={null} src/workflows/payment_processing/ ├── workflow.ts ├── steps.ts ├── credentials.yml.enc # Workflow-specific secrets └── credentials.key # Workflow-specific key ``` When a step runs inside this workflow, its credentials are **deep-merged** over the global ones. Workflow values win at the same path; global values fill in the rest. **Global credentials:** ```yaml theme={null} anthropic: api_key: sk-ant-global aws: region: us-east-1 secret: aws-global-secret ``` **Workflow credentials** (`payment_processing`): ```yaml theme={null} anthropic: api_key: sk-ant-workflow-specific stripe: secret_key: sk_live_workflow ``` **What `credentials.get()` sees inside the workflow:** ```yaml theme={null} anthropic: api_key: sk-ant-workflow-specific # Overridden by workflow aws: region: us-east-1 # From global secret: aws-global-secret # From global stripe: secret_key: sk_live_workflow # Added by workflow ``` > [!NOTE] > > `--environment` and `--workflow` are mutually exclusive flags. Environment scoping applies at the global level; workflow scoping applies per-workflow. ## Deploying to Production In local development, the `.key` files on disk handle decryption. In production, CI/CD, and Docker — where you don't have key files — set the decryption key as an environment variable. The system resolves keys with a fallback chain: | Scope | Environment Variable | Key File | | - | - | - | | Global | `OUTPUT_CREDENTIALS_KEY` | `config/credentials.key` | | Environment | `OUTPUT_CREDENTIALS_KEY_PRODUCTION` | `config/credentials/production.key` | | Workflow | `OUTPUT_CREDENTIALS_KEY_PAYMENT_PROCESSING` | `src/workflows/payment_processing/credentials.key` | The resolution order is: environment variable first, then key file. Workflow keys fall back to the global key if neither a workflow-specific env var nor a key file is found. ### Docker The encrypted credentials file must be present in the image — the key alone isn't enough. Make sure your Dockerfile includes: ```dockerfile theme={null} COPY config/ ./config/ ``` The `config/` directory is not cleaned up after the build because the encrypted file is read at runtime, not build time. Pass the decryption key as an environment variable in your Docker Compose or container config: ```yaml theme={null} # docker-compose.yml services: worker: image: your-worker-image environment: - OUTPUT_CREDENTIALS_KEY=${OUTPUT_CREDENTIALS_KEY} - NODE_ENV=production ``` ### CI/CD Store the key in your CI provider's secrets and expose it as an environment variable: ```yaml theme={null} # GitHub Actions example jobs: deploy: runs-on: ubuntu-latest env: OUTPUT_CREDENTIALS_KEY: ${{ secrets.OUTPUT_CREDENTIALS_KEY }} OUTPUT_CREDENTIALS_KEY_PRODUCTION: ${{ secrets.OUTPUT_CREDENTIALS_KEY_PRODUCTION }} steps: - run: output workflow run my_workflow ``` ## Key Management ### Never commit key files Add this to your `.gitignore`: ```gitignore theme={null} # Credential encryption keys *.key ``` The encrypted `.yml.enc` files are safe to commit — they can't be decrypted without the key. ### Sharing keys with your team Key files are created with `0o600` permissions (owner read/write only). Share keys with teammates through a secure channel — a password manager, encrypted messaging, or your organization's secret sharing tool. Each developer needs the key file at the expected path, or the matching environment variable set. ### Rotating keys To rotate a key: 1. Decrypt your current credentials: `output credentials show > /tmp/creds.yml` 2. Re-initialize with `--force` to generate a new key: `output credentials init --force` 3. Edit and paste your secrets back: `output credentials edit` 4. Distribute the new key to your team and update environment variables in production 5. Securely delete the temporary file: `rm /tmp/creds.yml` ### Verifying credentials Use the CLI to check that credentials are correctly set up: ```bash theme={null} # Show all decrypted credentials output credentials show # Get a specific value output credentials get anthropic.api_key # Check a workflow's credentials output credentials get stripe.secret_key --workflow payment_processing ``` ## Custom Providers The default provider reads encrypted YAML files from disk. You can replace it with a custom provider for alternative backends (e.g., AWS Secrets Manager, HashiCorp Vault) using `setProvider()`: ```typescript theme={null} import { setProvider } from '@outputai/core/credentials'; import type { CredentialsProvider } from '@outputai/core/credentials'; const vaultProvider: CredentialsProvider = { loadGlobal: ({ environment }) => { // Return credentials as a plain object return { anthropic: { api_key: fetchFromVault('anthropic-key') } }; }, loadForWorkflow: ({ workflowName, workflowDir, environment }) => { // Return workflow-specific credentials, or null to use global only return null; } }; setProvider(vaultProvider); ``` Call `setProvider()` in a hook file listed under `outputai.hookFiles`. Hook files load before the worker resolves `credential:` env vars, so those resolve through your provider too. | Method | Arguments | Returns | | - | - | - | | `loadGlobal(context)` | `{ environment: string \| undefined }` | `Record` | | `loadForWorkflow(context)` | `{ workflowName: string, workflowDir: string \| undefined, environment?: string }` | `Record \| null` | Returning `null` from `loadForWorkflow` means the workflow has no overrides, so global credentials are used as-is. ## Security Credentials are encrypted with **AES-256-GCM** using the `@noble/ciphers` library. Each encryption uses a fresh random nonce, so the same plaintext produces different ciphertext every time. * Key files are created with file mode `0o600` (owner read/write only). * During `output credentials edit`, the temporary plaintext file is overwritten with null bytes before it is deleted. ## API Reference ```typescript theme={null} import { credentials, setProvider, MissingCredentialError, MissingKeyError, InvalidCredentialsKeyError, MalformedCredentialsKeyError } from '@outputai/core/credentials'; import type { CredentialsGlobalContext, CredentialsProvider, CredentialsWorkflowContext } from '@outputai/core/credentials'; ``` ### credentials | Method | Returns | Throws | | - | - | - | | `credentials.get(path, defaultValue?)` | The value at `path`, or `defaultValue` (default `undefined`) when missing | Never for a missing path | | `credentials.require(path)` | The value at `path` | `MissingCredentialError` when the value is missing or `null` | `path` is a dot-notation path into the decrypted YAML, e.g. `'anthropic.api_key'`. Inside a step, the workflow's credentials are merged over the global ones. Credentials are decrypted once per scope and cached for the life of the process. ### Errors All four errors extend `FatalError`, so a step that throws one fails without being retried. | Error | Thrown when | | - | - | | `MissingCredentialError` | `credentials.require()` finds no value at the path | | `MissingKeyError` | No decryption key is found in the env var or key file | | `InvalidCredentialsKeyError` | The key can't decrypt the file: it doesn't match, or the file is corrupted | | `MalformedCredentialsKeyError` | The key isn't exactly 64 hex characters | For complete TypeScript API documentation, see the [Credentials Module API Reference](https://output-ai-reference-code-docs.onrender.com/modules/core_src_credentials.html). # Evals Source: https://docs.output.ai/packages/core/evals Workflow evaluation using datasets, typed evaluators, and deterministic or LLM-based assertions The `@outputai/core/evals` module lets you test workflow quality across datasets - without modifying your workflow code. You define evaluators with `verify()`, write datasets in YAML, and run them with the CLI. Each dataset case feeds a saved workflow input/output pair through your evaluators, and the framework reports pass/partial/fail verdicts per case. This is the complement to [evaluator steps](/evaluators/evaluator-step) that run inside workflows. Those evaluators power generate-evaluate-retry loops in production. Evaluation workflows answer a different question: "across a set of known inputs, does my workflow still produce acceptable output?" For the full guide, see [Evaluation Workflow](/evaluators/workflow-evaluators). ## What's in the Module ```typescript theme={null} import { // Eval workflow evalWorkflow, // Evaluator creation verify, // Deterministic + LLM assertion helpers Verdict, // Verdict and criticality values VERDICT, CRITICALITY, // Dataset and eval output schemas DatasetSchema, EvalOutputSchema } from '@outputai/core/evals'; // LLM judge functions import { judgeVerdict, judgeScore, judgeBoolean, judgeLabel } from '@outputai/core/llm'; ``` | Export | Description | | - | - | | `evalWorkflow` | Define an eval workflow that tests datasets against evaluators | | `verify` | Create a typed evaluator with Zod schemas for input/output | | `Verdict` | Deterministic assertion helpers (equals, gte, contains, etc.) and LLM result wrappers | | `VERDICT`, `CRITICALITY` | The `pass`/`partial`/`fail` and `required`/`informational` values | | `DatasetSchema`, `EvalOutputSchema` | Zod schemas for dataset cases and eval workflow output | | `judgeVerdict` | LLM judge that returns pass/partial/fail (from `@outputai/core/llm`) | | `judgeScore` | LLM judge that returns a numeric score (from `@outputai/core/llm`) | | `judgeBoolean` | LLM judge that returns true/false (from `@outputai/core/llm`) | | `judgeLabel` | LLM judge that returns a string label (from `@outputai/core/llm`) | The judges live in `@outputai/core/llm` because eval workflows run in Temporal's workflow sandbox, which cannot load the AI SDK. Import them only in evaluator files. ## Creating Evaluators with verify() `verify()` creates a typed evaluator that receives the workflow's input, output, and optional ground truth from the dataset. It wraps `evaluator()` from `@outputai/core` so it integrates with both the eval workflow and the Temporal worker. ```typescript theme={null} import { verify } from '@outputai/core/evals'; import { z } from '@outputai/core'; const myEvaluator = verify( { name: 'my_evaluator', input: z.object({ /* workflow input schema */ }), output: z.object({ /* workflow output schema */ }) }, ({ input, output, context }) => { // input: typed workflow input // output: typed workflow output // context.ground_truth: Record from dataset YAML return Verdict.equals(output.result, context.ground_truth.expected); } ); ``` The `input` and `output` schemas are optional — they default to `z.any()` if omitted. The check function receives a `CheckContext`: | Field | Type | Description | | - | - | - | | `input` | `TInput` | The workflow input from the dataset | | `output` | `TOutput` | The workflow output (cached or freshly executed) | | `context.ground_truth` | `Record` | Ground truth values from the dataset YAML | ### Basic Example A deterministic evaluator that checks a sum calculation: ```typescript tests/evals/evaluators.ts theme={null} import { verify, Verdict } from '@outputai/core/evals'; import { z } from '@outputai/core'; export const evaluateSum = verify( { name: 'evaluate_sum', input: z.object({ values: z.array(z.number()) }), output: z.object({ result: z.number() }) }, ({ input, output }) => Verdict.equals(output.result, input.values.reduce((a, b) => a + b, 0)) ); ``` ### Ground Truth Example Evaluators can read per-evaluator ground truth from the dataset. The framework merges global ground truth with evaluator-specific overrides: ```typescript tests/evals/evaluators.ts theme={null} import { verify, Verdict } from '@outputai/core/evals'; import { z } from '@outputai/core'; export const lengthOfOutput = verify( { name: 'length_of_output', input: z.object({ topic: z.string() }), output: z.object({ title: z.string(), blog_post: z.string() }) }, ({ output, context }) => Verdict.gte(output.blog_post.length, Number(context.ground_truth.min_length ?? 100)) ); ``` The ground truth comes from the dataset YAML: ```yaml tests/datasets/stripe_blog.yml theme={null} name: stripe_blog input: topic: "Stripe the payment processor" ground_truth: notes: "Known good case" evals: length_of_output: min_length: 100 evaluate_content: required_content: "https://stripe.com" ``` Global ground truth fields (like `notes`) are available to all evaluators. Fields under `evals.` are merged in for that specific evaluator, overriding globals with the same key. ## Verdict Helpers The `Verdict` object provides deterministic assertion helpers and LLM result wrappers. All deterministic helpers return results with confidence `1.0`. ### Deterministic Assertions | Helper | Arguments | Passes when | | - | - | - | | `Verdict.equals(actual, expected)` | any, any | `actual === expected` | | `Verdict.closeTo(actual, expected, tolerance)` | number, number, number | `\|actual - expected\| <= tolerance` | | `Verdict.gt(actual, threshold)` | number, number | `actual > threshold` | | `Verdict.gte(actual, threshold)` | number, number | `actual >= threshold` | | `Verdict.lt(actual, threshold)` | number, number | `actual < threshold` | | `Verdict.lte(actual, threshold)` | number, number | `actual <= threshold` | | `Verdict.inRange(actual, min, max)` | number, number, number | `min <= actual <= max` | | `Verdict.contains(haystack, needle)` | string, string | `haystack.includes(needle)` | | `Verdict.matches(value, pattern)` | string, RegExp | `pattern.test(value)` | | `Verdict.includesAll(actual, expected)` | array, array | `actual` contains every element of `expected` | | `Verdict.includesAny(actual, expected)` | array, array | `actual` contains at least one element of `expected` | | `Verdict.isTrue(value)` | boolean | `value === true` | | `Verdict.isFalse(value)` | boolean | `value === false` | ### Manual Verdicts | Helper | Arguments | Result | | - | - | - | | `Verdict.pass(reasoning?)` | string? | Pass with confidence 1.0 | | `Verdict.partial(confidence, reasoning?, feedback?)` | number, string?, FeedbackArg\[]? | Partial with custom confidence | | `Verdict.fail(reasoning, feedback?)` | string, FeedbackArg\[]? | Fail with confidence 0.0 | ### LLM Result Wrappers These wrap LLM judge output into evaluation results with confidence `0.9`: | Helper | Arguments | Result type | | - | - | - | | `Verdict.fromJudge({ verdict, reasoning })` | object | Verdict (pass/partial/fail) | | `Verdict.score(value, reasoning?)` | number, string? | Number | | `Verdict.label(value, reasoning?)` | string, string? | String | ## LLM Judge Functions For subjective evaluation — "is this blog post on-topic?", "rate the quality 0-100" — use the judge functions. They load a `.prompt` file, call the LLM, and return a typed evaluation result. ```typescript tests/evals/evaluators.ts theme={null} import { verify } from '@outputai/core/evals'; import { judgeVerdict, judgeScore, judgeLabel } from '@outputai/core/llm'; import { z } from '@outputai/core'; const blogInput = z.object({ topic: z.string() }); const blogOutput = z.object({ title: z.string(), blog_post: z.string() }); export const evaluateTopic = verify( { name: 'evaluate_topic', input: blogInput, output: blogOutput }, async ({ input, output, context }) => judgeVerdict({ prompt: 'judge_topic@v1', variables: { blog_title: output.title, blog_post: output.blog_post, required_topic: String(context.ground_truth.required_topic ?? input.topic) } }) ); export const evaluateQuality = verify( { name: 'evaluate_quality', input: blogInput, output: blogOutput }, async ({ input, output }) => judgeScore({ prompt: 'judge_quality@v1', variables: { blog_title: output.title, blog_post: output.blog_post, topic: input.topic } }) ); export const evaluateTone = verify( { name: 'evaluate_tone', input: blogInput, output: blogOutput }, async ({ output }) => judgeLabel({ prompt: 'judge_tone@v1', variables: { blog_title: output.title, blog_post: output.blog_post } }) ); ``` | Function | Expected schema | Returns | | - | - | - | | `judgeVerdict` | `{ verdict: 'pass'\|'partial'\|'fail', reasoning: string }` | `EvaluationVerdictResult` | | `judgeScore` | `{ score: number, reasoning: string }` | `EvaluationNumberResult` | | `judgeBoolean` | `{ result: boolean, reasoning: string }` | `EvaluationBooleanResult` | | `judgeLabel` | `{ label: string, reasoning: string }` | `EvaluationStringResult` | All judge functions accept a `JudgeArgs` object: | Field | Type | Description | | - | - | - | | `prompt` | `string` | Prompt filename (e.g., `'judge_topic@v1'`) | | `variables` | `Record` | Template variables | | `schema` | `ZodType` | Custom output schema (overrides the default) | Judge `.prompt` files live in the same `tests/evals/` directory as your evaluators: ```yaml tests/evals/judge_topic@v1.prompt theme={null} --- provider: anthropic model: claude-haiku-4-5-20251001 temperature: 0 maxOutputTokens: 1000 --- You are an evaluation judge. Assess whether a blog post is faithfully about the required topic. Return a JSON object with: - verdict: "pass" if the blog clearly focuses on the topic, "partial" if it mentions but lacks depth, "fail" if not about the topic - reasoning: brief explanation of your judgment Required topic: {{ required_topic }} Blog title: {{ blog_title }} Blog post: {{ blog_post }} Judge whether this blog post is faithfully about the required topic. ``` ## Creating an Eval Workflow `evalWorkflow()` ties your evaluators together into a workflow that the CLI can run against datasets: ```typescript tests/evals/workflow.ts theme={null} import { evalWorkflow } from '@outputai/core/evals'; import { evaluateSum } from './evaluators.js'; export default evalWorkflow({ name: 'simple_eval', evals: [ { evaluator: evaluateSum, criticality: 'required', interpret: { type: 'boolean' } } ] }); ``` Each entry in the `evals` array defines: | Field | Type | Default | Description | | - | - | - | - | | `evaluator` | Function | — | An evaluator created with `verify()` | | `criticality` | `'required' \| 'informational'` | `'required'` | Whether failure should fail the case | | `interpret` | `InterpretConfig` | — | How to convert the evaluator result to a verdict | A more complete example mixing deterministic and LLM evaluators: ```typescript tests/evals/workflow.ts theme={null} import { evalWorkflow } from '@outputai/core/evals'; import { lengthOfOutput, evaluateTopic, evaluateQuality, evaluateContent, evaluateTone } from './evaluators.js'; export default evalWorkflow({ name: 'blog_generator_eval', evals: [ { evaluator: lengthOfOutput, criticality: 'required', interpret: { type: 'boolean' } }, { evaluator: evaluateTopic, criticality: 'required', interpret: { type: 'verdict' } }, { evaluator: evaluateQuality, criticality: 'required', interpret: { type: 'number', pass: 0.7, partial: 0.4 } }, { evaluator: evaluateContent, criticality: 'informational', interpret: { type: 'boolean' } }, { evaluator: evaluateTone, criticality: 'informational', interpret: { type: 'string', pass: ['professional', 'informative'], partial: ['casual'] } } ] }); ``` ### Criticality * **`required`** (default): If this evaluator fails, the entire case fails. * **`informational`**: Failure is reported but doesn't affect the case verdict. Use for metrics you want to track without gating on. ### Interpret Types The `interpret` config tells the framework how to convert the raw evaluator result into a pass/partial/fail verdict: | Type | Config | Pass when | Partial when | Fail when | | - | - | - | - | - | | `boolean` | `{ type: 'boolean' }` | `value === true` | — | `value === false` | | `verdict` | `{ type: 'verdict' }` | `value === 'pass'` | `value === 'partial'` | `value === 'fail'` | | `number` | `{ type: 'number', pass: 0.7, partial: 0.4 }` | `value >= pass` | `value >= partial` | otherwise | | `string` | `{ type: 'string', pass: ['a', 'b'], partial: ['c'] }` | `value in pass` | `value in partial` | otherwise | The `partial` threshold is optional for both `number` and `string` types — omit it to have only pass and fail. ### Case Verdict Aggregation Each dataset case runs all evaluators. The case-level verdict is determined by: 1. If any **required** evaluator fails → case **fails** 2. Else if any **required** evaluator is partial → case is **partial** 3. Otherwise → case **passes** Informational evaluators never affect the case verdict. ## Datasets Datasets are YAML files that live in `tests/datasets/` within your workflow directory. Each file contains one or more test cases — the top-level key is the case name. ```yaml tests/datasets/core_cases.yml theme={null} basic_sum: input: values: - 1 - 2 - 3 - 4 - 5 ground_truth: notes: "Simple sum test" edge_case_empty: input: values: [] ground_truth: notes: "Empty input should return 0" ``` The key is the case name — no separate `name:` field inside. Every case must have an `input` field; the framework throws if one is missing. | Field | Required | Description | | - | - | - | | `input` | Yes | The workflow input | | `ground_truth` | No | Expected values for evaluators to check against | | `last_output` | No | Cached workflow output (used with `--cached` flag) | | `last_eval` | No | Cached evaluation results from the last run | Organise files however makes sense for your project — by topic, test suite version, or importance level: ``` tests/datasets/ ├── core_cases.yml # happy path coverage ├── edge_cases.yml # edge cases and error paths └── v2_regression.yml # cases added for v2 ``` The `--dataset` flag filters by case name regardless of which file it lives in: ```bash theme={null} output workflow test my_workflow --dataset basic_sum,edge_case_empty ``` You can write datasets by hand, or generate them from workflow executions using the CLI — see [Dataset Commands](/packages/cli#dataset-commands). ### Ground Truth Structure Ground truth supports global values and per-evaluator overrides: ```yaml theme={null} ground_truth: # Global — available to all evaluators notes: "Known good case" min_length: 100 # Per-evaluator overrides evals: evaluate_topic: required_topic: "Stripe the payment processor" evaluate_content: required_content: "https://stripe.com" ``` When an evaluator runs, the framework merges global ground truth with its evaluator-specific values. Per-evaluator values override globals with the same key. ## Directory Structure Eval files live alongside your workflow in a `tests/` directory: ```text theme={null} src/workflows/ └── blog_generator/ ├── workflow.ts ├── steps.ts ├── evaluators.ts # Inline evaluators (for production loops) ├── types.ts ├── prompts/ │ └── generate_blog@v1.prompt └── tests/ ├── evals/ │ ├── workflow.ts # evalWorkflow() definition │ ├── evaluators.ts # Workflow evaluators (verify + Verdict) │ ├── judge_topic@v1.prompt │ └── judge_quality@v1.prompt └── datasets/ ├── core_cases.yml └── edge_cases.yml ``` The eval workflow file (`tests/evals/workflow.ts`) is discovered automatically by the worker alongside your regular workflow. ## Running Evaluations Use the CLI to run evaluations and manage datasets. See [CLI Evaluation Commands](/packages/cli#evaluation-commands) for the full reference. ```bash theme={null} # Run evals using cached output (no workflow re-execution) output workflow test blog_generator --cached # Run evals with fresh workflow execution and save results output workflow test blog_generator --save # Run specific datasets only output workflow test blog_generator --dataset happy_path,edge_case # List available datasets output workflow dataset list blog_generator # Generate a dataset from a scenario output workflow dataset generate blog_generator my_scenario --name new_case ``` ## API Reference For complete TypeScript API documentation, see the [Evals Module API Reference](https://output-ai-reference-code-docs.onrender.com/modules/core_src_evals.html). # HTTP Source: https://docs.output.ai/packages/core/http Make traceable HTTP requests from your steps The `@outputai/core/http` module provides Fetch and Ky clients instrumented for [tracing](/operations/tracing). Every request — URL, method, status code, and timing — is recorded as a child node in the trace tree. It exposes two entry points: * `outputFetch` — a Fetch-compatible function backed by [Undici](https://undici.nodejs.org/). * `createKyClient` — creates a [Ky](https://github.com/sindresorhus/ky) client that uses `outputFetch`. Ky and Undici are peer dependencies of `@outputai/core`. Current npm and pnpm versions install compatible peers automatically, so the normal package installation is enough: ```bash theme={null} pnpm add @outputai/core ``` Install Ky or Undici explicitly only when you need to pin their versions or resolve a peer-version conflict. ## Using Instrumented Fetch Use `outputFetch` when you want the standard Fetch API: ```typescript theme={null} import { outputFetch } from '@outputai/core/http'; const response = await outputFetch( 'https://api.example.com/users', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify( { name: 'Ada' } ) } ); if ( !response.ok ) { throw new Error( `Request failed with status ${response.status}` ); } const user = await response.json(); ``` Like native Fetch, `outputFetch` returns responses for HTTP error statuses. It only throws for failures such as DNS errors, timeouts, and aborts. `outputFetch` accepts URL strings, `URL` objects, and both Node and Undici `Request` objects. Node `Request` and `FormData` inputs are normalized into the Undici realm before the request is sent. Keep `Request` and `FormData` from the same family when using both in one call. ## Creating a Ky Client The typical pattern is to create a client per external service in your [clients directory](/clients), then import it in your steps: ```typescript clients/jina.ts theme={null} import { createKyClient } from '@outputai/core/http'; export const client = createKyClient({ prefix: 'https://r.jina.ai', headers: { 'Authorization': `Bearer ${process.env.JINA_API_KEY}`, 'Accept': 'application/json' }, timeout: 30000 }); ``` `createKyClient` accepts Ky's complete options object and returns a standard Ky instance. All Ky methods, hooks, retries, timeout behavior, and `.extend()` support remain available. By default, the client uses `outputFetch`. Providing Ky's `fetch` option overrides it, so requests made by that client are not automatically traced by Output. > [!WARNING] > > Use the global `FormData` with Ky clients. Ky sends `undici.FormData` bodies as the text `[object FormData]`. You can extend clients to create specialized instances: ```typescript theme={null} const authenticatedClient = client.extend({ headers: { 'X-Custom-Header': 'value' } }); ``` ## HTTP Methods ```typescript theme={null} // GET const response = await client.get('https://acme.com'); const data = await response.json(); // POST const response = await client.post('companies', { json: { url: 'https://acme.com' } }); const result = await response.json(); // PUT await client.put('companies/123', { json: { industry: 'SaaS' } }); // DELETE await client.delete('companies/123'); ``` ## Response Bodies Both APIs follow normal Fetch semantics: callers own the returned response body. Always consume the body with `.json()`, `.text()`, `.arrayBuffer()`, or another body reader when you need the payload. If you only need response metadata from a non-`HEAD` request, such as `response.url`, `response.status`, or headers, cancel the unused body so the underlying connection and native buffers can be released: ```typescript theme={null} const response = await client.get('https://example.com', { redirect: 'follow' }); try { return response.url; } finally { await response.body?.cancel(); } ``` ## Using in Steps Wrap HTTP calls in steps for automatic retry and tracing: ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { jina } from '../../clients/jina.js'; import { ScrapePageInput, ScrapePageOutput } from './types.js'; export const scrapePage = step({ name: 'scrapePage', description: 'Scrape a web page using Jina Reader API', inputSchema: ScrapePageInput, outputSchema: ScrapePageOutput, fn: async (url) => { const response = await jina.get(url); const data = await response.json(); return { title: data.data?.title ?? '', content: data.data?.content ?? '', url: data.data?.url ?? url }; } }); // types.ts // import { z } from '@outputai/core'; // // export const ScrapePageInput = z.string(); // // export const ScrapePageOutput = z.object({ // title: z.string(), // content: z.string(), // url: z.string() // }); ``` ## Tracing All requests made with `@outputai/core/http` are automatically traced — no configuration needed. In your trace files, HTTP calls appear as children of the step that made them: ```json theme={null} { "kind": "http", "name": "request", "input": { "method": "GET", "url": "https://r.jina.ai/https://acme.com" }, "output": { "status": 200, "statusText": "OK" } } ``` See [Tracing](/operations/tracing) for details on the trace format. Each request also gets an `http:request:count` trace attribute, and `addRequestCost` adds an `http:request:cost` one. Their classes, `HTTPRequestCount` and `HTTPRequestCost`, are exported for matching attributes by type: ```typescript theme={null} import { HTTPRequestCost } from '@outputai/core/http'; const isCost = attribute instanceof HTTPRequestCost; ``` ## Request Events Every call made through `outputFetch` or a client returned by `createKyClient` emits an **`http:request`** hook event — independent of whether you attach a cost. Subscribe to it with [`on`](/packages/core#hooks) for logging, alerting, or per-vendor metrics: ```typescript theme={null} import { on } from '@outputai/core/hooks'; import type { HttpRequestEvent } from '@outputai/core/http'; on( 'http:request', async ( { eventId, workflowDetails, payload } ) => { if (!workflowDetails || !payload) { return; } console.log( `[${payload.outcome}] ${payload.method} ${payload.url} ${payload.status ?? '-'} ${payload.durationMs}ms`, { eventId, workflowId: workflowDetails.workflowId } ); } ); ``` The handler receives an event envelope. Request-specific fields are available under `payload`: | Field | Description | | - | - | | `eventId` | UUID v4 stamped per emit. Stable per-emit idempotency key — `http:request` and `cost:http:request` for the same fetch get distinct `eventId`s, so dedup keyed on `eventId` won't collapse the two. | | `eventDate` | Millisecond epoch timestamp for when the event was emitted. | | `activityInfo?` | Temporal [`activity.Info`](https://typescript.temporal.io/api/interfaces/activity.Info) when the request is made in an activity context. | | `workflowDetails?` | Output's serializable subset of Temporal [`workflow.WorkflowInfo`](https://typescript.temporal.io/api/interfaces/workflow.WorkflowInfo), when available. | | `outputActivityKind?` | Output activity kind when available. Possible values are `step`, `evaluator`, and `internal_step`. | | `payload.requestId` | UUID generated per request inside `@outputai/core/http`. Shared between the matching `http:request` and `cost:http:request` events for cross-event correlation. | | `payload.method` | HTTP method (uppercase). | | `payload.url` | Absolute request URL. | | `payload.status` | HTTP status code; `undefined` on network failure. | | `payload.durationMs` | Elapsed time from request issuance to response (or failure), in milliseconds. | | `payload.outcome` | One of `'success'` (2xx-3xx), `'error'` (status >= 400), `'failure'` (DNS / timeout / abort). | The event fires for **every** call — success, non-2xx responses, and network failures alike. The existing [`cost:http:request`](/costs/cost-events#http-request-cost) event is unchanged and continues to fire only when you call `addRequestCost`. ## Attaching Request Cost When you know the dollar cost of an HTTP request (for example from provider billing headers), you can attach it to the HTTP trace event with `addRequestCost`. ```typescript theme={null} import { addRequestCost, createKyClient } from '@outputai/core/http'; const client = createKyClient( { prefix: 'https://api.vendor.com' } ); const response = await client.post( 'search', { json: { query: 'acme' } } ); const inputCost = Number( response.headers.get( 'x-cost-input-usd' ) ?? 0 ); const outputCost = Number( response.headers.get( 'x-cost-output-usd' ) ?? 0 ); addRequestCost( response, inputCost + outputCost ); response.body?.cancel(); ``` `addRequestCost` accepts the total request cost as a number. `addRequestCost` only works with responses returned by `outputFetch` or `createKyClient`. If the response did not come from this package, the function safely no-ops and logs a warning. It also emits a **`cost:http:request`** hook event through the same hooks system as [LLM generation metering](/costs/cost-events#llm-generation-metering). For the payload and examples, see [Cost Events - HTTP](/costs/cost-events#http-request-cost). ## Error Handling `outputFetch` returns non-2xx responses without throwing. Ky clients use Ky's configured error behavior and throw `ky.HTTPError` for non-2xx responses by default and `ky.TimeoutError` for timeouts: ```typescript theme={null} import { createKyClient, ky } from '@outputai/core/http'; const client = createKyClient( { prefix: 'https://api.example.com' } ); try { const response = await client.get( 'users/1' ); return response.json(); } catch (error) { if (error instanceof ky.HTTPError) { if (error.response.status === 404) { return null; } throw error; } if (error instanceof ky.TimeoutError) { throw error; } throw error; } ``` Since steps retry automatically, you generally just need to handle cases where retrying won't help (like a 404). For everything else, let the error propagate and the step's retry policy will handle it. ## Undici Dispatchers Requests use an `EnvHttpProxyAgent` by default, including standard HTTP proxy environment variables. You can provide an Undici dispatcher for one request: ```typescript theme={null} import { outputFetch, undici } from '@outputai/core/http'; const dispatcher = new undici.Agent( { headersTimeout: 60_000, bodyTimeout: 60_000 } ); const response = await outputFetch( 'https://api.example.com', { dispatcher } ); ``` Set `dispatcher: undefined` explicitly to bypass the default dispatcher. ## Ky and Undici Exports The complete Ky and Undici namespaces are re-exported for convenience and to let callers use the same Undici realm as `outputFetch`: ```typescript theme={null} import { ky, undici } from '@outputai/core/http'; const request = new undici.Request( 'https://api.example.com' ); const isHttpError = ( error: unknown ) => error instanceof ky.HTTPError; ``` ## Environment Variables | Variable | Description | | - | - | | `OUTPUT_TRACE_HTTP_VERBOSE` | Set to `true` or `1` to include request/response headers and bodies in trace files (otherwise only method, URL, and status are recorded) | ## API Reference For complete TypeScript API documentation, see the [HTTP Module API Reference](https://output-ai-reference-code-docs.onrender.com/modules/core_src_http.html). # LLM Source: https://docs.output.ai/packages/core/llm Generate and stream text, structured outputs, and images with prompt file management The `@outputai/core/llm` module is how you call LLMs from your steps and evaluators. It wraps the [AI SDK](https://sdk.vercel.ai/docs) and adds [prompt files](/prompts) - version-controlled `.prompt` files that live alongside your code and define the provider, model, temperature, and prompt template in one place. Call arguments are the lists under [Call arguments](#call-arguments). AI SDK helpers and types (`Output`, `tool`, `isStepCount`, `ToolSet`) are on the `aiSdk` namespace: `import { generateText, aiSdk } from '@outputai/core/llm'`. ## Generate Functions `generateText` is the primary function for LLM calls. Use the `output` parameter with `aiSdk.Output.*` helpers to control the response shape. When you need progress as text arrives, prefer `generateTextWithStreaming` in workflow steps: it uses streaming internally but returns a complete result and rejects on provider or transport errors. Use `streamText` when you need direct control over the stream: | Output Shape | How | Use when you need | | - | - | - | | Unstructured text | `generateText({ prompt })` | Summaries, emails, explanations | | Complete text with streaming callbacks | `generateTextWithStreaming({ prompt, onChunk })` | Progress updates with normal promise-based error handling | | Raw text stream | `streamText({ prompt })` | Direct access to `textStream`, `stream`, and stream promises | | Typed object | `generateText({ prompt, output: aiSdk.Output.object({ schema }) })` | Structured data, evaluator judgments | | Array of objects | `generateText({ prompt, output: aiSdk.Output.array({ element }) })` | Lists, multiple items | | One of N choices | `generateText({ prompt, output: aiSdk.Output.choice({ options }) })` | Classification, routing | | Image | `generateImage({ prompt })` | Text-to-image, image-to-image, and image edits | ### Text Output Generate unstructured text from a prompt file: ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { generateText } from '@outputai/core/llm'; import { GenerateSummaryInput, GenerateSummaryOutput } from './types.js'; export const generateSummary = step({ name: 'generateSummary', description: 'Generate a company summary from research data', inputSchema: GenerateSummaryInput, outputSchema: GenerateSummaryOutput, fn: async (input) => { const { result } = await generateText({ prompt: 'generate_summary@v1', variables: { companyName: input.name, industry: input.industry, size: input.size } }); return result; } }); // types.ts // import { z } from '@outputai/core'; // // export const GenerateSummaryInput = z.object({ // name: z.string(), // industry: z.string(), // size: z.number() // }); // // export const GenerateSummaryOutput = z.string(); ``` `result` is a convenience alias for `response.text`. ### Streaming #### Complete result over streaming transport `generateTextWithStreaming` behaves like `generateText`: await it to receive the complete response, including `result`, `text`, `output`, `usage`, `finishReason`, and `cost`. Internally it uses streaming transport and invokes `onChunk` as parts arrive. This is the recommended streaming API for Output workflow steps. Provider, transport, and abort errors reject the returned promise, so the step fails and Temporal can apply its retry policy. ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { generateTextWithStreaming } from '@outputai/core/llm'; import { GenerateContentInput, GenerateContentOutput } from './types.js'; export const generateContent = step({ name: 'generateContent', description: 'Generates content with streaming progress', inputSchema: GenerateContentInput, outputSchema: GenerateContentOutput, fn: async ({ topic }) => { const chunks: string[] = []; const result = await generateTextWithStreaming({ prompt: 'stream_content@v1', variables: { topic }, onChunk({ chunk }) { if (chunk.type === 'text-delta') { chunks.push(chunk.text); } } }); return { content: result.result, chunkCount: chunks.length, avgChunkSize: chunks.length > 0 ? Math.round(result.result.length / chunks.length) : 0 }; } }); ``` `generateTextWithStreaming` also supports structured output. Pass an `aiSdk.Output.*` specification and read the parsed value from `result.output`, just as with `generateText`. #### Direct stream access `streamText` remains available when you need to choose how the stream is consumed. It is not `async`: it returns a stream result synchronously, with `textStream` and `stream` iterables plus promise-based properties such as `text`, `usage`, and `finishReason`. `fullStream` remains available as a deprecated alias for `stream`. AI SDK streaming reports provider and transport failures through `onError`; consuming `textStream` does not reliably throw that original error. In a workflow step, capture the mapped error and throw it after consumption so Temporal records a failed activity instead of an empty successful result: ```typescript theme={null} const captured: { error: unknown } = { error: null }; const result = streamText({ prompt: 'generate@v1', variables: { topic: 'AI safety' }, onError({ error }) { captured.error = error; } }); const chunks: string[] = []; for await (const chunk of result.textStream) { chunks.push(chunk); } if (captured.error) { throw captured.error; } const content = chunks.join(''); ``` Registering `onError` alone is not enough to fail the step. Output treats it as a fire-and-forget observer: exceptions and rejected promises from the callback are ignored to avoid a secondary stream failure. Capture the mapped error and throw it after consumption; awaiting a completion property can produce a generic no-output error instead of the original provider error. ### Object Output Generate a structured object matching a Zod schema. This is what you'll use most in evaluators: ```typescript evaluators.ts theme={null} import { evaluator, EvaluationBooleanResult } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; import { JudgeSummaryInput } from './types.js'; export const judgeSummaryQuality = evaluator({ name: 'judgeSummaryQuality', description: 'Judge whether a company summary is accurate and useful', inputSchema: JudgeSummaryInput, fn: async (input) => { const { output } = await generateText({ prompt: 'judge_summary@v1', variables: { summary: input.summary, companyName: input.companyName }, output: aiSdk.Output.object({ schema: z.object({ reasoning: z.string(), passes: z.boolean(), confidence: z.number() }) }) }); return new EvaluationBooleanResult({ value: output.passes, confidence: output.confidence, reasoning: output.reasoning }); } }); // types.ts // import { z } from '@outputai/core'; // // export const JudgeSummaryInput = z.object({ // summary: z.string(), // companyName: z.string() // }); ``` `output` contains the typed object matching your schema. ### Image Output Generate images from a prompt file with `generateImage`. Image prompt files use plain instructions, not chat role tags like `` or ``. Keep plain text as the first meaningful body content so Output selects [instruction mode](/prompts#prompt-body-modes): ```yaml prompts/nascar_race@v1.prompt theme={null} --- provider: openai model: gpt-image-1 size: 1024x1024 n: 1 providerOptions: openai: quality: high --- Create a cinematic motorsport image. Scene: {{ scene }} ``` Call `generateImage` from a step: ```typescript steps.ts theme={null} import { randomUUID } from 'node:crypto'; import { mkdirSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { step, z } from '@outputai/core'; import { generateImage } from '@outputai/core/llm'; export const generateRaceImage = step({ name: 'generateRaceImage', description: 'Generate a race image from a prompt file', inputSchema: z.object({ scene: z.string() }), outputSchema: z.object({ fileName: z.string() }), fn: async ({ scene }) => { const response = await generateImage({ prompt: 'nascar_race@v1', variables: { scene } }); if (!response.result?.base64) { throw new Error('Image generation did not return base64 image data.'); } mkdirSync('_temp', { recursive: true }); const fileName = `race-${randomUUID()}.png`; writeFileSync(join('_temp', fileName), Buffer.from(response.result.base64, 'base64')); return { fileName }; } }); ``` `result` is a convenience alias for the first generated image (`response.images[0]`). The returned image exposes AI SDK image fields such as `base64` and `mediaType`. For image-to-image or edit flows, pass runtime image inputs with `images` and optionally `mask`. Output forwards these to the AI SDK prompt object: ```typescript theme={null} import { readFileSync } from 'node:fs'; import { generateImage } from '@outputai/core/llm'; const referenceImage = readFileSync('nascar-reference.jpg'); const response = await generateImage({ prompt: 'nascar_race@v1', variables: { scene: 'Use the reference car as the hero car in a night race restart.' }, images: [referenceImage] }); const image = response.result; ``` Supported image inputs follow the AI SDK shape: `Buffer`, `Uint8Array`, `ArrayBuffer`, raw base64 strings, or `{ data, mediaType }` objects. `mask` uses the same input shape and requires `images`. > [!NOTE] > > `generateImage` does not upload generated images, download remote images, or normalize provider-specific values like `size: "auto"`. Download or upload files in your workflow/client code, pass image bytes to `images`, and set concrete provider options in prompt front matter (`size`, `n`, `aspectRatio`, `seed`, `providerOptions`). Common image options can live in prompt front matter: | Option | Description | | - | - | | `n` | Number of images to request when supported by the provider/model | | `maxImagesPerCall` | AI SDK image batching limit | | `size` | Concrete image size such as `1024x1024` | | `aspectRatio` | Aspect ratio such as `1:1` or `16:9` | | `seed` | Seed for deterministic output when supported | | `providerOptions` | Provider-specific options, for example `openai.quality` or `vertex.imageConfig.imageSize` | ### Array Output Generate an array of structured items: ```typescript theme={null} import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; const { output } = await generateText({ prompt: 'extract_contacts@v1', variables: { companyData: JSON.stringify(company) }, output: aiSdk.Output.array({ element: z.object({ name: z.string(), role: z.string(), email: z.string().optional() }) }) }); // output is an array of { name, role, email } objects ``` ### Choice Output Select one value from a set of options: ```typescript theme={null} import { generateText, aiSdk } from '@outputai/core/llm'; const { output } = await generateText({ prompt: 'classify_lead@v1', variables: { activity: leadActivity }, output: aiSdk.Output.choice({ options: ['hot', 'warm', 'cold', 'unknown'] }) }); // output is one of 'hot', 'warm', 'cold', 'unknown' ``` ## Agents The `Agent` class uses an internal AI SDK `ToolLoopAgent` through composition with Output [prompts](/prompts) and the [skills](/prompts/skills) system. It does not inherit from `ToolLoopAgent`. Use it when you need multi-step tool execution, conversation history, or a reusable agent instance with a fixed configuration. For single-shot LLM calls without tools, `generateText` is simpler. ### Construction A prompt filename is loaded and rendered at construction time. A loaded or custom `Prompt` object can be passed directly instead. Variables and `promptDir` apply only to filename prompts; tools are fixed at construction. Skills and `maxSteps` come from the resolved prompt. The agent is ready to call `generate()`, `generateWithStreaming()`, or `stream()` immediately. Each call seeds authored `` blocks from the prompt. `` blocks become `instructions`. Authored `` blocks are dropped; use `generateText` when the prompt is a few-shot or prefilled thread. ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { Agent, aiSdk } from '@outputai/core/llm'; export const reviewContent = step({ name: 'reviewContent', description: 'Review content with structured feedback', inputSchema: ReviewContentInput, outputSchema: ReviewContentOutput, fn: async (input) => { const agent = new Agent({ prompt: 'writing_assistant@v1', variables: { content_type: input.contentType, focus: input.focus, content: input.content }, output: aiSdk.Output.object({ schema: reviewSchema }) }); const { output } = await agent.generate(); return output; } }); ``` **Constructor options:** | Option | Type | Default | Description | | - | - | - | - | | `prompt` | `string \| Prompt` | *(required)* | Prompt filename or a loaded/custom prompt object | | `promptDir` | `string` | - | Override the stack-resolved prompt directory for a filename prompt | | `variables` | `PromptVariables` | - | Template variables rendered for a filename prompt | | `tools` | AI SDK tools | - | Caller tools; merged with prompt YAML tools (`load_skill` last) | | `stopWhen` | function or function\[] | - | Custom stop condition (overrides prompt `maxSteps` when tools exist) | | `output` | `aiSdk.Output` | - | Structured output spec (e.g. `aiSdk.Output.object({ schema })`) | | `messageStore` | `MessageStore` | - | Pluggable store for multi-turn history | ### generate() Run the agent and return when complete: ```typescript theme={null} const result = await agent.generate(); console.log(result.text); // Generated text console.log(result.output); // Structured output (when using aiSdk.Output.object) console.log(result.usage); // Token counts ``` The result has the same shape as `generateText`: `text`, `result` (alias for `text`), `output`, `usage`, `finishReason`, `toolCalls`, etc. Pass additional messages to extend the conversation. You can also pass `abortSignal` and `toolChoice`: ```typescript theme={null} const result = await agent.generate({ messages: [{ role: 'user', content: 'Now focus on the introduction section.' }] }); ``` ### generateWithStreaming() Use `generateWithStreaming()` when you want streaming progress and a complete result. It accepts the same `messages`, `abortSignal`, and `toolChoice` as `generate()`, plus `onChunk`: ```typescript theme={null} const result = await agent.generateWithStreaming({ onChunk({ chunk }) { if (chunk.type === 'text-delta') { process.stdout.write(chunk.text); } } }); ``` Like `generate()`, the method returns the complete response, rejects on stream errors, and automatically appends messages to the configured message store. Prefer it over `stream()` in workflow steps unless you need direct access to the stream result. ### stream() Use `stream()` when you need direct access to the agent's stream result. It accepts the same `messages`, `abortSignal`, and `toolChoice` as `generate()`, plus `onChunk`, `onEnd`, and `onError`: ```typescript theme={null} const captured: { error: unknown } = { error: null }; const stream = await agent.stream({ onError({ error }) { captured.error = error; } }); for await (const chunk of stream.textStream) { process.stdout.write(chunk); } if (captured.error) { throw captured.error; } ``` Like `streamText`, the stream result provides `textStream` and `stream` iterables, plus promise-based properties (`text`, `usage`, `finishReason`) that resolve on completion. In a workflow step, capture and rethrow `onError` as shown so a failed stream cannot become an empty successful activity. ### Structured Output Use `aiSdk.Output.object()` with Agent to get typed responses: ```typescript steps.ts theme={null} import { Agent, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; const reviewSchema = z.object({ issues: z.array(z.string()).describe('List of issues found'), suggestions: z.array(z.string()).describe('Actionable suggestions'), score: z.number().describe('Quality score 0-100'), summary: z.string().describe('Brief overall assessment') }); const agent = new Agent({ prompt: 'writing_assistant@v1', variables: { content_type: 'documentation', focus: 'clarity', content: markdownContent }, output: aiSdk.Output.object({ schema: reviewSchema }) }); const { output } = await agent.generate(); // output: { issues: string[], suggestions: string[], score: number, summary: string } ``` ### Message Store By default, Agent is stateless. Each `generate()` / `stream()` call starts from the prompt seed (authored `` blocks) plus this turn's `messages`. Pass a `messageStore` to keep history across calls. The store holds this turn's caller messages plus the model reply. It does not persist the prompt seed. Reconstructing an agent is the same prompt (and variables) plus a hydrated store. ```typescript theme={null} import { Agent } from '@outputai/core/llm'; import type { MessageStore } from '@outputai/core/llm'; const messages: Parameters[0] = []; const messageStore: MessageStore = { getMessages: () => messages, addMessages: incoming => { messages.push(...incoming); } }; const chatbot = new Agent({ prompt: 'chatbot@v1', messageStore }); const r1 = await chatbot.generate({ messages: [{ role: 'user', content: 'Hello, tell me about Output.' }] }); // r1.text: "Output is an AI framework for..." const r2 = await chatbot.generate({ messages: [{ role: 'user', content: 'How does it handle retries?' }] }); // r2 sees the full history from r1 ``` `MessageStore` is: ```typescript theme={null} interface MessageStore { getMessages(): ModelMessage[] | Promise; addMessages(messages: ModelMessage[]): void | Promise; } ``` `ModelMessage` is an AI SDK type (`aiSdk` / `ai`). There is no built-in store. Implement the interface in memory for a single process, or with your database for durable history. > [!NOTE] > > `generate()`, `generateWithStreaming()`, and `stream()` append messages to the message store only when `finishReason` is not `'error'`. Errored turns are not persisted. ### When to Use Agent vs generateText | | `generateText` | `Agent` | | - | - | - | | **Best for** | Single-shot LLM calls | Multi-step tool loops | | **Tools** | Supported | Supported | | **Skills** | Supported | Supported | | **Conversation history** | Manual | Built-in with `messageStore` | | **Reusable instance** | No (function call) | Yes (construct once, call many) | | **Structured output** | `aiSdk.Output.object()` | `aiSdk.Output.object()` | Start with `generateText`. Move to `Agent` when you need conversation state or a reusable instance with a fixed configuration. ## Response Object `generateText`, `generateTextWithStreaming`, `Agent.generate()`, and `Agent.generateWithStreaming()` return the complete [AI SDK response](https://sdk.vercel.ai/docs/reference/ai-sdk-core/generate-text#returns): | Field | Description | | - | - | | `result` | Convenience alias for `text` | | `text` | The raw generated text | | `output` | The structured output when using `aiSdk.Output.*` helpers | | `usage` | Token counts: `inputTokens`, `outputTokens`, `totalTokens`, plus `inputTokenDetails` and `outputTokenDetails` | | `finishReason` | Why generation stopped (`'stop'`, `'length'`, `'tool-calls'`, etc.) | | `response` | Raw provider response metadata | | `responseMessages` | Accumulated assistant and tool messages from every step | | `finalStep` | Final-step reasoning, request, response, and provider metadata | | `warnings` | Any warnings from the provider | | `toolCalls` | Tool calls made by the model (when using tools) | | `sources` | Merged tool + provider sources (`sourceType: 'url'` or `'document'`). Always an array. | | `cost` | Normalized `LLMGenerationCost` (`providerId`, `modelId`, `promptName`, `requestDetails`, aggregate totals, and priced items). A model or provider missing from the rate table yields an incomplete cost; `null` when usage cannot be normalized | The `cost` property is an `LLMGenerationCost`: ```json theme={null} { "type": "llm:generation:cost", "providerId": "openai", "modelId": "gpt-4o", "promptName": "summarize@v1", "requestDetails": { "ids": ["req_8e1cf3899f254171855c866214eb5620"], "count": 1, "duration": 1240 }, "status": "precise", "pricingFreshness": "cached", "input": 0.001085, "output": 0.000135, "total": 0.00122, "items": [ { "group": "input", "label": "no_cache", "amount": 217, "ppm": 5, "total": 0.001085, "status": "ok" }, { "group": "output", "label": "text", "amount": 9, "ppm": 15, "total": 0.000135, "status": "ok" } ] } ``` Detailed cost items are used when the provider breakdown reconciles with the aggregate token count. Missing cache pricing falls back to the regular input rate and marks the item as `fallback`. Reasoning tokens use the model's reasoning rate when one is listed, otherwise the output rate; either way the item is marked `ok`, since providers bill reasoning as output unless they list a separate rate. Context-tiered token items include `tier: { type: "context", size: number }`. A tier is priced on its own: a rate it does not list follows the same rules and is never taken from the base pricing, so a tier without a reasoning rate prices reasoning at the tier's output rate. Items whose applicable tier cannot be determined precisely are marked `uncertain`, making the aggregate cost `imprecise`. Incomplete multi-step usage is priced at base rates and may understate the cost when an individual request crossed a higher-priced tier. Missing prices produce `null` item costs and an `incomplete` aggregate status. `pricingFreshness` reports how current the rate table was (`live`, `cached`, `stale`, or `snapshot`). **Direct streaming response shape.** `streamText` and `Agent.stream()` return a different result type. Stream iterables (`textStream`, `stream`) provide real-time chunks, while scalar properties (`text`, `usage`, `finishReason`, etc.) are promises that resolve when the stream completes: | Field | Type | Description | | - | - | - | | `textStream` | `AsyncIterable` | Async iterable of text chunks | | `stream` | `AsyncIterable` | Async iterable of all stream events (text deltas, tool calls, etc.) | | `text` | `Promise` | Full text, resolved on completion | | `usage` | `Promise` | Token counts, resolved on completion | | `finishReason` | `Promise` | Why generation stopped, resolved on completion | | `toolCalls` | `Promise` | Tool calls made during streaming, resolved on completion | | `response` | `Promise` | Raw provider response metadata | | `responseMessages` | `Promise` | Accumulated assistant and tool messages from every step | | `finalStep` | `Promise` | Final-step reasoning, request, response, and provider metadata | | `warnings` | `Promise` | Any warnings from the provider | `streamText` / `Agent.stream()` `onEnd` receives the wrapped end payload: `result` (alias for `text`), `cost` (an incomplete `LLMGenerationCost` when model or dimension pricing is missing, `null` when usage cannot be normalized), and merged `sources` (always an array). ## Prompt Files Instead of hardcoding model config and messages in your code, you write `.prompt` files that live in your workflow's `prompts/` folder. See the [Prompts Guide](/prompts) for the full documentation. ```yaml prompts/generate_summary@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 temperature: 0.7 --- You write concise company summaries for sales teams. Write a 2-3 paragraph summary of {{ companyName }}. Industry: {{ industry }} Company size: {{ size }} employees ``` ### Configuration Options | Option | Type | Description | | - | - | - | | `provider` | `string` | `anthropic`, `openai`, `azure`, `amazon-bedrock`, `google-vertex`, `perplexity`, or a provider registered with `registerProvider`. Legacy aliases `bedrock` and `vertex` are deprecated but still accepted and normalized with a warning. | | `model` | `string` | Model identifier | | `temperature` | `number` | Sampling temperature; supported range varies by provider | | `maxOutputTokens` | `number` | Maximum output tokens | | `maxTokens` | `number` | Deprecated compatibility key; prefer `maxOutputTokens` | | `topP` | `number` | Nucleus sampling value; usually set instead of `temperature` | | `topK` | `number` | Restricts sampling to the top K token choices | | `presencePenalty` | `number` | Penalizes tokens already present in the prompt or generated output | | `frequencyPenalty` | `number` | Penalizes tokens according to how often they appear | | `stopSequences` | `string[]` | Sequences that stop text generation | | `seed` | `number` | Random seed for deterministic text or image generation when supported | | `maxSteps` | `number` (default 10 after `loadPrompt`) | Tool-loop iterations when tools or skills are present | | `skills` | `string` or `string[]` in YAML; always `string[]` after `loadPrompt` (`[]` if omitted) | Skill file or directory paths, relative to this prompt | | `tools` | `object` | Provider-specific tools (web search, etc.) | | `providerOptions` | `object` | Provider-specific options - see [ProviderOptions Guide](/prompts#provider-options) | | `messageOptions` | `object` | Named per-message `providerOptions` sets | | `n`, `size`, `aspectRatio`, `maxImagesPerCall` | | Image generation fields | `loadPrompt` retains `maxTokens` on `config` for backward compatibility. When `maxOutputTokens` is absent, it also copies the `maxTokens` value to `maxOutputTokens`. When both keys are set, `maxOutputTokens` takes precedence. Text generation APIs use `maxOutputTokens`. Unknown top-level keys throw `Invalid prompt file`. Snake_case aliases of known fields (`max_output_tokens`) include a suggestion (`use "maxOutputTokens"`). Put provider-specific keys such as `effort` and `reasoningEffort` under `providerOptions`. ## Providers `@outputai/core/llm` requires `ai >=7 <8` and ships built-in support for common AI SDK providers. `ai` is a peer dependency of `@outputai/core` that npm and pnpm install automatically. The provider packages are optional peer dependencies, so install only the ones your prompts use: ```bash theme={null} pnpm add @ai-sdk/anthropic@4 @ai-sdk/openai@4 ``` | Prompt `provider` | Package | Supported range | | - | - | - | | `anthropic` | `@ai-sdk/anthropic` | `>=4 <5` | | `openai` | `@ai-sdk/openai` | `>=4 <5` | | `azure` | `@ai-sdk/azure` | `>=4 <5` | | `amazon-bedrock` | `@ai-sdk/amazon-bedrock` | `>=5 <6` | | `google-vertex` | `@ai-sdk/google-vertex` | `>=5 <6` | | `perplexity` | `@ai-sdk/perplexity` | `>=4 <5` | Legacy aliases `bedrock` -> `amazon-bedrock` and `vertex` -> `google-vertex` are deprecated but still work; prompt parsing normalizes them to their canonical names and logs a deprecation warning. Built-in provider instances are initialized lazily. Output creates the provider instance only when a prompt or API call first requests that provider, then reuses it for later calls. A prompt that uses a built-in provider whose package is not installed fails with `Provider "" requires the "" package, which is not installed`. `getProviderNames()` lists only the built-in providers whose package is installed, plus the ones added with `registerProvider()`. ### Anthropic ```yaml theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 --- ``` Requires `ANTHROPIC_API_KEY` environment variable. ### OpenAI ```yaml theme={null} --- provider: openai model: gpt-4o --- ``` Requires `OPENAI_API_KEY` environment variable. ### Azure OpenAI ```yaml theme={null} --- provider: azure model: gpt-4o --- ``` Requires `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT`, and `AZURE_OPENAI_API_VERSION`. ### Google Vertex AI ```yaml theme={null} --- provider: google-vertex model: gemini-1.5-pro --- ``` Requires `GOOGLE_VERTEX_PROJECT` and `GOOGLE_VERTEX_LOCATION`, plus service account credentials. The legacy alias `vertex` is still accepted. Set `GCP_CREDENTIALS_JSON` to the contents of your service account key file to authenticate without deploying the file itself: ```bash .env theme={null} GOOGLE_VERTEX_PROJECT=lead-enrichment-prod GOOGLE_VERTEX_LOCATION=us-central1 GCP_CREDENTIALS_JSON=eyJ0eXBlIjoic2VydmljZV9hY2NvdW50Iiw... ``` The value accepts the raw JSON document or its base64 encoding. Prefer base64 for `.env` files and container environments: a downloaded key file spans multiple lines, and most environment variable parsers stop at the first newline. ```bash theme={null} base64 -i gcp-credentials.json | tr -d '\n' ``` When `GCP_CREDENTIALS_JSON` is unset, the provider uses Application Default Credentials instead - a `GOOGLE_APPLICATION_CREDENTIALS` file path, a `gcloud auth application-default login` session, or the metadata server. On Cloud Run or GKE with workload identity, that means you configure the project and location and nothing else. ### Amazon Bedrock ```yaml theme={null} --- provider: amazon-bedrock model: anthropic.claude-sonnet-4-20250514-v1:0 --- ``` Requires AWS credentials (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`) or IAM role-based authentication. Set `AWS_SESSION_TOKEN` when using temporary credentials (e.g., from `aws sts assume-role`). The legacy alias `bedrock` is still accepted. For cross-region inference, use the regional inference profile format: `us.anthropic.claude-sonnet-4-20250514-v1:0`. Always set `maxOutputTokens` in your Bedrock prompt files. Unlike the direct Anthropic provider (which auto-detects per-model limits), the Bedrock SDK has no client-side defaults and relies on server-side defaults that may be lower than the model's capacity. When using `providerOptions`, use the AI SDK `bedrock` namespace (not `anthropic`): ```yaml theme={null} providerOptions: bedrock: guardrailConfig: guardrailIdentifier: my-guardrail guardrailVersion: "1" ``` ### Custom Providers Use `registerProvider` when you want prompt files to reference an AI SDK provider that is not built in, or when you need a custom provider instance: ```typescript theme={null} import { createVertexAnthropic } from '@ai-sdk/google-vertex/anthropic'; import { registerProvider } from '@outputai/core/llm'; registerProvider('vertex-anthropic', createVertexAnthropic({ project: process.env.GOOGLE_VERTEX_PROJECT, location: process.env.GOOGLE_VERTEX_LOCATION })); ``` Then use the registered provider name in prompt front matter: ```yaml theme={null} --- provider: vertex-anthropic model: claude-haiku-4-5 --- ``` Built-in providers use Output's default fetch configuration, including longer Undici response timeouts for LLM calls that take time before returning headers or body chunks. Custom registered providers are used exactly as you register them; they do not automatically receive that custom fetch. If your custom provider also needs longer network timeouts, configure its provider instance directly. LLM cost estimation looks up rates by `provider` + `model` in the [models.dev](https://models.dev) catalog. Built-in provider names match that catalog. A custom `registerProvider` name (such as `vertex-anthropic` above) will not match, so `response.cost` is an incomplete `LLMGenerationCost` with unavailable totals and a missing-pricing warning is logged - register under a models.dev provider id if you need automatic pricing. The catalog is fetched once and cached for a day. If a refresh fails, the previously cached rates are reused; if the catalog is unreachable before anything has been cached, the built-in providers fall back to a snapshot of the catalog bundled with `@outputai/core`. Every cost records which of these it used in `pricingFreshness`. Because the snapshot is point-in-time and can lag the live catalog by an unbounded amount, a cost priced from it is reported as `imprecise`; a merely stale cache is not, since those rates were accurate when they were fetched. Custom registered providers are not in the snapshot and get unavailable totals as described above. The snapshot is refreshed periodically, so upgrading to a newer `@outputai/core` picks up a more recent table. ## Prompt Caching When a prompt sends the same large prefix on every call - a long system prompt, few-shot examples, a pasted reference document - you can cache that prefix so the provider skips reprocessing it. Cached input is about 90% cheaper and faster to first token. How you enable it depends on the provider. ### Anthropic Anthropic caches only what you explicitly mark. Define a `cacheControl` set in `messageOptions` and attach it - with `options` - to the block that ends your static prefix. Everything up to and including that block is cached and reused on the next call: ```text prompts/generate_summary@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 messageOptions: cached: anthropic: cacheControl: type: ephemeral --- You write concise company summaries for sales teams. Follow this style guide: {{ style_guide }} Summarize {{ companyName }}. ``` Only the `` block - the part that changes each call - is re-billed at full price; the cached `` prefix is charged at the much cheaper cache-read rate. For the 1-hour cache instead of the default 5 minutes, add `ttl: 1h` under `cacheControl`. A block can reference several sets (`options="cached fast"`), and a set can be reused across blocks. Bare `options` and names missing from `messageOptions` throw when the prompt loads. > [!WARNING] > > Attach the set to the last **static** block, never one containing per-call `{{ variables }}`. A breakpoint on changing content rewrites the cache on every call and never gets a hit. Order your blocks static-first, dynamic-last. Each set is a provider-namespaced `providerOptions` object - the same shape and [namespace rules](/prompts#provider-options) as prompt-file `providerOptions`. On Vertex with a Claude model, use the same `anthropic` namespace. ### OpenAI OpenAI caches automatically - there are no breakpoints to set, so the `messageOptions` mechanism above isn't needed. Any prompt of 1024 tokens or longer is cached for you, with no markup. To improve hit rates across calls, set a stable `promptCacheKey` (and, on GPT-5.1+, extend retention) via `providerOptions`: ```yaml prompts/enrich_company@v1.prompt theme={null} --- provider: openai model: gpt-5 providerOptions: openai: promptCacheKey: enrich-company-v1 promptCacheRetention: 24h --- {{ enrichment_playbook }} Enrich {{ company }}. ``` ### Confirming a cache hit Cache activity appears in the response usage and the [metering event](/costs/cost-events): the first call reports cache creation in `usage.inputTokenDetails.cacheWriteTokens`, and later calls within the TTL report cache reads in `usage.inputTokenDetails.cacheReadTokens`. The corresponding normalized cost items use `group: "input"` with `label: "cache_write"` or `label: "cache_read"`. > [!NOTE] > > Anthropic caches only prefixes above a model-specific minimum - around 1,024 tokens for most Sonnet and Opus models, higher for some. Shorter prefixes are silently not cached, with no error. A request supports at most four cache breakpoints. ## Provider Tools Many providers offer built-in tools like web search. Configure them in YAML front matter: ```yaml prompts/research@v1.prompt theme={null} --- provider: google-vertex model: gemini-2.0-flash tools: googleSearch: mode: MODE_DYNAMIC dynamicThreshold: 0.8 --- Research {{ topic }} and provide sources ``` This is equivalent to calling the Vertex provider's `tools.googleSearch({ mode: 'MODE_DYNAMIC', dynamicThreshold: 0.8 })` at the code level, but keeps your prompt self-contained. YAML tools are merged with code-level tools, so you can combine provider tools (from YAML) with custom tools (from code). Code-level tools take precedence if names conflict. Normalized metering records per-request charges for Gemini grounding and Anthropic or OpenAI native web search as `tools` usage, separately from token usage. For provider-specific tool options, see: * [Vertex AI Tools](https://sdk.vercel.ai/docs/ai-sdk-providers/google-vertex#provider-instance-methods) * [OpenAI Tools](https://sdk.vercel.ai/docs/ai-sdk-providers/openai#provider-instance-methods) * [Anthropic Tools](https://sdk.vercel.ai/docs/ai-sdk-providers/anthropic#provider-instance-methods) * [Amazon Bedrock Tools](https://sdk.vercel.ai/docs/ai-sdk-providers/amazon-bedrock#provider-instance-methods) ## Tool Calling Use tools with `generateText` to enable function calling: ```typescript theme={null} import { generateText, aiSdk } from '@outputai/core/llm'; import { z } from '@outputai/core'; const { result, toolCalls } = await generateText({ prompt: 'agent@v1', variables: { task: 'Research competitor pricing' }, tools: { searchWeb: aiSdk.tool({ description: 'Search the web for information', inputSchema: z.object({ query: z.string() }), execute: async ({ query }) => fetchSearchResults(query) }) }, toolChoice: 'auto' }); ``` ## Call arguments `prompt` accepts either a prompt filename string or a loaded/custom `Prompt` object. When passing an object, do not also pass `promptDir` or `variables`: prompt objects are already resolved and rendered. For filename prompts, `variables` accepts Liquid values, including nested objects and arrays. Use dot notation and Liquid loops to read structured values in the prompt template. ### Text APIs | Argument | `generateText` | `generateTextWithStreaming` | `streamText` | | - | - | - | - | | `prompt` | required | required | required | | `promptDir` | optional | optional | optional | | `variables` | optional | optional | optional | | `tools` | optional | optional | optional | | `output` | optional | optional | optional | | `toolChoice` | optional | optional | optional | | `stopWhen` | optional | optional | optional | | `abortSignal` | optional | optional | optional | | `onChunk` | - | optional | optional | | `onEnd` | - | - | optional | | `onError` | - | - | optional | `toolChoice`, `stopWhen`, and prompt `maxSteps` apply only when tools exist. With tools, an explicit `stopWhen` takes precedence; otherwise Output uses `aiSdk.isStepCount(maxSteps)` from the prompt (default 10). ### generateImage | Argument | Required | Description | | - | - | - | | `prompt` | yes | Prompt filename or a loaded/custom `Prompt` object | | `promptDir` | no | Override the stack-resolved prompt directory for a filename prompt | | `variables` | no | Template variables for a filename prompt | | `images` | no | Source images for image-to-image | | `mask` | no | Inpainting mask; requires `images` | | `abortSignal` | no | Cancel the request | ### Agent Constructor options are set on `new Agent(...)`. `generate()`, `generateWithStreaming()`, and `stream()` take an optional args object (or omit it). `messages` defaults to `[]`. | Argument | `new Agent` | `.generate` | `.generateWithStreaming` | `.stream` | | - | - | - | - | - | | `prompt` | required | - | - | - | | `promptDir` | optional | - | - | - | | `variables` | optional | - | - | - | | `tools` | optional | - | - | - | | `output` | optional | - | - | - | | `stopWhen` | optional | - | - | - | | `messageStore` | optional | - | - | - | | `messages` | - | optional | optional | optional | | `abortSignal` | - | optional | optional | optional | | `toolChoice` | - | optional | optional | optional | | `onChunk` | - | - | optional | optional | | `onEnd` | - | - | - | optional | | `onError` | - | - | - | optional | ## Retries and Network Timeouts Output always sets AI SDK `maxRetries` to 0. In Output workflows, LLM calls usually run inside steps, and steps are Temporal activities. When a provider error fails the step, Temporal records the failed activity attempt and retries it according to the workflow's retry policy. `generateText`, `generateTextWithStreaming`, `Agent.generate()`, and `Agent.generateWithStreaming()` reject on failures. With direct `streamText` or `Agent.stream()` usage, capture the error in `onError` and throw it after consuming the stream, as shown in their direct-stream examples. A failure in the SDK's own response handling - reading the model response, merging sources, building the returned response - is not retried: it throws a non-retryable `FatalError` wrapping the original error, so Temporal fails the activity on the first attempt. Such a failure is deterministic, and a retry would pay for the model call again and fail the same way. The usage already spent is still billed and recorded on the trace. Built-in providers are initialized with a custom fetch that extends Undici's `headersTimeout` and `bodyTimeout` to 15 minutes. This helps long-running LLM responses where the provider accepts the request but takes longer to return response headers or body chunks, for example reasoning-heavy calls. Active cancellation still works: if you pass `abortSignal`, or the AI SDK/provider aborts the request, that cancellation wins. ## LLM metering events For direct streams, metering events fire when the stream finishes. Observe them with the [hooks mechanism](/packages/core#error-hooks) by registering handlers with `on()` from `@outputai/core/hooks` in a hook file listed under `outputai.hookFiles`. ### Normalized generation metering `llm:generation:metering` is emitted whenever raw AI SDK usage can be normalized. Its payload contains `usage: LLMGenerationUsage` and `cost: LLMGenerationCost | null`. Missing model or dimension prices produce an incomplete `LLMGenerationCost`. Both carry the `promptName` of the call and its `requestDetails`: the provider request IDs, the request count and the duration in milliseconds. See [Request details](/costs/cost-events#request-details). ```typescript theme={null} import { on } from '@outputai/core/hooks'; import type { LLMGenerationMeteringEvent } from '@outputai/core/llm'; on('llm:generation:metering', event => { if (!event.payload) { return; } console.log(event.payload.usage.total, event.payload.cost?.total); }); ``` ### Legacy LLM request cost `cost:llm:request` remains available with its legacy `LLMUsageEvent` payload, so existing hooks do not need a structural migration. The same payload remains attached to priced LLM traces as the deprecated `attributes["llm:usage"]` attribute, preserving existing trace readers. ```typescript theme={null} import { on } from '@outputai/core/hooks'; import type { LLMUsageEvent } from '@outputai/core/llm'; on('cost:llm:request', event => { if (!event.payload) { return; } console.log(event.payload.modelId, event.payload.total, event.payload.usage); }); ``` ```json theme={null} { "type": "llm:usage", "modelId": "gpt-4o", "usage": [ { "type": "input", "ppm": 5, "amount": 217, "total": 0.001085 }, { "type": "output", "ppm": 15, "amount": 9, "total": 0.000135 } ], "total": 0.00122, "tokensUsed": 226 } ``` Legacy usage line types are frozen as `input`, `input_cached`, `output`, and `reasoning`. The event and trace attribute keep this payload shape for compatibility, while corrected reasoning accounting or AI SDK 7 usage details can change individual values. `LLMUsageEvent` is deprecated only to guide new integrations toward the more complete event and normalized trace attributes. See [Cost Events](/costs/cost-events) for the complete normalized usage/cost schemas and HTTP cost events. ## loadPrompt Load and render a prompt file for inspection, reuse, or direct use as a generation argument: ```typescript theme={null} import { loadPrompt } from '@outputai/core/llm'; const prompt = loadPrompt('generate_summary@v1', { companyName: 'Acme Corp', industry: 'SaaS', size: 250 }); console.log(prompt.config); // includes skills: string[] and maxSteps (default 10) console.log(prompt.messages); // PromptMessage[] with system, user, or assistant roles console.log(prompt.instructions); // string | null console.log(prompt.variables); // { companyName: 'Acme Corp', industry: 'SaaS', size: 250 } ``` The returned `Prompt` can be passed directly to `generateText`, `generateTextWithStreaming`, `streamText`, `generateImage`, or `new Agent()`. See [Passing Prompt Objects Directly](/prompts#passing-prompt-objects-directly). For instruction-mode prompts, `messages` is empty and `instructions` contains the rendered body. For message-mode prompts, `messages` contains the parsed role blocks and `instructions` is `null`. See [Prompt Body Modes](/prompts#prompt-body-modes). `PromptMessage.role` is typed as `'system' | 'user' | 'assistant'`, matching the authored role blocks accepted in message mode. ## LLM Judges `judgeVerdict`, `judgeScore`, `judgeBoolean`, and `judgeLabel` call `generateText` with a judge prompt and return an evaluation result, for use in [eval workflow evaluators](/packages/core/evals#llm-judge-functions): ```typescript theme={null} import { verify } from '@outputai/core/evals'; import { judgeVerdict } from '@outputai/core/llm'; export const evaluateTopic = verify( { name: 'evaluate_topic' }, ({ output }) => judgeVerdict({ prompt: 'judge_topic@v1', variables: { blog_post: output.blog_post } }) ); ``` The prompt file is resolved from the directory of the file calling the judge. Each judge has a default output schema, and `schema` replaces it. See [LLM Judge Functions](/packages/core/evals#llm-judge-functions) for the schemas and returned result types. ## API Reference For complete TypeScript API documentation, see the [LLM Module API Reference](https://output-ai-reference-code-docs.onrender.com/modules/core_src_llm.html). # Production Prompts Source: https://docs.output.ai/prompts/best-practices Write effective prompts for production AI workflows Production prompts need to be reliable, not clever. This guide covers patterns that work consistently across thousands of runs. The examples below use [message mode](/prompts#prompt-body-modes): the rendered body starts with a role tag, and all top-level content stays inside supported role blocks. Text generation APIs require message mode. Use instruction mode for image prompts or when consuming `loadPrompt()` results directly. ## System Messages The system message defines who the LLM is and how it behaves. Be specific. **Vague (bad):** ```yaml theme={null} You are a helpful assistant. ``` **Specific (good):** ```yaml theme={null} You are a sales research assistant at a B2B SaaS company. You help sales teams prepare for calls by summarizing prospect information. Rules: - Be factual and concise - Never make up information — if something is unclear, say so - Focus on business-relevant details: what they do, who they sell to, recent news - Skip generic company boilerplate ``` The specific version produces consistent, useful output. The vague version produces whatever the model feels like. ### Constraints Matter Explicit constraints prevent the most common failure modes: ```yaml theme={null} You classify leads by buying intent based on their activity. Constraints: - Only use the categories: high, medium, low, unknown - When uncertain between two categories, choose the lower intent - Never create new categories - If activity data is insufficient, classify as "unknown" ``` Without constraints, the model might invent categories, misclassify edge cases inconsistently, or add explanations you don't want. ## Temperature Settings Temperature controls randomness. Match it to your task: | Temperature | Use Case | Example | | - | - | - | | `0` | Judges, extraction, classification | Evaluator prompts, extracting entities, classifying leads | | `0.3` | Analysis, summarization | Company research summaries, content analysis | | `0.7` | General tasks, balanced creativity | Drafting emails, writing descriptions | | `1.0+` | Brainstorming, creative writing | Generating variations, ideation | For production workflows, err toward lower temperatures. A temperature of 0 means the same input produces the same output — essential for debugging and testing. Judge prompts should always use temperature 0. ```yaml judge_summary@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 temperature: 0 --- You evaluate company research summaries for a sales team. A good summary must: 1. Mention what the company does (their core product or service) 2. Identify their target market or customer base 3. Include at least one specific, verifiable fact 4. Be 2-4 paragraphs long 5. Not contain any claims that aren't supported by the provided source data ``` ## Structured Output When you need to parse the result programmatically, use `generateText` with `aiSdk.Output.object()` and a Zod schema instead of asking for JSON in the prompt. **Unreliable (parsing JSON from text):** ```yaml theme={null} Extract the company info and return as JSON with fields: name, industry, employee_count. ``` **Reliable (schema-validated):** ```typescript theme={null} const { output } = await generateText({ prompt: 'extract_company@v1', variables: { content: websiteContent }, output: aiSdk.Output.object({ schema: z.object({ name: z.string(), industry: z.string(), employeeCount: z.number().nullable() }) }) }); ``` The schema is validated server-side by the LLM provider. You get typed output or an error — no parsing surprises. ### Keep Schemas Simple Complex nested schemas confuse models. If your schema has more than 5-6 fields or deep nesting, split it into multiple calls. **Too complex:** ```typescript theme={null} const schema = z.object({ company: z.object({ name: z.string(), details: z.object({ industry: z.string(), subIndustry: z.string(), // ... 10 more nested fields }) }), competitors: z.array(z.object({ // ... another complex structure })) }); ``` **Better — split into focused calls:** ```typescript theme={null} const { output: company } = await generateText({ prompt: 'extract_company@v1', output: aiSdk.Output.object({ schema: companySchema }), ... }); const { output: competitors } = await generateText({ prompt: 'find_competitors@v1', output: aiSdk.Output.array({ element: competitorSchema }), ... }); ``` ## Few-Shot Examples Show the LLM what you want with 2-3 examples. This works better than lengthy instructions. ```yaml theme={null} Classify this lead's buying intent: high, medium, low, or unknown. Examples: - "Downloaded pricing page, requested demo, visited 5 pages" → high - "Read two blog posts, signed up for newsletter" → medium - "Visited homepage once from a Google ad" → low Lead activity: {{ activity }} ``` Few-shot examples are especially effective for: * Classification tasks * Formatting requirements * Edge case handling * Tone matching ## Common Mistakes ### 1. No Role Definition ```yaml theme={null} # Bad — no context for the model Summarize this company: {{ content }} ``` ```yaml theme={null} # Good — clear role and purpose You create concise company summaries for sales teams. Your audience is busy sales reps who want key takeaways before a call. Summarize this company: {{ content }} ``` ### 2. Unbounded Creativity ```yaml theme={null} # Bad — model will write a novel Write about {{ company_name }}. ``` ```yaml theme={null} # Good — clear bounds Write a 2-paragraph company overview for {{ company_name }}. Paragraph 1: What they do and who they serve. Paragraph 2: Recent developments or notable achievements. ``` ### 3. Asking for Everything at Once ```yaml theme={null} # Bad — too many things, inconsistent results Analyze this company: give me an overview, list competitors, identify their tech stack, summarize recent news, and predict their growth trajectory. ``` ```yaml theme={null} # Good — focused request, combine in workflow Based on this content, identify 3-5 direct competitors for {{ company_name }}. Only list companies that compete for the same customers. ``` Run multiple focused prompts and combine results in your workflow. This is what steps are for. ## Writing Style Guidelines For prompts that generate customer-facing content, define explicit style rules: ```yaml theme={null} You write company research briefs for sales teams. Writing guidelines: - Voice: Professional but conversational, not corporate - Objectivity: State facts, avoid superlatives ("leading", "best-in-class") - Language: Clear and direct, no jargon unless industry-specific - Structure: Use bullet points for lists, short paragraphs for narrative - Length: 200-300 words unless specified otherwise ``` These constraints produce consistent output that matches your brand voice. ## Output Shape Selection Match the `Output.*` helper to your output shape: | Need | Output Helper | Example | | - | - | - | | Free-form text | *(none)* | Summaries, emails, explanations | | Typed object | `aiSdk.Output.object({ schema })` | Extracted data, evaluator judgments | | List of items | `aiSdk.Output.array({ element })` | Contacts, competitors, action items | | One of N choices | `aiSdk.Output.choice({ options })` | Lead classification, sentiment | ```typescript theme={null} // Classification → aiSdk.Output.choice const { output: intent } = await generateText({ prompt: 'classify_lead@v1', variables: { activity: leadActivity }, output: aiSdk.Output.choice({ options: ['high', 'medium', 'low', 'unknown'] }) }); // Extraction → aiSdk.Output.object const { output: company } = await generateText({ prompt: 'extract_company@v1', variables: { content: websiteContent }, output: aiSdk.Output.object({ schema: companySchema }) }); // List → aiSdk.Output.array const { output: competitors } = await generateText({ prompt: 'find_competitors@v1', variables: { companyName: 'Acme Corp', industry: 'SaaS' }, output: aiSdk.Output.array({ element: z.object({ name: z.string(), reason: z.string() }) }) }); ``` ## Further Reading * [Anthropic's prompt engineering guide](https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering) * [LLM-as-a-Judge Best Practices](/evaluators/best-practices) — Writing effective judge prompts specifically # Writing Prompt Files Source: https://docs.output.ai/prompts/index Version-controlled prompts with YAML configuration and structured message or instruction bodies Prompts in Output live in `.prompt` files inside a `prompts/` folder — version-controlled, reviewable, and deployed with your code. No more strings scattered across your codebase or prompts locked in external dashboards. ```yaml generate_summary@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 temperature: 0.3 maxOutputTokens: 2000 --- You are a sales research assistant. You help sales teams prepare for calls by summarizing company information. Be factual and concise. Never make up information. If something is unclear from the provided data, say so. Research this company and provide a brief summary for a sales call: Company: {{ company_name }} Website content: {{ website_content }} Include: what they do, target market, recent news if available, and potential pain points we could address. ``` A prompt file has two parts: YAML frontmatter (configuration) and a body containing either role-tagged messages or plain instructions. ## File Naming Prompt files use the pattern `name@version.prompt`: * `generate_summary@v1.prompt` * `judge_summary@v1.prompt` * `classify_lead@v2.prompt` The version lets you iterate on prompts while keeping old versions around. When you reference a prompt in code, use the name without the `.prompt` extension: ```typescript theme={null} await generateText({ prompt: 'generate_summary@v1', variables: { company_name: 'Acme Corp', website_content: '...' } }); ``` Output searches recursively from your workflow's directory to find the prompt file. ## Passing Prompt Objects Directly `generateText`, `generateTextWithStreaming`, `streamText`, `generateImage`, and `new Agent()` also accept a loaded or custom `Prompt` object. This lets you load a prompt once or supply one from another source: ```typescript theme={null} import { generateText, loadPrompt } from '@outputai/core/llm'; const prompt = loadPrompt('generate_summary@v1', { company_name: 'Acme Corp', website_content: '...' }); await generateText({ prompt }); ``` A custom object must match the normalized `Prompt` shape: ```typescript theme={null} import { generateText } from '@outputai/core/llm'; import type { Prompt } from '@outputai/core/llm'; const prompt: Prompt = { name: 'custom-summary', fileDir: process.cwd(), variables: {}, config: { provider: 'openai', model: 'gpt-4o', maxSteps: 10, skills: [] }, messages: [ { role: 'user', content: 'Summarize the latest account activity.' } ], instructions: null }; await generateText({ prompt }); ``` Prompt objects are already resolved and rendered, so `promptDir` and call-level `variables` cannot be used with them. `fileDir` remains the base directory for relative skill paths. Use canonical provider names in custom objects. Deprecated aliases are still accepted and normalized with a warning. > [!WARNING] > > Only accept prompt objects from trusted sources. They can select providers and models and load local skill files relative to `fileDir`. ## File Organization Place prompt files in a `prompts/` subfolder within your workflow directory: ``` src/workflows/ ├── lead_enrichment/ │ ├── workflow.ts │ ├── steps.ts │ ├── evaluators.ts │ ├── types.ts │ └── prompts/ │ ├── generate_summary@v1.prompt │ └── judge_summary@v1.prompt ├── classify_tickets/ │ ├── workflow.ts │ ├── steps.ts │ └── prompts/ │ └── classify@v1.prompt └── shared/ └── prompts/ └── check_factuality@v1.prompt # Shared across workflows ``` The recursive search means you can also keep prompts alongside your workflow code if you prefer a flatter structure. For prompts used by multiple workflows, create a shared `prompts/` folder at a higher level. ## Frontmatter The YAML frontmatter configures the LLM call. ### Required Fields | Field | Description | Example | | - | - | - | | `provider` | LLM provider | `anthropic`, `openai`, `azure`, `amazon-bedrock`, `google-vertex`, `perplexity` (legacy aliases: `bedrock`, `vertex`) | | `model` | Model identifier | `claude-sonnet-4-20250514`, `gpt-4o` | Each built-in provider needs its AI SDK package installed in your project, such as `@ai-sdk/anthropic` for `anthropic`. New projects ship with `@ai-sdk/anthropic` and `@ai-sdk/openai`. See [Providers](/packages/core/llm#providers) for the full list. ### Optional Fields | Field | Description | Example | | - | - | - | | `temperature` | Sampling temperature; supported range varies by provider | `0` for judges, `0.3` for summaries, `0.7` for general | | `maxOutputTokens` | Maximum output tokens | `2000` | | `maxTokens` | Deprecated compatibility key; prefer `maxOutputTokens` | `2000` | | `topP` | Nucleus sampling value; usually set instead of `temperature` | `0.9` | | `topK` | Restrict sampling to the top K token choices | `40` | | `presencePenalty` | Penalize tokens already present in the prompt or generated output | `0.2` | | `frequencyPenalty` | Penalize tokens according to how often they appear | `0.2` | | `stopSequences` | Stop text generation when one of these sequences is produced | `["END"]` | | `seed` | Random seed for deterministic text or image generation when supported | `42` | | `maxSteps` | Tool-loop iterations when tools or skills are present (default 10). Always a positive integer after `loadPrompt`. | `5` | | `skills` | Skill file or directory paths, relative to this prompt. YAML may be a string or array; after `loadPrompt` always `string[]` (`[]` if omitted). | `./skills`, `../shared/tone.md` | | `tools` | Provider-specific tools | Vertex `googleSearch`, OpenAI `webSearch` | | `providerOptions` | Provider-specific config | See below | | `messageOptions` | Named per-message `providerOptions` sets | See [Prompt Caching](/packages/core/llm#prompt-caching) | | `n`, `size`, `aspectRatio`, `maxImagesPerCall` | Image generation fields | See [Image Output](/packages/core/llm#image-output) | `loadPrompt` retains `maxTokens` on `config` for backward compatibility. When `maxOutputTokens` is absent, it also copies the `maxTokens` value to `maxOutputTokens`. When both keys are set, `maxOutputTokens` takes precedence. Text generation APIs use `maxOutputTokens`. All fields use **camelCase**. Unknown top-level keys throw. A snake_case alias of a known field fails with a suggestion (`max_output_tokens` -> use `maxOutputTokens`). Provider-specific keys such as `effort` and `reasoningEffort` belong under `providerOptions`, not at the top level. ```yaml theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 temperature: 0.3 maxOutputTokens: 2000 --- ``` ### Configuration Structure Prompt configurations have two layers: **1. Top-level config** — Standard AI SDK options: ```yaml theme={null} provider: anthropic model: claude-sonnet-4-20250514 temperature: 0.7 # Standard option maxOutputTokens: 4000 # Standard option maxSteps: 5 # Tool-loop ceiling when tools or skills are present (default 10) ``` **2. providerOptions** — Provider-specific and special options: ```yaml theme={null} providerOptions: thinking: # Special: AI SDK extension (top-level) type: enabled budgetTokens: 5000 anthropic: # Provider-specific options (nested) effort: medium ``` **When to use providerOptions:** * Provider-specific options that aren't standard across all providers * Special AI SDK extensions like `thinking` or `order` (AI Gateway) * Multi-provider configurations (Vertex with multiple model types) **When NOT to use providerOptions:** * Shared top-level fields: `temperature`, `maxOutputTokens`, `topP`, `topK`, `presencePenalty`, `frequencyPenalty`, `stopSequences`, `seed`, `maxSteps`, `skills`, `tools`, `messageOptions`, and the image fields (`n`, `size`, `aspectRatio`, `maxImagesPerCall`) * These go at the top level alongside `provider` and `model` ### Provider Options Use `providerOptions` for provider-specific configuration. **Anthropic-specific options:** ```yaml theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 providerOptions: anthropic: # Namespace for Anthropic-specific options effort: medium # Not available on other providers --- ``` **OpenAI-specific options:** ```yaml theme={null} --- provider: openai model: gpt-4o providerOptions: openai: # Namespace for OpenAI-specific options maxToolCalls: 1 reasoning: true --- ``` **Google Vertex with Gemini (important namespace note):** ```yaml theme={null} --- provider: google-vertex model: gemini-2.0-flash providerOptions: google: # Use 'google' for Gemini, not 'google-vertex'! useSearchGrounding: true --- ``` **Extended thinking (special top-level key):** ```yaml theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 providerOptions: thinking: # Special: stays at top level (not under 'anthropic') type: enabled budgetTokens: 5000 anthropic: # Provider-specific options effort: medium --- ``` **Common Provider Options Reference:** | Provider | Option | Namespace | Description | | - | - | - | - | | Anthropic | `effort` | `anthropic:` | Reasoning effort: `low`, `medium`, `high` | | OpenAI | `reasoningEffort` | `openai:` | Reasoning effort for o1 models | | OpenAI | `maxToolCalls` | `openai:` | Maximum tool calls per turn | | Vertex (Gemini) | `useSearchGrounding` | `google:` | Enable Gemini search grounding | | Vertex (Claude) | `effort` | `anthropic:` | Claude models on Vertex use anthropic namespace | | AI SDK | `thinking` | Top-level | Extended thinking (not under provider) | | AI Gateway | `order` | Top-level | Provider routing order | **Google Vertex Provider Namespace Guide:** When using `provider: google-vertex` (or the legacy alias `vertex`), the `providerOptions` namespace depends on the model: * **Gemini models** → Use `google:` namespace * **Claude models** → Use `anthropic:` namespace * **Vertex-specific options** → Use `vertex:` namespace ## Prompt Body Modes After rendering the template, Output determines how to parse the body from its first meaningful token. Leading whitespace and HTML comments (``) do not affect this decision: * If the first meaningful token is plain text, the whole trimmed body becomes `instructions` and `messages` is empty. Tags later in the body stay part of the instruction text. * If the first meaningful token is a tag, Output enters message mode and validates the body as role-tagged markup. `instructions` is `null`. Use instruction mode for image prompts or when consuming `loadPrompt()` results directly. `generateText`, `generateTextWithStreaming`, `streamText`, and `Agent` require message mode. ```yaml theme={null} --- provider: openai model: gpt-image-1 --- Create a cinematic product photograph of {{ product }}. ``` Use message mode when the provider should receive a conversation: ```yaml theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 --- You write concise product descriptions. Describe {{ product }}. ``` In message mode: * Top-level tags must be ``, ``, or ``. * Between top-level blocks, only whitespace and HTML comments are allowed. * Top-level self-closing tags and closing tags without an opening block are invalid. * Every top-level block needs a matching closing tag. * Tags with a different name inside a message are preserved as message content. This includes semantic tags, HTML-like examples, and code such as `Array`. * A nested non-self-closing tag with the same name as its message is ambiguous and throws. Escape literal examples, including both brackets, such as `<user>example</user>`. These rules are validated when the prompt loads. Invalid roles, root text, malformed attributes, and unclosed blocks produce explicit errors instead of being silently ignored. ## Message Blocks Message blocks use XML-style tags to define the conversation structure. ### `` The system message sets the persona and constraints. It defines *who* the LLM is and *how* it should behave. This stays constant across requests. ```yaml theme={null} You are a sales research assistant. You summarize company information for sales teams. Rules: - Be factual and concise - Never make up information - Focus on business-relevant details ``` ### `` The user message is the actual request — *what* you want right now. This typically contains your variables. ```yaml theme={null} Write a company summary for {{ company_name }}. Industry: {{ industry }} Company size: {{ size }} employees Website content: {{ website_content }} ``` ### `` The assistant block is for conversation history or response prefilling. Use it when you want to prime the model's response format. `generateText`, `generateTextWithStreaming`, and `streamText` send it as part of the prompt thread. `Agent` drops authored `` blocks; it only seeds `` turns (system goes to `instructions`). For Agent few-shot or prefills, put examples in `` or ``, or use `generateText`. ```yaml theme={null} Based on my analysis, here is the company summary: ``` Authored `` blocks are not supported. AI SDK tool results use structured message parts tied to a preceding tool call; AI SDK creates these during tool execution, and Agent callers may supply them through `messages` or `messageStore`. ### `options` The only supported attribute on a role tag is `options`, a space-separated list of names from frontmatter `messageOptions`. At load, those sets are merged from left to right onto the message as `providerOptions`; later sets win when the same provider option is repeated. Give `options` an explicit quoted or unquoted value, such as `options="cached fast"` or `options=cached`. Bare `options` throws, while `options=""` is treated as absent. Every referenced name must exist in `messageOptions`, and any other role-tag attribute throws. See [Prompt Caching](/packages/core/llm#prompt-caching). ## System vs User A common mistake is putting everything in the user message. The split matters: **System message** (constant): * Who the LLM is ("You are a sales research assistant") * Behavioral constraints ("Never make up information") * Output format requirements ("Respond in JSON") **User message** (varies per request): * The specific request * The data to process * Dynamic instructions based on input This separation makes prompts easier to maintain. When you need to change the task, you edit the user message. When you need to change behavior, you edit the system message. ## Using Prompts Call prompts from your steps using the generate functions from `@outputai/core/llm`. ### With generateText For single-shot LLM calls, use `generateText`: ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { generateText } from '@outputai/core/llm'; import { GenerateSummaryInput, GenerateSummaryOutput } from './types.js'; export const generateSummary = step({ name: 'generateSummary', description: 'Generate a company summary from research data', inputSchema: GenerateSummaryInput, outputSchema: GenerateSummaryOutput, fn: async (input) => { const { result } = await generateText({ prompt: 'generate_summary@v1', variables: { company_name: input.name, website_content: input.websiteContent } }); return result; } }); // types.ts // import { z } from '@outputai/core'; // // export const GenerateSummaryInput = z.object({ // name: z.string(), // websiteContent: z.string() // }); // // export const GenerateSummaryOutput = z.string(); ``` `generateText` also supports [skills](/prompts/skills) for on-demand instruction loading. List skill paths in the prompt frontmatter. Set `maxSteps` in the same frontmatter when the default of 10 is wrong. ### With Agent For multi-step tool loops and stateful conversations, use the `Agent` class: ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { Agent } from '@outputai/core/llm'; import { ReviewContentInput, ReviewContentOutput } from './types.js'; export const reviewContent = step({ name: 'reviewContent', description: 'Review technical content with structured feedback', inputSchema: ReviewContentInput, outputSchema: ReviewContentOutput, fn: async (input) => { const agent = new Agent({ prompt: 'writing_assistant@v1', variables: { content_type: 'documentation', focus: 'clarity', content: input.content } }); const { text } = await agent.generate(); return text; } }); ``` Use `generateText` for single-shot LLM calls. Use `Agent` when you need multi-step tool execution, conversation history, or a reusable agent instance. See the [Agents section](/packages/core/llm#agents) for the full API. The `variables` object maps to the `{{ variable }}` placeholders in your prompt. For dynamic content like conditionals and loops, see [Templating](/prompts/templating). # Skills Source: https://docs.output.ai/prompts/skills Load detailed instructions on demand to keep prompts lightweight Prompts get unwieldy when you pack every instruction into the system message. Skills solve this. They are lazy-loaded instruction packages that keep your initial context window small while providing deep expertise on demand. ## How Skills Work Skills are text documents parsed as Markdown, with a name, description, and body of instructions. At prompt render time, Output builds a summary of available skills and adds it to the system message. The LLM decides which skills are relevant for the task and loads them when necessary. ## Providing Skills List skill paths in the prompt YAML frontmatter. Paths can be individual files of any extension or directories, resolved relative to the prompt file. Explicit files are loaded regardless of extension; directory scans load only `.md` files. A `skills/` folder next to the prompt is not loaded unless you list it. ``` prompts/ ├── writing_assistant@v1.prompt └── skills/ ├── clarity_guidelines.md ├── response_format.md └── structure_guide.md ``` ```yaml writing_assistant@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 maxOutputTokens: 2048 maxSteps: 5 skills: - ./skills - ../shared_skills/tone_guide.md --- You are an expert technical writing assistant. Use load_skill to get the full instructions for any skill before applying it. Review the following {{ content_type }} content focusing on {{ focus }}. Content: {{ content }} ``` List skill paths in the prompt YAML frontmatter. Skills add a `load_skill` tool, so set `maxSteps` in the same frontmatter when the default of 10 is wrong. Omit `skills` (or set `skills: []`) when a prompt should load none. That is the default: a sibling `skills/` folder used by other prompts in the same directory is not inherited. ## Skill File Format Skill files are parsed as Markdown documents with an optional YAML frontmatter block: ```markdown clarity_guidelines.md theme={null} --- name: clarity_guidelines description: Rules for writing clear, readable technical content --- # Clarity Guidelines When reviewing or writing technical content for clarity: 1. **Sentence length**: Keep sentences under 25 words when possible. Break complex ideas into multiple sentences. 2. **Active voice**: Prefer active voice ("The function returns X") over passive ("X is returned by the function"). 3. **Jargon**: Define technical terms on first use. Avoid unnecessary acronyms without explanation. 4. **Concrete examples**: Every abstract concept should have a concrete example. When applying this skill, flag any violations you find and suggest improvements. ``` | Field | Required | Default | Description | | - | - | - | - | | `name` | No | Filename without a trailing `.md`; other extensions are retained | Identifier the LLM uses with `load_skill` | | `description` | No | Same as `name` | When to use this skill (shown in system message) | | Body | Yes | - | Full instructions returned by `load_skill` | If you omit the frontmatter entirely, the filename without a trailing `.md` is used as both the name and description. Other extensions are retained, so `tone.txt` defaults to `name: "tone.txt"` and `description: "tone.txt"`. Write good descriptions. They're what the LLM uses to decide whether to load a skill. "Rules for writing clear, readable technical content" is better than "clarity_guidelines". # Templating with Variables Source: https://docs.output.ai/prompts/templating Use Liquid.js to create dynamic prompts with variables, conditionals, and loops Prompt files use [Liquid.js](https://liquidjs.com/) for dynamic content. Instead of hardcoding values, you insert variables that get filled in when the prompt runs. ```yaml generate_summary@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 temperature: 0.3 --- You summarize company information for sales teams. Write a {{ max_paragraphs }}-paragraph summary of this company: {{ company_data }} ``` When you call `generateText({ prompt: 'generate_summary@v1', variables: { max_paragraphs: 2, company_data: '...' } })`, Liquid replaces `{{ max_paragraphs }}` with `2` and `{{ company_data }}` with your content before the prompt is sent to the LLM. Templates render before YAML parsing, so you can template the frontmatter too — useful for dynamic model selection or configuration. The rendered body is then parsed as either [plain instructions or role-tagged messages](/prompts#prompt-body-modes). A template that emits plain text first selects instruction mode; one that emits a tag first selects message mode. Text generation APIs require message mode, while `generateImage` requires instruction mode. ## Variables The double-brace syntax `{{ variableName }}` renders values from the `variables` object you pass to the generate function. ```yaml theme={null} Write a company summary for {{ company_name }} in the {{ industry }} industry. ``` ```typescript theme={null} await generateText({ prompt: 'generate_summary@v1', variables: { company_name: 'Acme Corp', industry: 'SaaS' } }); ``` For nested objects, use dot notation: ```yaml theme={null} Write a summary for {{ company.name }} ({{ company.industry }}, {{ company.size }} employees). ``` ```typescript theme={null} variables: { company: { name: 'Acme Corp', industry: 'SaaS', size: 250 } } ``` Undefined variables and unknown filters throw a non-retryable `FatalError` at render time (`strictVariables` / `strictFilters`). Pass every variable the template references, and only use known Liquid filters. Validate inputs in your step before calling the LLM. ### Variables containing markup Output automatically XML-escapes body interpolations before it identifies message blocks, then decodes the value inside the resulting message or instructions. A variable containing `example` therefore remains data and cannot inject a new message: ```yaml theme={null} Review this example: {{ content }} ``` Do not add Liquid's `escape` filter for this safety behavior; it would escape a value that Output already protects. Use `{% raw %}...{% endraw %}` when the authored template itself must contain literal Liquid delimiters such as `{{ example }}`. In message mode, authored examples of the surrounding role tag must still be escaped. For example, write `<user>example</user>` inside a `` block. See [Prompt Body Modes](/prompts#prompt-body-modes). ## Conditionals Use `{% if %}` to include content only when a condition is true: ```yaml theme={null} You are a sales research assistant. {% if include_competitors %} When relevant, mention how this company compares to competitors. {% endif %} Write a summary for {{ company_name }}. ``` With `include_competitors: true`, the competitor instruction is included. With `false` or undefined, it's omitted entirely. Add `{% else %}` for alternate content: ```yaml theme={null} {% if detailed %} Provide a comprehensive analysis with industry context, competitive positioning, and growth trajectory. {% else %} Give a brief overview in 2-3 paragraphs. {% endif %} ``` Use `{% unless %}` for the inverse — it renders when the condition is falsy: ```yaml theme={null} {% unless skip_pain_points %} Include potential pain points we could address in a sales call. {% endunless %} ``` ## Loops Iterate over arrays with `{% for %}`: ```yaml theme={null} Evaluate this company summary against these criteria: {% for criterion in criteria %} {{ forloop.index }}. {{ criterion }} {% endfor %} Summary: {{ summary }} ``` `forloop.index` gives you the 1-based position (1, 2, 3...). Use `forloop.index0` for 0-based indexing. For arrays of objects: ```yaml theme={null} Compare these companies: {% for company in companies %} - {{ company.name }}: {{ company.industry }}, {{ company.size }} employees {% endfor %} Which is the strongest competitor? ``` ## Filters Filters transform values using the pipe syntax `{{ value | filter }}`. **Text transformations:** ```yaml theme={null} {{ company_name | upcase }} # "ACME CORP" {{ company_name | downcase }} # "acme corp" {{ company_name | capitalize }} # "Acme corp" ``` **Arrays:** ```yaml theme={null} {{ industries | join: ", " }} # "SaaS, FinTech, Healthcare" {{ companies | first }} # First element {{ companies | last }} # Last element {{ companies | size }} # Array length ``` **Default values:** ```yaml theme={null} {{ tone | default: "professional" }} ``` If `tone` is undefined or empty, it renders as "professional". **Chaining filters:** ```yaml theme={null} {{ company_name | downcase | replace: " ", "-" }} # "Acme Corp" becomes "acme-corp" ``` For the full filter reference, see the [Liquid.js documentation](https://liquidjs.com/filters/overview.html). ## Templating Frontmatter Variables work in the YAML frontmatter too. This lets you dynamically configure model settings: ```yaml theme={null} --- provider: {{ provider }} model: {{ model_name }} temperature: {{ temperature | default: 0.7 }} --- {{ prompt_text }} ``` ```typescript theme={null} await generateText({ prompt: 'flexible@v1', variables: { provider: 'anthropic', model_name: 'claude-sonnet-4-20250514', temperature: 0.3, prompt_text: 'Summarize this company...' } }); ``` Use this pattern when you need to switch models based on task complexity or cost. ## Common Patterns **Optional sections based on input:** ```yaml theme={null} Research {{ company_name }}. {% if focus_areas %} Focus specifically on: {% for area in focus_areas %} - {{ area }} {% endfor %} {% endif %} {% if competitor_names %} Compare against these competitors: {{ competitor_names | join: ", " }} {% endif %} ``` **Building structured instructions from an array of rules:** ```yaml theme={null} You are a {{ role }} assistant. Your response must: {% for rule in rules %} {{ forloop.index }}. {{ rule }} {% endfor %} ``` **Conditional system behavior:** ```yaml theme={null} You help sales teams research companies. {% if include_reasoning %} Explain your reasoning before providing the final output. {% endif %} {% unless allow_creativity %} Stick strictly to the facts provided. Do not add information. {% endunless %} ``` ## Cheatsheet Quick reference for the most common Liquid.js syntax. ### Output | Syntax | Description | Example | | - | - | - | | `{{ variable }}` | Output a variable | `{{ name }}` → `Acme Corp` | | `{{ obj.property }}` | Dot notation | `{{ company.industry }}` → `SaaS` | | `{{ array[0] }}` | Array index | `{{ items[0] }}` → first item | ### Tags | Syntax | Description | | - | - | | `{% if condition %}...{% endif %}` | Conditional block | | `{% if condition %}...{% else %}...{% endif %}` | If/else | | `{% elsif condition %}` | Else if | | `{% unless condition %}...{% endunless %}` | Negative conditional | | `{% for item in array %}...{% endfor %}` | Loop over array | | `{% assign var = value %}` | Create a variable | | `{% capture var %}...{% endcapture %}` | Capture block into variable | | `{% comment %}...{% endcomment %}` | Comment (not rendered) | ### Operators | Operator | Description | Example | | - | - | - | | `==` | Equals | `{% if status == "active" %}` | | `!=` | Not equals | `{% if type != "draft" %}` | | `>`, `<`, `>=`, `<=` | Comparison | `{% if count > 0 %}` | | `and` | Logical and | `{% if a and b %}` | | `or` | Logical or | `{% if a or b %}` | | `contains` | String/array contains | `{% if tags contains "saas" %}` | ### Loop Variables | Variable | Description | | - | - | | `forloop.index` | Current iteration (1-based) | | `forloop.index0` | Current iteration (0-based) | | `forloop.first` | True if first iteration | | `forloop.last` | True if last iteration | | `forloop.length` | Total iterations | ### String Filters | Filter | Example | Result | | - | - | - | | `upcase` | `{{ "hello" \| upcase }}` | `HELLO` | | `downcase` | `{{ "HELLO" \| downcase }}` | `hello` | | `capitalize` | `{{ "hello world" \| capitalize }}` | `Hello world` | | `strip` | `{{ " hi " \| strip }}` | `hi` | | `truncate: n` | `{{ "hello world" \| truncate: 5 }}` | `he...` | | `truncatewords: n` | `{{ "one two three" \| truncatewords: 2 }}` | `one two...` | | `replace: a, b` | `{{ "hello" \| replace: "l", "x" }}` | `hexxo` | | `remove: str` | `{{ "hello" \| remove: "l" }}` | `heo` | | `append: str` | `{{ "hello" \| append: "!" }}` | `hello!` | | `prepend: str` | `{{ "world" \| prepend: "hello " }}` | `hello world` | | `split: delim` | `{{ "a,b,c" \| split: "," }}` | `["a","b","c"]` | ### Array Filters | Filter | Example | Result | | - | - | - | | `join: delim` | `{{ arr \| join: ", " }}` | `a, b, c` | | `first` | `{{ arr \| first }}` | First element | | `last` | `{{ arr \| last }}` | Last element | | `size` | `{{ arr \| size }}` | Array length | | `reverse` | `{{ arr \| reverse }}` | Reversed array | | `sort` | `{{ arr \| sort }}` | Sorted array | | `uniq` | `{{ arr \| uniq }}` | Unique elements | | `map: prop` | `{{ users \| map: "name" }}` | Array of names | | `where: prop, val` | `{{ users \| where: "active", true }}` | Filtered array | ### Other Filters | Filter | Example | Result | | - | - | - | | `default: val` | `{{ x \| default: "none" }}` | `none` if x is nil/empty | | `date: format` | `{{ now \| date: "%Y-%m-%d" }}` | `2024-01-15` | | `json` | `{{ obj \| json }}` | JSON string | | `escape` | `{{ html \| escape }}` | HTML-escaped string (body variables are already protected during prompt parsing) | | `newline_to_br` | `{{ text \| newline_to_br }}` | `\n` → `
` | ### Number Filters | Filter | Example | Result | | - | - | - | | `plus: n` | `{{ 5 \| plus: 3 }}` | `8` | | `minus: n` | `{{ 5 \| minus: 3 }}` | `2` | | `times: n` | `{{ 5 \| times: 3 }}` | `15` | | `divided_by: n` | `{{ 10 \| divided_by: 3 }}` | `3` | | `modulo: n` | `{{ 10 \| modulo: 3 }}` | `1` | | `round` | `{{ 4.6 \| round }}` | `5` | | `ceil` | `{{ 4.2 \| ceil }}` | `5` | | `floor` | `{{ 4.8 \| floor }}` | `4` | # Claude Code Source: https://docs.output.ai/start-here/claude-code Output is the first programming framework designed for AI coding agents — and Claude Code is how you use it Output was designed for Claude Code from day one. We started with support for multiple coding assistants, then made a deliberate choice: ship only what we trust our own codebase with at GrowthX (we welcome community contributions for other assistants). Every workflow keeps its files together — `workflow.ts`, `steps.ts`, `types.ts`, prompts, scenarios, traces, cost data — no scattering across folders. Describe what you want in plain English, and Claude Code writes correct, idiomatic Output code. The plugin gives it deep knowledge of the framework's conventions, patterns, and common mistakes. ## Installing the Plugin When you create a new project with `npx @outputai/cli init`, the plugin is installed automatically. You're ready to go. To update it alongside your CLI: ```bash theme={null} npx output update --agents ``` If you ever need to install manually: ```bash theme={null} claude plugin marketplace add growthxai/output claude plugin install outputai@outputai ``` ## What the Plugin Gives Claude Code The Output plugin isn't a wrapper around a few CLI commands. It's a comprehensive system with **3 slash commands**, **5 specialized agents**, and **32 skills** that give Claude Code expert-level knowledge of the Output framework. When you start a Claude Code session in an Output project, the plugin loads automatically. It injects the full framework context — every convention, every pattern, every rule — so Claude Code understands Output from the first message. ### Slash Commands In practice, you rarely need to type these directly — Claude Code picks the right skill or command based on what you ask in plain English. But it's useful to know what's available so you understand what's happening under the hood. | Command | What it does | Example | | - | - | - | | `/output-plan-workflow` | Produces a detailed implementation plan before writing code. Covers workflow structure, step boundaries, prompt design, error handling, and testing strategy. Saves to `.outputai/plans/`. | `A workflow that researches a company and produces a sales brief` | | `/output-build-workflow` | Takes a plan and generates working code — `workflow.ts`, `steps.ts`, `types.ts`, prompts, evaluators, and test scenarios. Every file follows Output conventions. | `.outputai/plans/2026_03_19_company_research/PLAN.md` | | `/output-debug-workflow` | Checks infrastructure, pulls execution traces, identifies the failure, and suggests a fix. Systematic — no guessing. | `The company_research workflow is timing out on the scrape step` | ### Specialized Agents The plugin includes 5 expert agents that Claude Code delegates to automatically based on what you're asking. | Agent | Expertise | | - | - | | **Workflow Planner** | Designs workflow architecture, step boundaries, orchestration patterns | | **Workflow Quality** | Reviews code for framework compliance, catches common mistakes | | **Workflow Debugger** | Diagnoses execution failures using traces and error patterns | | **Prompt Writer** | Creates and reviews `.prompt` files — Liquid.js templates, YAML frontmatter, provider config | | **Context Fetcher** | Retrieves existing patterns from your project to ensure consistency | ### Skills Skills are the building blocks that power the commands and agents — 32 in total across five categories: * **Development** — Creates every file type in an Output project with correct patterns, imports, and conventions * **Workflow operations** — Run, start, check status, retrieve results, list workflows * **Monitoring and debugging** — Analyze traces, check service health, identify failure patterns * **Error diagnosis** — Six skills for the most common mistakes: wrong `zod` imports, non-determinism in workflows, try-catch swallowing retries, missing schemas, direct I/O in workflow functions, using `axios`/`fetch` instead of `@outputai/core/http` * **Credentials** — Initialize encrypted stores, edit secrets, wire to environment variables ## What Gets Enforced The plugin enforces Output's conventions so you don't accidentally create patterns that break in production: * Import `z` from `@outputai/core`, never from `zod` directly * All I/O goes in steps, never in workflow functions * Use `@outputai/core/http` for HTTP calls, not `axios` or `fetch` * Use `@outputai/core/llm` for LLM calls, not provider libraries directly * ES module imports always use `.js` extensions * Every step and workflow has input and output schemas * Prompt templates use Liquid.js syntax, not Handlebars * Don't wrap step calls in try-catch (it swallows the retry logic) These aren't arbitrary rules. Each one exists because we hit the bug in production at GrowthX and built the guardrail so you don't have to. ## Want to dive deeper? You can see all skills, agents, commands, and hooks [here in our repo](https://github.com/growthxai/output/tree/main/coding_assistants/claude/plugins/). ## What's Next > [card] [Learning Path](/start-here/learning-path) > > **Learning Path.** A structured guide through the rest of the documentation. > [card] [Workflows](/workflows) > > **Workflows.** Deep dive into workflow structure, patterns, and orchestration. # Getting Started Source: https://docs.output.ai/start-here/getting-started Create your first Output workflow in minutes ## TL;DR This is the quick and dirty way to get started – but be sure to read the full guide below. ```bash theme={null} # Install VS Code Claude Code extension (recommended) # https://marketplace.visualstudio.com/items?itemName=anthropics.claude-code # Create project npx @outputai/cli init cd # Add your Anthropic API key to .env # Start services npx output dev # Temporal UI: http://localhost:8080 # Run example workflow in a new terminal: npx output workflow run blog_evaluator paulgraham_hwh # Inspect the execution trace: npx output workflow debug ``` *** ## Getting Started: Step-by-step > [!NOTE] > > **How this tutorial works**: We'll use Claude Code throughout - Output is designed to work with Claude Code natively - we'll ask things in plain English, and Claude Code builds it. Along the way, we show the CLI commands running under the hood—so you understand both approaches, or you can just use the CLI directly if you prefer. ### Prerequisites Before starting, you'll need: * **Node.js 24.15.0+** — [Download here](https://nodejs.org/) * **Docker Desktop** — [Download here](https://www.docker.com/products/docker-desktop/) we'll need for running some of dependencies (PostgreSQL, Redis, Temporal) * **VS Code with Claude Code** — [Install extension](https://marketplace.visualstudio.com/items?itemName=anthropics.claude-code). You can use the CLI directly if you prefer or Claude Code outside of VS Code as well - your choice, but AI assisted is how we recommend you use Output. * **Anthropic API key** — [Get one here](https://console.anthropic.com/) ### Create Your Project Open your terminal and run: ```bash theme={null} npx @outputai/cli init ``` The CLI will prompt you. Enter these values: | Prompt | Enter | | - | - | | What is your project name? | `content-workflows` | | What folder name should be used? | Press Enter (uses default) | | What is your project description? | Press Enter (uses default) | | Would you like to configure environment variables now? | `Y` | | ANTHROPIC_API_KEY (secret): | Paste your Anthropic API key | | OPENAI_API_KEY (secret): | Press Enter to skip (or paste if you have one) | The CLI creates the project, configures your `.env`, and installs dependencies. Here's what you get: ``` content-workflows/ ├── config/ │ └── costs.yml # Pricing overrides (LLM and API services) ├── src/ │ ├── shared/ # Shared code across workflows │ │ ├── clients/ # API clients │ │ │ └── jina.ts # Jina Reader API client │ │ └── utils/ # Utility functions │ │ └── url.ts # URL validation │ └── workflows/ │ └── blog_evaluator/ # Example workflow │ ├── types.ts # Schema definitions │ ├── workflow.ts # Workflow orchestration │ ├── steps.ts # Step implementations │ ├── evaluators.ts # LLM evaluators │ ├── utils.ts # Workflow-specific utilities │ ├── prompts/ # LLM prompt files │ │ └── signal_noise@v1.prompt │ └── scenarios/ # Test inputs │ └── paulgraham_hwh.json ├── .env.example # Environment template └── package.json ``` ### Start Development Services Navigate into your project and start the dev environment: ```bash theme={null} cd content-workflows npx output dev ``` This starts the services needed for development (Temporal, Redis, PostgreSQL, worker). Keep this terminal running. > [!TIP] > > The first run downloads Docker images - this takes a few minutes. Subsequent starts are fast. ### Open VS Code with Claude Code Open a **new terminal** and launch VS Code: ```bash theme={null} cd content-workflows code . ``` Start a Claude Code session (Cmd+Shift+P → "Claude Code: Open"). From here on, we'll interact with Output through Claude Code. ### Run the Example Workflow Tell Claude Code: > "Run the blog_evaluator workflow with the test scenario" **Under the hood**, Claude Code runs: ```bash theme={null} npx output workflow run blog_evaluator paulgraham_hwh ``` You'll see output like: ```bash theme={null} Using scenario: src/workflows/blog_evaluator/scenarios/paulgraham_hwh.json Executing workflow: blog_evaluator... Workflow ID: blog_evaluator-22b798f9-4812-4f48-80b2-89fac07285ed Output: { "url": "https://paulgraham.com/hwh.html", "title": "How to Work Hard", "signalToNoiseScore": 82, "confidence": 0.85, "summary": "Signal-to-noise score: 82/100" } ``` For more ways to run workflows — async execution, inline JSON input, the HTTP API, and more — see [Running Workflows](/workflows/running) and the [API Reference](/api). ### Explore Execution via UI For execution, Output uses Temporal.io - a battle-tested workflow engine. You can use the Temporal UI at [http://localhost:8080](http://localhost:8080) to inspect your workflow runs. This is likely your first experience with Temporal. The UI can feel overwhelming at first - there's a lot of information. Don't worry about understanding everything now. The key thing to know: Temporal records every workflow execution, and this UI lets you inspect them. You'll see your workflow run listed. Click into it to see: * **Input**: The question you asked * **Output**: The LLM's answer * **Event History**: Every step that executed, with timing This is one way to monitor executions. Every step recorded, every retry visible, every failure debuggable—and you can replay any execution to debug issues. However, Output also records every run in a trace file (covered in the next section), and when using Claude Code for development, you'll rarely need to look at the Temporal UI. Claude Code can analyze traces and fix issues for you. ### Explore Execution Traces Output traces **every operation** - not just LLM calls, but HTTP requests, step executions, and timing data. This happens automatically with zero configuration. The quickest way to inspect a run is `output workflow debug` with the workflow ID from the previous step: ```bash theme={null} npx output workflow debug ``` This prints a tree showing every step that ran, what it received, what it returned, and how long it took: ``` Trace Log: ────────────────────────────────────────────────────────────────────────────── ┌─ [blog_evaluator] completed │ ├─ [fetch_blog_content] [END] 430ms │ │ ├─ input: {"url":"https://paulgraham.com/hwh.html"} │ │ └─ output: {"title":"How to Work Hard","content":"...","tokenCount":3241} │ └─ [evaluate_signal_to_noise] [END] 890ms │ ├─ input: {"title":"How to Work Hard","content":"..."} │ └─ output: {"score":82} ────────────────────────────────────────────────────────────────────────────── ``` Use `--format json` to get the full untruncated trace, including complete LLM inputs and outputs. Traces are also saved as JSON files in your project's `logs/runs/` directory — you can open them directly or share them with teammates: ```bash theme={null} ls logs/runs/blog_evaluator/ ``` **Why trace everything?** Your data should live close to your code and belong to you—not locked in a third-party dashboard. With traces, you can inspect every API call, understand costs by token count, extract scenarios for testing, and most importantly, use them as part of your iteration cycle with Claude Code. When something fails, ask Claude Code to analyze the trace and fix it. Traces can also be sent to S3 for production storage. See the [Tracing guide](/operations/tracing) for configuration. ### Understand the Code Let's look at what makes up a workflow. The `blog_evaluator` example demonstrates the key patterns: ```typescript workflow.ts theme={null} // src/workflows/blog_evaluator/workflow.ts import { workflow, z } from '@outputai/core'; import { validateUrl } from '../../shared/utils/url.js'; import { fetchContent } from './steps.js'; import { evaluateSignalToNoise } from './evaluators.js'; import { createWorkflowOutput } from './utils.js'; import { workflowInputSchema, workflowOutputSchema } from './types.js'; export default workflow({ name: 'blog_evaluator', description: 'Evaluate a blog post for signal-to-noise ratio', inputSchema: workflowInputSchema, outputSchema: workflowOutputSchema, fn: async (input) => { const validatedUrl = validateUrl(input.url); const blogContent = await fetchContent({ url: validatedUrl }); const evaluation = await evaluateSignalToNoise(blogContent); return createWorkflowOutput(blogContent, evaluation.value); }, options: { activityOptions: { retry: { maximumAttempts: 3 } } } }); ``` ```typescript steps.ts theme={null} // src/workflows/blog_evaluator/steps.ts import { step, z } from '@outputai/core'; import { fetchBlogContent } from '../../clients/jina.js'; export const fetchContent = step({ name: 'fetch_blog_content', description: 'Fetch blog content from URL using Jina Reader API', inputSchema: z.object({ url: z.string().url() }), outputSchema: z.object({ title: z.string(), url: z.string(), content: z.string(), tokenCount: z.number() }), fn: async ({ url }) => { const response = await fetchBlogContent(url); return { title: response.data.title, url: response.data.url, content: response.data.content, tokenCount: response.data.usage.tokens }; } }); ``` ```typescript evaluators.ts theme={null} // src/workflows/blog_evaluator/evaluators.ts import { evaluator, z, EvaluationNumberResult } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import type { BlogContent } from './types.js'; const blogContentSchema = z.object({ title: z.string(), url: z.string(), content: z.string(), tokenCount: z.number() }); export const evaluateSignalToNoise = evaluator({ name: 'evaluate_signal_to_noise', description: 'Evaluate the signal-to-noise ratio of blog content', inputSchema: blogContentSchema, fn: async (input: BlogContent) => { const { output } = await generateText({ prompt: 'signal_noise@v1', variables: { title: input.title, content: input.content }, output: aiSdk.Output.object({ schema: z.object({ score: z.number().min(0).max(100).describe('Signal-to-noise score 0-100') }) }) }); return new EvaluationNumberResult({ value: output.score, confidence: 0.85 }); } }); ``` ```yaml signal_noise@v1.prompt theme={null} --- provider: anthropic model: claude-haiku-4-5 temperature: 0.3 maxOutputTokens: 256 --- You are an expert content analyst. Evaluate blog posts for their signal-to-noise ratio. Analyze this blog post for signal-to-noise ratio. Title: {{ title }} Content: {{ content }} Score 0-100 where: - 0-20: Mostly filler/noise - 21-40: More noise than signal - 41-60: Balanced - 61-80: Good signal, minimal noise - 81-100: Exceptional, dense valuable content Return only the score. ``` **workflow\.ts** — The control flow. Decides what runs and in what order. Think of it as the conductor—it coordinates, but doesn't do the work itself. The `options.activityOptions.retry` configures automatic retries at the workflow level. (No I/O here—this matters later when we cover rewinding and replaying workflows.) **steps.ts** — The actual work. API calls, database queries—anything that talks to the outside world (aka I/O) goes here. If a step fails, Output retries it automatically. **evaluators.ts** — The quality assessment layer. Evaluators wrap LLM calls and return structured results with confidence scores. Use them when you need to assess or score content rather than transform it. The `EvaluationNumberResult` provides a standardized way to return numeric evaluations with confidence levels. **[signal_noise@v1.prompt](mailto:signal_noise@v1.prompt)** — The LLM prompt. Settings at the top (provider, model), then the actual prompt with variables like `{{ title }}` and `{{ content }}`. There's a powerful templating language under the hood (Liquid.js) that we'll cover in detail later. ### Building Something Real: Web Summarization The example workflow is a good "Hello World", but let's build something real: a workflow that scrapes a webpage and summarizes its content. Tell Claude Code: > "Delete the simple workflow and create a new workflow called 'summarize_url' that scrapes a webpage in markdown format and summarizes its content. At the end we want a structured output with the title, summary, and full page (markdown) content. For the scraping we'll need an API client for Jina ([https://jina.ai/](https://jina.ai/)) reader" **Under the hood**, Claude Code: ```bash theme={null} # Remove the example workflow rm -rf src/workflows/blog_evaluator/ # Create a plan from your description npx output workflow plan "summarize_url workflow that scrapes a webpage..." # Generate the workflow from the plan npx output workflow generate summarize_url --plan-file .outputai/plans/summarize_url.md ``` Here's what it generates: ```typescript workflow.ts theme={null} // src/workflows/summarize_url/workflow.ts import { workflow, z } from '@outputai/core'; import { scrapeUrl, summarizeContent } from './steps.js'; export default workflow({ name: 'summarize_url', description: 'Scrape a webpage and summarize its content', inputSchema: z.object({ url: z.string().url().describe('The URL to scrape and summarize') }), outputSchema: z.object({ title: z.string().describe('Page title'), summary: z.string().describe('Summary of the page content'), wordCount: z.number().describe('Word count of original content') }), fn: async input => { const { title, content } = await scrapeUrl(input.url); const summary = await summarizeContent(content); return { title, summary, wordCount: content.split(/\s+/).length }; } }); ``` ```typescript steps.ts theme={null} // src/workflows/summarize_url/steps.ts import { step, z } from '@outputai/core'; import { generateText } from '@outputai/core/llm'; import { jinaClient } from '../../clients/jina.js'; // src/clients/jina.ts export const scrapeUrl = step({ name: 'scrapeUrl', description: 'Fetch and extract content from a URL using Jina Reader', inputSchema: z.string().url(), outputSchema: z.object({ title: z.string(), content: z.string() }), fn: async url => { const markdown = await jinaClient.read(url); // Extract title from first heading or first line const titleMatch = markdown.match(/^#\s+(.+)$/m); const title = titleMatch ? titleMatch[1] : 'Untitled'; return { title, content: markdown }; } }); export const summarizeContent = step({ name: 'summarizeContent', description: 'Summarize text content using an LLM', inputSchema: z.string(), outputSchema: z.string(), fn: async content => { const truncated = content.slice(0, 10000); return generateText({ prompt: 'summarize@v1', variables: { content: truncated } }); } }); ``` ```typescript src/clients/jina.ts theme={null} // src/clients/jina.ts import { createKyClient } from '@outputai/core/http'; const client = createKyClient({ prefix: 'https://r.jina.ai', timeout: 30000 }); export const jinaClient = { /** * Convert a URL to clean markdown using Jina Reader */ read: async (url: string): Promise => { const response = await client.get(url); return response.text(); } }; ``` ```yaml summarize@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 temperature: 0.3 --- You are a concise summarizer. Create a clear, informative summary of the provided content. Focus on the main points and key takeaways. Keep the summary to 2-3 paragraphs. Summarize the following content: {{ content }} ``` ```json scenarios/test_url.json theme={null} { "url": "https://en.wikipedia.org/wiki/Ada_Lovelace" } ``` Notice the **API client pattern**: the Jina client lives in `src/clients/jina.ts`, separate from the workflow. It wraps `@outputai/core/http` which gives you automatic tracing and retries. When you need to integrate with other APIs (Stripe, Slack, your own backend), create similar clients in `src/clients/`. Now run it: > "Run the summarize_url workflow with the test scenario" **Under the hood**: ```bash theme={null} npx output workflow run summarize_url test_url ``` You'll see a structured summary of the Wikipedia page about Ada Lovelace. Open the execution interface at [http://localhost:8080](http://localhost:8080) to see both steps in the execution history: `scrapeUrl` followed by `summarizeContent`. Each step shows its input and output. You can also inspect the detailed trace in the `logs/runs/summarize_url/` folder. ### Adding Parallel Steps Let's make this more interesting. Tell Claude Code: > "Add a generateFaq step that creates 5 FAQs from the content. Run it in parallel with the summarization step." Here's what changes: ```typescript workflow.ts theme={null} // src/workflows/summarize_url/workflow.ts import { workflow, z } from '@outputai/core'; import { scrapeUrl, summarizeContent, generateFaq } from './steps.js'; export default workflow({ name: 'summarize_url', description: 'Scrape a webpage, summarize it, and generate FAQs', inputSchema: z.object({ url: z.string().url().describe('The URL to scrape and summarize') }), outputSchema: z.object({ title: z.string().describe('Page title'), summary: z.string().describe('Summary of the page content'), faqs: z.array(z.object({ question: z.string(), answer: z.string() })).describe('Frequently asked questions'), wordCount: z.number().describe('Word count of original content') }), fn: async input => { const { title, content } = await scrapeUrl(input.url); // Run summarization and FAQ generation in parallel const [summary, faqs] = await Promise.all([ summarizeContent(content), generateFaq(content) ]); return { title, summary, faqs, wordCount: content.split(/\s+/).length }; } }); ``` ```typescript steps.ts (add to existing) theme={null} export const generateFaq = step({ name: 'generateFaq', description: 'Generate FAQs from content using an LLM', inputSchema: z.string(), outputSchema: z.array(z.object({ question: z.string(), answer: z.string() })), fn: async content => { const truncated = content.slice(0, 10000); const { output } = await generateText({ prompt: 'generate_faq@v1', variables: { content: truncated }, output: aiSdk.Output.array({ element: z.object({ question: z.string(), answer: z.string() }) }) }); return output; } }); ``` ```yaml generate_faq@v1.prompt theme={null} --- provider: anthropic model: claude-sonnet-4-20250514 temperature: 0.3 --- You are a helpful assistant that generates frequently asked questions. Create 5 Q&A pairs based on the content. Questions should be what a reader would naturally ask. Answers should be concise and directly from the content. Generate 5 FAQs from this content: {{ content }} ``` Run it again and check the execution interface. You'll see `summarizeContent` and `generateFaq` running at the same time—parallel execution with just `Promise.all`. That's the power of steps: each is independently retryable, traceable, and can run concurrently when the workflow allows it. ### Next Steps You've built your first real Output workflow. Here's where to go next: > [card] [CLI Reference](/packages/cli) > > **CLI Reference.** All commands in depth—run, start, status, terminate, and more. > [card] [Workflows](/workflows) > > **Workflows.** Control flow, child workflows, scenarios, and advanced patterns. > [card] [Claude Code](/start-here/claude-code) > > **Claude Code.** How Output's Claude Code plugin plans, builds, and debugs workflows for you. # Learning Path Source: https://docs.output.ai/start-here/learning-path Recommended reading order for learning Output.ai Now that you've completed the [Getting Started](/start-here/getting-started) guide and read about [Claude Code](/start-here/claude-code), this is the recommended reading order. Each phase builds on the last — beginners can follow it straight through, experienced engineers can skip to what they need. ## Phase 1: Core Concepts Understand the building blocks: 1. **[Workflows](/workflows)** - Where you orchestrate the work 2. **[Steps](/steps)** - Where the actual work happens 3. **[Prompts](/prompts)** - How to manage your LLM interactions 4. **[Evaluators](/evaluators)** - Quality control for your AI outputs 5. **[API Clients](/clients)** - Call external APIs **Outcome:** You understand the architecture *** ## Phase 2: Building Real Workflows Best practices and patterns for building real workflows: 6. **[Step Best Practices](/steps/best-practices)** - Patterns & organization 7. **[Evaluator Best Practices](/evaluators/best-practices)** - LLM-as-judge patterns 8. **[Child Workflows](/workflows/child-workflows)** - Compose workflows by calling other workflows 9. **[Workflow Context](/workflows/context)** - Understand the execution context 10. **[Running Steps in Parallel](/workflows/parallel-execution)** - How to execute steps concurrently 11. **[Credentials](/packages/core/credentials)** - Manage secrets and API keys across environments **Outcome:** You can build complex, production-quality workflows *** ## Phase 3: Production Readiness Ship with confidence: 12. **[Error Handling](/operations/error-handling)** - Retries, failures, recovery 13. **[Error Hooks](/operations/error-hooks)** - React to failures with custom logic 14. **[Testing](/operations/testing)** - Testing deterministic and non-deterministic code 15. **[Tracing](/operations/tracing)** - Observability and debugging 16. **[Cost Estimation](/costs)** - Track and control your AI spend 17. **[Evaluation Workflow](/evaluators/workflow-evaluators)** - Test workflow quality across datasets **Outcome:** You're ready to deploy *** ## Phase 4: Integrate with Your App Connect Output to your product: 18. **[Integration Overview](/api)** - How your app talks to Output over HTTP 19. **[API Configuration](/api/configuration)** - Base URL, ports, environment variables 20. **[Authentication](/api/authentication)** - Dev vs production auth 21. **[Error Responses](/api/errors)** - Error codes and response handling **Outcome:** Your product can trigger and manage workflows via REST *** ## Reference (As Needed) * **[Packages](/packages/core)** - Package documentation * **[External Integration](/workflows/external-integration)** - Send data out, receive input while running * **[Prompt Templating](/prompts/templating)** - Advanced prompt patterns # Step Patterns & Best Practices Source: https://docs.output.ai/steps/best-practices Organize steps, extract utilities, share across workflows, and use evaluators for flow control As your workflow grows, you'll need patterns for keeping steps clean and organized. This guide covers how to structure step files, extract reusable logic, share steps across workflows, and use evaluators to control flow. ## Extracting Logic to utils.ts Steps are where most of your code lives. Sometimes they start to get complex — lots of data transformation, scoring logic, response parsing. When a step's `fn` gets hard to read, you can extract some of that logic into a `utils.ts` file. Here's a step that's a potential candidate for extraction: ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { lookupCompany as fetchFromClearbit } from '../../../clients/clearbit.js'; import { LookupCompanyInput, LookupCompanyOutput } from './types.js'; export const lookupCompany = step({ name: 'lookupCompany', description: 'Look up and normalize company data from Clearbit', inputSchema: LookupCompanyInput, outputSchema: LookupCompanyOutput, fn: async (domain) => { const raw = await fetchFromClearbit(domain); const name = raw.name?.trim() || raw.domain; const industry = raw.category?.industry || 'Unknown'; const size = raw.metrics?.employees || 0; const sizeCategory = size > 1000 ? 'enterprise' : size > 100 ? 'mid-market' : 'smb'; const techStack = (raw.tech || []) .filter((t) => t.category === 'analytics' || t.category === 'crm') .map((t) => t.name); return { name, industry, size, sizeCategory, techStack }; } }); ``` You can extract the transformation logic to a utility file: ```typescript utils.ts theme={null} export function normalizeCompanyData(raw) { const name = raw.name?.trim() || raw.domain; const industry = raw.category?.industry || 'Unknown'; const size = raw.metrics?.employees || 0; const sizeCategory = size > 1000 ? 'enterprise' : size > 100 ? 'mid-market' : 'smb'; const techStack = (raw.tech || []) .filter((t) => t.category === 'analytics' || t.category === 'crm') .map((t) => t.name); return { name, industry, size, sizeCategory, techStack }; } ``` ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { lookupCompany as fetchFromClearbit } from '../../../clients/clearbit.js'; import { normalizeCompanyData } from './utils.js'; import { LookupCompanyInput, LookupCompanyOutput } from './types.js'; export const lookupCompany = step({ name: 'lookupCompany', description: 'Look up and normalize company data from Clearbit', inputSchema: LookupCompanyInput, outputSchema: LookupCompanyOutput, fn: async (domain) => { const raw = await fetchFromClearbit(domain); return normalizeCompanyData(raw); } }); ``` The step is now two lines: fetch and transform. The transformation logic is testable on its own, reusable by other steps, and easy to understand at a glance. Good candidates for `utils.ts`: * Data transformation and normalization * Scoring algorithms and threshold checks * Prompt variable formatting * Response parsing and cleanup ## File Organization Most workflows use a single `steps.ts` file — you can put as many steps as you want in there, and that's perfectly fine. But sometimes a workflow has steps that naturally group around different concerns: some deal with data fetching, others with enrichment, others with notifications. When that happens, you can split them into a `steps/` folder with one file per group. **Single file** — the default for most workflows: ``` src/workflows/lead_enrichment/ ├── workflow.ts ├── steps.ts # All steps in one file ├── utils.ts # Shared helpers └── types.ts ``` **Folder-based** — when you want to group related steps into separate files: ``` src/workflows/lead_enrichment/ ├── workflow.ts ├── steps/ │ ├── data_fetching.ts # lookupCompany, searchNews │ ├── enrichment.ts # generateSummary, scoreLead │ └── notifications.ts # sendSlackAlert, updateCRM ├── utils.ts └── types.ts ``` Both patterns work — Output detects steps from either `steps.ts` or any file inside a `steps/` directory. The folder approach isn't about the number of steps; it's about organizing related steps together so they're easier to find and reason about. > [!NOTE] > > You can mix patterns across workflows in the same project. One workflow might use `steps.ts` while another uses `steps/`. Output handles both. ## Shared Steps When multiple workflows need the same step, put it in `src/shared/steps/`. This is common for things like CRM lookups, email verification, or enrichment calls that several workflows depend on. For example, looking up a contact in HubSpot is something both your lead enrichment and outreach workflows might need: ```typescript src/shared/steps/lookup_hubspot_contact.ts theme={null} import { step } from '@outputai/core'; import { getContact } from '../../clients/hubspot.js'; import { LookupContactInput, LookupContactOutput } from './types.js'; export const lookupHubspotContact = step({ name: 'lookupHubspotContact', description: 'Look up a contact in HubSpot by email', inputSchema: LookupContactInput, outputSchema: LookupContactOutput, fn: async (email) => { const contact = await getContact(email); return { exists: !!contact, contactId: contact?.id, lifecycleStage: contact?.properties?.lifecyclestage, owner: contact?.properties?.hubspot_owner_id }; } }); // types.ts // import { z } from '@outputai/core'; // // export const LookupContactInput = z.string(); // // export const LookupContactOutput = z.object({ // exists: z.boolean(), // contactId: z.string().optional(), // lifecycleStage: z.string().optional(), // owner: z.string().optional() // }); ``` Import shared steps in any workflow: ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { lookupHubspotContact } from '../../shared/steps/lookup_hubspot_contact.js'; import { enrichLead, generateSummary } from './steps.js'; import { LeadEnrichmentInput, LeadEnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', inputSchema: LeadEnrichmentInput, outputSchema: LeadEnrichmentOutput, fn: async (input) => { const contact = await lookupHubspotContact(input.email); const lead = await enrichLead(input.companyDomain); const summary = await generateSummary(lead); return { company: lead.name, summary, existsInCRM: contact.exists }; } }); // types.ts // import { z } from '@outputai/core'; // // export const LeadEnrichmentInput = z.object({ // email: z.string(), // companyDomain: z.string() // }); // // export const LeadEnrichmentOutput = z.object({ // company: z.string(), // summary: z.string(), // existsInCRM: z.boolean() // }); ``` If the shared logic is more than a single step — say it involves multiple steps in sequence with its own retry boundaries — you might want a [child workflow](/workflows/child-workflows) instead. But for a single reusable operation like a CRM lookup, a shared step is enough. > [!WARNING] > > Shared steps can only be imported by workflows, not by other steps. This enforces the activity isolation rule — steps can't call other steps. ## Evaluators for Flow Control Evaluators are a special type of step that score LLM output. They use the same `@outputai/core/llm` module and follow the same import rules as regular steps. What makes them powerful is using the score to control what happens next — retry if quality is low, skip a step if confidence is high, or branch to a different path. Here's an evaluator that judges the quality of an AI-generated company summary: ```typescript evaluators.ts theme={null} import { evaluator, EvaluationStringResult } from '@outputai/core'; import { generateText, aiSdk } from '@outputai/core/llm'; import { JudgeSummaryInput, JudgeSummaryOutput } from './types.js'; export const judgeSummaryQuality = evaluator({ name: 'judgeSummaryQuality', description: 'Score the quality of an AI-generated company summary', inputSchema: JudgeSummaryInput, outputSchema: JudgeSummaryOutput, fn: async (data) => { const { output } = await generateText({ prompt: 'judge_summary@v1', variables: { summary: data.output, companyName: data.input.name }, output: aiSdk.Output.object({ schema: JudgeSummaryOutput }) }); return new EvaluationStringResult({ value: output.feedback, confidence: output.score / 100 }); } }); // types.ts // import { z } from '@outputai/core'; // // export const JudgeSummaryInput = z.object({ // input: z.object({ name: z.string() }), // output: z.string() // }); // // export const JudgeSummaryOutput = z.object({ // score: z.number().min(0).max(100), // feedback: z.string() // }); ``` The real value shows up in workflows. Call an evaluator after an LLM step, check the score, and decide what to do next: ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { lookupCompany, generateSummary } from './steps.js'; import { judgeSummaryQuality } from './evaluators.js'; import { LeadEnrichmentInput, LeadEnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', inputSchema: LeadEnrichmentInput, outputSchema: LeadEnrichmentOutput, fn: async (input) => { const company = await lookupCompany(input.companyDomain); let summary; let attempts = 0; const maxAttempts = 3; while (attempts < maxAttempts) { summary = await generateSummary(company); const quality = await judgeSummaryQuality({ input: { name: company.name }, output: summary }); if (quality.confidence >= 0.7) break; attempts++; } return { company: company.name, summary }; } }); // types.ts // import { z } from '@outputai/core'; // // export const LeadEnrichmentInput = z.object({ // companyDomain: z.string() // }); // // export const LeadEnrichmentOutput = z.object({ // company: z.string(), // summary: z.string() // }); ``` This pattern — generate, evaluate, retry if needed — is the core of LLM-as-a-judge. The evaluator gives your workflow a way to check its own work and improve automatically. See the [Evaluators guide](/evaluators) for the full API, evaluation result types, and shared evaluator patterns. # The steps.ts File Source: https://docs.output.ai/steps/index Reusable units of work that handle I/O operations Workflows orchestrate, but they can't do any real work themselves — no API calls, no database queries, no LLM requests. That's by design. Output replays workflow code to recover from failures, so if you made an API call directly in a workflow, it could run twice. Steps are the boundary: they run once, their results are cached, and if something fails, only the failed step retries. ## Basic Step Here's a step that looks up a company using an external API: ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { lookupCompany as fetchFromClearbit } from '../../../clients/clearbit.js'; import { LookupCompanyInput, LookupCompanyOutput } from './types.js'; export const lookupCompany = step({ name: 'lookupCompany', description: 'Look up company data from Clearbit', inputSchema: LookupCompanyInput, outputSchema: LookupCompanyOutput, fn: async (domain) => { const company = await fetchFromClearbit(domain); return { name: company.name, industry: company.industry, size: company.employees }; } }); // types.ts // import { z } from '@outputai/core'; // // export const LookupCompanyInput = z.string(); // // export const LookupCompanyOutput = z.object({ // name: z.string(), // industry: z.string(), // size: z.number() // }); ``` Steps are called from workflows like regular async functions — `await lookupCompany('acme.com')`. The workflow decides *when* to call each step; the step does the actual work. ## Step Properties | Property | Type | Description | | - | - | - | | `name` | `string` | Unique identifier for the step | | `description` | `string` | Human-readable description | | `inputSchema` | `ZodSchema` | Zod schema for input; values are **parsed** before `fn` runs | | `outputSchema` | `ZodSchema` | Zod schema for output; values are **parsed** before returning to callers | | `options` | `object` | Optional workflow options (see [Options](#options)) | | `fn` | `function` | The step implementation | Step names must start with a letter or underscore, followed by letters, numbers, or underscores. Hyphens, spaces, dots, and other punctuation are not allowed. > [!NOTE] > > Schemas parse step values; they do not only validate them. The step `fn` receives the value returned by `inputSchema`, and the caller receives the value returned by `outputSchema`. Zod transforms, coercions, defaults, and object-key stripping therefore apply at runtime. If you feed a step's parsed output back into the same (or another) schema as input, transforms run again — keep them idempotent or pass wire-format values when that round-trip matters. ## Steps vs Workflows > [card] Workflows > > **Workflows:** > > * Orchestrate steps in sequence or parallel > * Must be deterministic (no I/O) > * Replayed on failure to recover state > [card] Steps > > **Steps:** > > * Where I/O happens: APIs, databases, LLMs > * Results cached — won't re-run on replay > * Automatically retried on failure The rule is simple: if it talks to something external, it goes in a step. ## Calling an LLM Steps are where you make LLM calls using `@outputai/core/llm`. The prompt file handles the model configuration; the step handles the orchestration: ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { generateText } from '@outputai/core/llm'; import { GenerateSummaryInput, GenerateSummaryOutput } from './types.js'; export const generateSummary = step({ name: 'generateSummary', description: 'Generate an AI summary of company data', inputSchema: GenerateSummaryInput, outputSchema: GenerateSummaryOutput, fn: async (input) => { const { result } = await generateText({ prompt: 'summarize_company@v1', variables: { companyName: input.name, industry: input.industry, size: input.size } }); return result; } }); // types.ts // import { z } from '@outputai/core'; // // export const GenerateSummaryInput = z.object({ // name: z.string(), // industry: z.string(), // size: z.number() // }); // // export const GenerateSummaryOutput = z.string(); ``` The `prompt` references a `.prompt` file in your workflow's `prompts/` directory. See [Writing Prompt Files](/prompts) for how to create them. ## Options Steps accept an optional `options` property to configure retry behavior and timeouts. Use `options.activityOptions` for Temporal activity options. Options set on a workflow apply to all its steps; a step can override them with its own `options.activityOptions`: ```typescript steps.ts theme={null} import { step } from '@outputai/core'; import { searchNews as fetchFromTavily } from '../../../clients/tavily.js'; import { SearchNewsInput, SearchNewsOutput } from './types.js'; export const searchNews = step({ name: 'searchNews', description: 'Search for recent news about a company', inputSchema: SearchNewsInput, outputSchema: SearchNewsOutput, options: { activityOptions: { retry: { maximumAttempts: 5, initialInterval: '1s', backoffCoefficient: 2 } } }, fn: async (query) => { const articles = await fetchFromTavily(query); return articles; } }); // types.ts // import { z } from '@outputai/core'; // // export const SearchNewsInput = z.string(); // // export const SearchNewsOutput = z.array(z.object({ // title: z.string(), // url: z.string(), // snippet: z.string() // })); ``` For the full list of supported options and default values, see [Activity Options](/workflows#activity-options) in the Workflows guide. Evaluators use the same options. ## Import Rules > [!WARNING] > > Steps are isolated execution units. A step cannot call another step or an evaluator — only workflows can do that. **Steps can import:** * [Clients](/clients) from `src/clients/` * Type definitions, constants, helpers, utilities * Any file that is not a component file (steps, evaluators, or workflow) **Steps cannot import:** * Other steps (activity calling activity) * Evaluators (they are also activities) * Workflow files This isolation exists because of how Temporal executes activities. Each step runs independently, and Temporal needs to be able to retry or replay any step without side effects from other steps. ## What's Next * [Step Patterns & Best Practices](/steps/best-practices) — Extract utilities, organize step files, share steps across workflows, and use evaluators for flow control * [Evaluators](/evaluators) — Score LLM output and control workflow flow with LLM-as-a-judge # Composing with Child Workflows Source: https://docs.output.ai/workflows/child-workflows Compose workflows by invoking other workflows As your system grows, you'll have workflows that make sense as standalone units — a notification sender, a company enrichment pipeline, a report generator. Child workflows let you call one workflow from another, giving each its own execution context and retry boundaries. This is an abstraction of Temporal's [child workflow execution](https://docs.temporal.io/develop/typescript/child-workflows) concept. ## Basic Usage Import a workflow and call it like a regular async function: ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import enrichCompanyWorkflow from '../enrich_company/workflow.js'; import { LeadPipelineInput, LeadPipelineOutput } from './types.js'; export default workflow({ name: 'lead_pipeline', description: 'Full lead enrichment pipeline', inputSchema: LeadPipelineInput, outputSchema: LeadPipelineOutput, fn: async (input) => { const enriched = await enrichCompanyWorkflow({ domain: input.companyDomain }); return enriched; } }); // types.ts // import { z } from '@outputai/core'; // // export const LeadPipelineInput = z.object({ // companyDomain: z.string() // }); // // export const LeadPipelineOutput = z.object({ // name: z.string(), // summary: z.string() // }); ``` The child workflow runs with its own retry boundaries — if `enrich_company` fails and retries, it doesn't affect the parent's execution history. > [!NOTE] > > Calling the workflow as a function is the supported way to run a child workflow. You can also start one with `executeChild` or `startChild` from `@temporalio/workflow`, but those children won't be included in the trace file and won't inherit the parent's search attributes. ## Invocation Patterns ```typescript theme={null} // With input const result = await enrichCompanyWorkflow({ domain: 'acme.com' }); // With input and activity options const result = await enrichCompanyWorkflow( { domain: 'acme.com' }, { activityOptions: { retry: { maximumAttempts: 1 } } } ); // Without input but with activity options (pass undefined as first argument) const result = await generateReportWorkflow( undefined, { activityOptions: { retry: { maximumAttempts: 99 } } } ); // Without input and without options const result = await generateReportWorkflow(); ``` ## Configuration Options The second argument to a child workflow invocation is a configuration object: | Option | Type | Description | | - | - | - | | `activityOptions` | `TemporalActivityOptions` | Override activity options for all steps in the child workflow. These are merged with the parent workflow's current activity options and the child workflow's own defaults. See [Activity Options](https://typescript.temporal.io/api/interfaces/common.ActivityOptions) for available options. | | `detached` | `boolean` | If `true`, the child workflow uses `ParentClosePolicy.ABANDON` instead of `TERMINATE`. See [Lifecycle](#lifecycle) below. | | `context` | `DeepPartial` | Override workflow context values in test environments. This is mainly useful for unit tests. | ### Activity Options Override Options set on a child workflow invocation apply to all steps within that child workflow branch. Steps can still override these with their own `options.activityOptions` property. ```typescript theme={null} // All steps in enrich_company will use maximumAttempts: 1 await enrichCompanyWorkflow( { domain: input.companyDomain }, { activityOptions: { retry: { maximumAttempts: 1 } } } ); ``` Activity options are merged from broad defaults to specific overrides: 1. Output's default activity options 2. The child workflow's `options.activityOptions` 3. Activity options inherited from the parent workflow 4. The `activityOptions` passed to this child workflow invocation 5. The called step's own `options.activityOptions` This lets a parent tune a child workflow branch for the current use case, while step-specific options still protect activities that need stricter behavior, such as activities that should not retry. ## Lifecycle When you call a child workflow, you have three choices: wait for it, fire it off and forget about it, or start it without waiting but let it die if the parent dies. Here's the breakdown: | Pattern | Code | Parent Waits? | Child Survives Parent Termination? | | - | - | - | - | | **Attached (awaited)** | `await enrichCompanyWorkflow(input)` | Yes | No | | **Detached (fire-and-forget)** | `sendNotificationWorkflow(input, { detached: true })` | No | Yes | | **Not awaited (attached)** | `enrichCompanyWorkflow(input)` | No | No | ### Attached (Awaited) The parent waits for the child to finish before continuing. If the parent is terminated, the child is terminated too: ```typescript theme={null} const enriched = await enrichCompanyWorkflow({ domain: input.companyDomain }); // Parent continues only after enrichment completes ``` > [!NOTE] > > When using `await`, the `detached` flag has no effect since the parent waits for the child to complete. ### Detached (Fire-and-Forget) The parent doesn't wait, and the child keeps running even if the parent terminates. Use this for things like sending notifications or logging — work that should finish regardless of what happens to the parent: ```typescript theme={null} sendNotificationWorkflow( { recipientEmail: lead.email, message: 'Your report is ready' }, { detached: true } ); // Parent continues immediately, notification sends in the background ``` ### Not Awaited (Attached) The parent doesn't wait, but the child is terminated if the parent terminates. Use this when you want to kick off work in parallel but don't need the result: ```typescript theme={null} enrichCompanyWorkflow({ domain: input.companyDomain }); // Parent continues immediately // But if parent terminates, enrichment is cancelled ``` ## When to Use Child Workflows **Use child workflows when:** * You have a reusable pipeline called from multiple places (e.g. `enrich_company` called from both `lead_pipeline` and `account_research`) * You want independent retry boundaries — a failing child doesn't blow up the parent's execution history * A sub-task should outlive the parent (detached mode for notifications, webhooks) * You're organizing a large system into smaller, independently testable units **Don't use child workflows when:** * You just need to reuse a step — import the step directly * The logic is tightly coupled to the parent and doesn't make sense on its own ## Examples ### Parallel Child Workflows Enrich multiple companies at once by running child workflows in parallel: ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import enrichCompanyWorkflow from '../enrich_company/workflow.js'; import { BatchEnrichmentInput, BatchEnrichmentOutput } from './types.js'; export default workflow({ name: 'batch_enrichment', description: 'Enrich multiple companies in parallel', inputSchema: BatchEnrichmentInput, outputSchema: BatchEnrichmentOutput, fn: async (input) => { const results = await Promise.all( input.domains.map(domain => enrichCompanyWorkflow({ domain }) ) ); return { results }; } }); // types.ts // import { z } from '@outputai/core'; // // export const BatchEnrichmentInput = z.object({ // domains: z.array(z.string()) // }); // // export const BatchEnrichmentOutput = z.object({ // results: z.array(z.object({ name: z.string(), summary: z.string() })) // }); ``` ### Fire-and-Forget Notification Process an order and send a notification without blocking: ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import sendNotificationWorkflow from '../send_notification/workflow.js'; import { processOrder } from './steps.js'; import { OrderInput, OrderOutput } from './types.js'; export default workflow({ name: 'order_pipeline', description: 'Process order and notify customer', inputSchema: OrderInput, outputSchema: OrderOutput, fn: async (input) => { const order = await processOrder(input.orderId); // Notification sends in the background — doesn't block the return sendNotificationWorkflow( { email: input.customerEmail, message: `Order ${input.orderId}: ${order.status}` }, { detached: true } ); return { orderId: input.orderId, status: order.status }; } }); // types.ts // import { z } from '@outputai/core'; // // export const OrderInput = z.object({ // orderId: z.string(), // customerEmail: z.string() // }); // // export const OrderOutput = z.object({ // orderId: z.string(), // status: z.string() // }); ``` # Execution Context Source: https://docs.output.ai/workflows/context Access workflow execution information and control flow Sometimes your workflow needs to know about itself — its execution ID for logging, or whether it's been running long enough that it should checkpoint and start fresh. The `context` object gives you this. It's the second argument to your workflow's `fn`, and it's always there whether you use it or not. ## Basic Usage ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { lookupCompany, generateSummary } from './steps.js'; import { LeadEnrichmentInput, LeadEnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', description: 'Enrich a sales lead with company data and AI summary', inputSchema: LeadEnrichmentInput, outputSchema: LeadEnrichmentOutput, fn: async (input, context) => { const company = await lookupCompany(input.companyDomain); const summary = await generateSummary(company); return { company: company.name, summary, workflowId: context.info.workflowId }; } }); // types.ts // import { z } from '@outputai/core'; // // export const LeadEnrichmentInput = z.object({ // companyDomain: z.string() // }); // // export const LeadEnrichmentOutput = z.object({ // company: z.string(), // summary: z.string(), // workflowId: z.string() // }); ``` The `context` is always the second argument, even if your workflow has no `inputSchema`. In that case, use `_input` to signal you're ignoring it: `fn: async (_input, context) => { ... }`. ## Context Structure | Namespace | Description | | - | - | | `context.control` | Functions to control workflow execution flow | | `context.info` | Information about the current workflow execution | ## Workflow Information ### `context.info.workflowId` The unique Temporal workflow ID for this execution. Include it in your output when you need to correlate results with external systems, track executions in logs, or pass a reference to another service. See the [Temporal workflow ID documentation](https://docs.temporal.io/workflow-execution/workflowid-runid#workflow-id) for more details. ## Control Functions ### `continueAsNew()` Every step your workflow executes adds to its execution history. For short workflows this doesn't matter, but if you're looping over thousands of leads or running a long-lived polling workflow, that history grows. `continueAsNew` checkpoints the current state and starts a fresh execution — same workflow, clean history. The new execution is in the same chain as the previous one but generates a separate trace file. See [Tracing — continue-as-new](/operations/tracing#continue-as-new) for how traces are correlated across runs. `continueAsNew` must be the last thing your workflow does — call it with `return`: ```typescript theme={null} fn: async (input, context) => { const result = await enrichLead(input.companyDomain); if (result.needsMoreData) { // Checkpoint and restart with updated input return context.control.continueAsNew({ companyDomain: input.companyDomain, attempt: (input.attempt ?? 0) + 1 }); } return { company: result.name, summary: result.summary }; } ``` If your workflow has an `inputSchema`, pass the input object for the new execution. If it has no `inputSchema`, call without arguments: `context.control.continueAsNew()`. The new run parses that payload with `inputSchema` like any other workflow start — there is no “already parsed” shortcut. Pass wire-format input (what you would pass when starting the workflow), especially if `inputSchema` uses `.transform()` or other helpers that are not safe to apply twice. The function's return type matches your `outputSchema` for type-checking, but it never actually returns — the execution is replaced. See the [Temporal continue-as-new documentation](https://docs.temporal.io/develop/typescript/continue-as-new) for more details. ### `isContinueAsNewSuggested()` Rather than guessing when to checkpoint, ask Temporal. This returns `true` when the runtime thinks your history is getting large enough that you should continue as new. Check it at loop boundaries: ```typescript theme={null} fn: async (input, context) => { const remainingLeads = [...input.leads]; while (remainingLeads.length > 0) { const lead = remainingLeads.shift(); await enrichLead(lead); if (context.control.isContinueAsNewSuggested()) { return context.control.continueAsNew({ leads: remainingLeads }); } } return { completed: true }; } ``` See the [Temporal continue-as-new testing guide](https://docs.temporal.io/develop/typescript/continue-as-new#how-to-test) for more details. ## Full Example A workflow that processes a large batch of leads, checkpointing when Temporal suggests it: ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { enrichLead } from './steps.js'; import { BatchEnrichmentInput, BatchEnrichmentOutput } from './types.js'; export default workflow({ name: 'batch_enrichment', description: 'Enrich leads in batches with automatic checkpointing', inputSchema: BatchEnrichmentInput, outputSchema: BatchEnrichmentOutput, fn: async (input, context) => { const remaining = [...input.leads]; let enriched = input.enrichedCount; while (remaining.length > 0) { const lead = remaining.shift(); await enrichLead(lead); enriched++; if (context.control.isContinueAsNewSuggested()) { return context.control.continueAsNew({ leads: remaining, enrichedCount: enriched }); } } return { totalEnriched: enriched }; } }); // types.ts // import { z } from '@outputai/core'; // // export const BatchEnrichmentInput = z.object({ // leads: z.array(z.object({ // domain: z.string(), // name: z.string() // })), // enrichedCount: z.number().default(0) // }); // // export const BatchEnrichmentOutput = z.object({ // totalEnriched: z.number() // }); ``` # External Integration Source: https://docs.output.ai/workflows/external-integration Send data out, receive input, and query status while workflows run Your workflow doesn't run in isolation. It needs to notify your dashboard when a step completes, wait for a human to approve a document, let a monitoring service check progress, or accept configuration changes mid-run. Output gives you primitives for both directions: sending data out and receiving data in. ## Quick Reference | I need to... | Use | Direction | | - | - | - | | Notify a service or call a webhook | `sendHttpRequest` | Out | | Send a request, pause until callback | `sendPostRequestAndAwaitWebhook` | Out, then In | | Let external systems push data in | Signal | In | | Let a dashboard read current state | Query | In | | Accept a change and confirm it worked | Update | In | ## Sending Data Out ### Post a Notification The simplest integration: call an external API when something happens. Use `sendHttpRequest` to POST to a webhook — notify any HTTP-based service, kick off a Zapier automation, etc. ```typescript theme={null} // src/workflows/content_pipeline/workflow.ts import { workflow, sendHttpRequest } from '@outputai/core'; import { research, draft, review } from './steps.js'; export default workflow({ name: 'content_pipeline', description: 'Research, draft, and review content with progress notifications', fn: async (input) => { const researchResults = await research(input.topic); // Notify your dashboard or monitoring service await sendHttpRequest({ url: `${process.env.INTERNAL_API_URL}/events`, method: 'POST', payload: { event: 'step_complete', workflow: 'content_pipeline', step: 'research', data: { topic: input.topic } } }); const content = await draft({ topic: input.topic, research: researchResults }); await sendHttpRequest({ url: `${process.env.INTERNAL_API_URL}/events`, method: 'POST', payload: { event: 'step_complete', workflow: 'content_pipeline', step: 'draft', data: { title: content.title } } }); const reviewed = await review(content); return reviewed; } }); ``` Each `sendHttpRequest` fires and continues — the workflow doesn't wait for a response beyond the HTTP acknowledgment. ### Parameters | Parameter | Type | Description | | - | - | - | | `url` | `string` | The request URL (required) | | `method` | `'GET' \| 'POST' \| 'PUT' \| 'DELETE' \| 'PATCH'` | HTTP method (default: `GET`) | | `payload` | `object` | Request body for POST/PUT (optional) | | `headers` | `Record` | HTTP headers (optional). Use `$ENV_VAR_NAME` placeholders for secret values. | | `responseOptions.includeHeaders` | `boolean` | Include response headers in the returned value. Headers are redacted when included. Default: `false`. | | `responseOptions.includeBody` | `boolean` | Include the response body in the returned value. Default: `false`. | By default, the response includes only `url`, `status`, `statusText`, and `ok`. Response headers and body are opt-in because activity inputs and outputs are stored in workflow history and can appear in trace files. ### Headers and Secrets Workflows should not read secret values directly. If a header needs a token, pass an environment variable placeholder and the activity worker replaces it immediately before sending the request: ```typescript theme={null} await sendHttpRequest({ url: 'https://api.example.com/events', method: 'POST', headers: { Authorization: 'Bearer $API_TOKEN', 'Content-Type': 'application/json' }, payload: { event: 'step_complete' } }); ``` The workflow history and trace files store `Bearer $API_TOKEN`, not the resolved token. The worker reads `process.env.API_TOKEN` at activity execution time. If the environment variable is missing, the request fails before it is sent. > [!WARNING] > > `sendHttpRequest` and `sendPostRequestAndAwaitWebhook` are not primarily designed for secure or sensitive HTTP exchanges. Misconfigured requests can leak keys, tokens, cookies, signed URLs, payload data, or response bodies into Temporal history and trace files. Use `$ENV_VAR_NAME` placeholders for request header secrets, avoid secrets in URLs and payloads, and only opt into response bodies when they are safe to persist. ### Signed Webhooks When sending data out, it's common practice for the receiving end to require a shared secret that is signed. Here's an example for how to sign a webhook payload using HMAC-SHA256: > [!NOTE] > > Signing must happen in a **step**, not directly in the workflow. Cryptographic operations like `crypto.createHmac` are non-deterministic and must run inside a step. ```typescript theme={null} // src/workflows/signed_webhook/steps.ts import { step, z } from '@outputai/core'; import crypto from 'crypto'; export const sendSignedWebhook = step({ name: 'sendSignedWebhook', description: 'Send a webhook with HMAC signature', inputSchema: z.object({ url: z.string(), payload: z.record(z.unknown()) }), outputSchema: z.object({ status: z.number() }), fn: async ({ url, payload }) => { const secret = process.env.WEBHOOK_SECRET; const body = JSON.stringify(payload); const signature = crypto .createHmac('sha256', secret) .update(body) .digest('hex'); const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Signature': signature }, body }); return { status: response.status }; } }); ``` ```typescript theme={null} // src/workflows/signed_webhook/workflow.ts import { workflow } from '@outputai/core'; import { sendSignedWebhook } from './steps.js'; export default workflow({ name: 'order_complete', fn: async (input) => { // ... process order ... await sendSignedWebhook({ url: 'https://partner-api.example.com/webhooks', payload: { event: 'order_complete', orderId: input.orderId, total: input.total } }); return { success: true }; } }); ``` The receiver verifies by computing the same HMAC and comparing signatures. ## Receiving Data In Sometimes your workflow needs input from the outside world while it's running. A human approves a document. A dashboard checks progress. An operator changes a setting. Output exposes three primitives for this, built on [Temporal's message passing](https://docs.temporal.io/develop/typescript/message-passing). | Primitive | Blocks caller? | Can change state? | Returns value? | Use when... | | - | - | - | - | - | | **Signal** | No | Yes | No | Fire-and-forget input (stop, add data) | | **Query** | Yes | No | Yes | Read current state (progress, status) | | **Update** | Yes | Yes | Yes | Change state and confirm (set threshold) | ### Query: Read State Without Changing It A **query** lets external systems read workflow state. The workflow keeps running — queries are read-only and don't affect execution. > [!NOTE] > > **Why two imports?** Output wraps Temporal for workflow orchestration. High-level helpers like `workflow` and `sendHttpRequest` come from `@outputai/core`. Low-level primitives like `defineQuery`, `defineSignal`, and `setHandler` come directly from `@temporalio/workflow` — Output doesn't wrap these since Temporal's API is already clean. **Job:** Your dashboard needs to show which step the workflow is on. ```typescript theme={null} // src/workflows/content_pipeline/workflow.ts import { workflow } from '@outputai/core'; import { defineQuery, setHandler } from '@temporalio/workflow'; import { research, draft, review } from './steps.js'; // defineQuery('name') - the generic specifies what the query returns const getProgress = defineQuery<{ step: string; completed: number; total: number }>('getProgress'); export default workflow({ name: 'content_pipeline', description: 'Content pipeline with progress query', fn: async (input) => { let currentStep = 'research'; let completedSteps = 0; const totalSteps = 3; setHandler(getProgress, () => ({ step: currentStep, completed: completedSteps, total: totalSteps })); const researchResults = await research(input.topic); completedSteps = 1; currentStep = 'draft'; const content = await draft({ topic: input.topic, research: researchResults }); completedSteps = 2; currentStep = 'review'; const reviewed = await review(content); completedSteps = 3; currentStep = 'done'; return reviewed; } }); ``` Query the workflow via HTTP: ```bash theme={null} curl -X POST http://localhost:3001/workflow/content_pipeline-abc123/query/getProgress \ -H "Content-Type: application/json" ``` Response: ```json theme={null} { "step": "draft", "completed": 1, "total": 3 } ``` Your dashboard can poll this endpoint to show a progress bar — no webhooks needed. > [!TIP] > > **About the `payload` wrapper**: When sending data to signals, queries, or updates, wrap your data in `{ "payload": {...} }`. The API extracts `payload` and passes it to your handler. For queries with no arguments, send an empty object: `{ "payload": {} }` or omit the body entirely. ### Query with Arguments Queries can accept arguments from the caller. Use this to filter results, control verbosity, or request specific data. **Job:** An agent makes multiple tool calls per step. The dashboard wants to show either a summary or detailed tool call history. ```typescript theme={null} // Define query with input arguments: defineQuery const getProgress = defineQuery< ProgressResult, [{ verbose?: boolean; toolCallId?: string }] >('getProgress'); // In your workflow interface ToolCall { id: string; tool: string; input: unknown; output: unknown; timestamp: number; } const toolCalls: ToolCall[] = []; let currentStep = 'planning'; setHandler(getProgress, (args) => { // Return specific tool call if requested if (args.toolCallId) { const call = toolCalls.find(t => t.id === args.toolCallId); return { toolCall: call ?? null }; } // Return full history or summary if (args.verbose) { return { currentStep, toolCalls, totalCalls: toolCalls.length }; } return { currentStep, totalCalls: toolCalls.length }; }); // During execution, record each tool call const searchResult = await webSearch({ query: 'AI safety' }); toolCalls.push({ id: `tc-${toolCalls.length + 1}`, tool: 'web_search', input: { query: 'AI safety' }, output: searchResult, timestamp: Date.now() }); ``` Query with arguments: ```bash theme={null} # Summary view curl -X POST http://localhost:3001/workflow/agent-abc123/query/getProgress \ -H "Content-Type: application/json" \ -d '{ "payload": {} }' # { "currentStep": "research", "totalCalls": 5 } # Detailed view curl -X POST http://localhost:3001/workflow/agent-abc123/query/getProgress \ -H "Content-Type: application/json" \ -d '{ "payload": { "verbose": true } }' # { "currentStep": "research", "totalCalls": 5, "toolCalls": [...] } # Specific tool call curl -X POST http://localhost:3001/workflow/agent-abc123/query/getProgress \ -H "Content-Type: application/json" \ -d '{ "payload": { "toolCallId": "tc-3" } }' # { "toolCall": { "id": "tc-3", "tool": "web_search", ... } } ``` ### Signal: Push Data In A **signal** pushes data into a running workflow. The caller doesn't wait for processing — the API returns immediately. Use signals for fire-and-forget input like "stop processing" or "here's new data." **Job:** An operator wants to stop a long-running research workflow early. ```typescript theme={null} // src/workflows/iterative_research/workflow.ts import { workflow } from '@outputai/core'; import { defineSignal, setHandler, condition } from '@temporalio/workflow'; import { executeResearch, validateQuality } from './steps.js'; const stopSignal = defineSignal('stop'); export default workflow({ name: 'iterative_research', description: 'Research with early stop capability', fn: async (input) => { let shouldStop = false; let results = []; setHandler(stopSignal, () => { shouldStop = true; }); for (let iteration = 1; iteration <= 3; iteration++) { const iterationResults = await executeResearch({ topic: input.topic, iteration }); results.push(...iterationResults); const quality = await validateQuality(results); // Check if operator sent stop signal if (shouldStop) { break; } // Also stop if quality is good enough if (quality.score >= 0.8) { break; } } return { results, iterations: results.length }; } }); ``` Send the stop signal: ```bash theme={null} curl -X POST http://localhost:3001/workflow/iterative_research-abc123/signal/stop ``` The workflow checks `shouldStop` between iterations and exits early. The operator gets `200 OK` immediately — they don't wait for the workflow to actually stop. ### Update: Change State and Get Confirmation An **update** changes workflow state and returns a result. The caller blocks until the workflow processes the update. Use updates when you need confirmation that a change was applied. **Job:** An admin wants to change the quality threshold mid-workflow and see the previous value. ```typescript theme={null} // src/workflows/iterative_research/workflow.ts import { workflow } from '@outputai/core'; import { defineUpdate, setHandler } from '@temporalio/workflow'; import { executeResearch, validateQuality } from './steps.js'; const setThreshold = defineUpdate('setThreshold'); export default workflow({ name: 'iterative_research', description: 'Research with adjustable quality threshold', fn: async (input) => { let qualityThreshold = 0.8; setHandler(setThreshold, (params) => { const previous = qualityThreshold; qualityThreshold = params.threshold; return previous; // Caller receives this }); // ... research iterations using qualityThreshold ... } }); ``` Send the update: ```bash theme={null} curl -X POST http://localhost:3001/workflow/iterative_research-abc123/update/setThreshold \ -H "Content-Type: application/json" \ -d '{ "payload": { "threshold": 0.9 } }' ``` Response: ```json theme={null} 0.8 ``` The admin sees the previous threshold (0.8) and knows their change was applied. ## Waiting for External Input Two patterns for pausing a workflow until the outside world responds. ### Pattern 1: Workflow Initiates the Request Use `sendPostRequestAndAwaitWebhook` when your workflow knows who to ask and wants to pause until they respond. **Job:** Send a document for human approval, pause until they decide. ```typescript theme={null} // src/workflows/document_approval/workflow.ts import { workflow, sendPostRequestAndAwaitWebhook } from '@outputai/core'; import { generateDocument } from './steps.js'; export default workflow({ name: 'document_approval', description: 'Generate document and wait for human approval', fn: async (input) => { const document = await generateDocument(input); // Workflow pauses here until approval service calls back const approval = await sendPostRequestAndAwaitWebhook({ url: 'https://approval-service.example.com/request', payload: { documentId: document.id, title: document.title } }) as { approved: boolean; comments?: string }; return { documentId: document.id, approved: approval.approved, comments: approval.comments }; } }); ``` Output automatically includes the `workflowId` in the request. The approval service stores it and calls back when the human decides: ```bash theme={null} curl -X POST http://localhost:3001/workflow/document_approval-abc123/feedback \ -H "Content-Type: application/json" \ -d '{ "payload": { "approved": true, "comments": "Looks good" } }' ``` The workflow resumes with the approval data. ### Pattern 2: External System Initiates Use a signal with `condition()` when external systems contact your workflow unprompted. The `condition()` function pauses the workflow until a predicate becomes true — the workflow stays durable and doesn't consume resources while waiting. **Job:** Wait for Stripe to confirm a payment succeeded. ```typescript theme={null} // src/workflows/order_processing/workflow.ts import { workflow } from '@outputai/core'; import { defineSignal, setHandler, condition } from '@temporalio/workflow'; import { createOrder, fulfillOrder } from './steps.js'; const paymentComplete = defineSignal<[{ paymentId: string; amount: number }]>('paymentComplete'); export default workflow({ name: 'order_processing', description: 'Process order after payment confirmation', fn: async (input) => { const order = await createOrder(input); let payment: { paymentId: string; amount: number } | null = null; setHandler(paymentComplete, (data) => { payment = data; }); // Workflow pauses here, no CPU consumed await condition(() => payment !== null); // Payment received, continue processing const result = await fulfillOrder({ orderId: order.id, paymentId: payment!.paymentId }); return result; } }); ``` Configure Stripe to send webhooks to your Output API. When Stripe confirms payment: ```bash theme={null} curl -X POST http://localhost:3001/workflow/order_processing-abc123/signal/paymentComplete \ -H "Content-Type: application/json" \ -d '{ "payload": { "paymentId": "pi_123", "amount": 9900 } }' ``` The workflow wakes up and continues. ### Which Pattern to Use? | Scenario | Pattern | | - | - | | Workflow knows who to ask (approval service, specific user) | `sendPostRequestAndAwaitWebhook` | | External system contacts workflow unprompted (webhook, event) | Signal + `condition()` | | Need to poll for updates while waiting | Add a query alongside the signal | ## Full Example: Research Agent with Human Override A research agent that runs autonomously but accepts human intervention. Combines all the patterns: signals to stop or add questions, queries to check progress and tool calls, and updates to change settings. ```typescript theme={null} // src/workflows/research_agent/workflow.ts import { workflow } from '@outputai/core'; import { defineSignal, defineQuery, defineUpdate, setHandler } from '@temporalio/workflow'; import { planQuestions, executeQuestion, synthesize } from './steps.js'; // Types interface ToolCall { id: string; question: string; result: unknown; timestamp: number; } interface ProgressArgs { verbose?: boolean; toolCallId?: string; } // Define message handlers const stopSignal = defineSignal('stop'); const addQuestionSignal = defineSignal<[{ question: string }]>('addQuestion'); const getProgress = defineQuery('getProgress'); const setMaxIterations = defineUpdate('setMaxIterations'); export default workflow({ name: 'research_agent', description: 'Autonomous research with human override capabilities', fn: async (input) => { // State let shouldStop = false; let maxIterations = 3; let currentIteration = 0; let questionsCompleted = 0; let totalQuestions = 0; let qualityScore: number | null = null; let additionalQuestions: string[] = []; const toolCalls: ToolCall[] = []; // Signals setHandler(stopSignal, () => { shouldStop = true; }); setHandler(addQuestionSignal, (params) => { additionalQuestions.push(params.question); }); // Query with arguments - return different data based on request setHandler(getProgress, (args = {}) => { // Return specific tool call if (args.toolCallId) { return { toolCall: toolCalls.find(t => t.id === args.toolCallId) ?? null }; } // Return verbose or summary const summary = { iteration: currentIteration, questionsCompleted, totalQuestions, qualityScore }; if (args.verbose) { return { ...summary, toolCalls }; } return summary; }); // Update setHandler(setMaxIterations, (params) => { const previous = maxIterations; maxIterations = params.max; return previous; }); // Main research loop for (let i = 1; i <= maxIterations && !shouldStop; i++) { currentIteration = i; const questions = await planQuestions({ topic: input.topic, previousResults: toolCalls.map(t => t.result), additionalQuestions }); additionalQuestions = []; totalQuestions = questions.length; questionsCompleted = 0; for (const question of questions) { if (shouldStop) break; const result = await executeQuestion({ question }); // Track each tool call for querying toolCalls.push({ id: `tc-${toolCalls.length + 1}`, question, result, timestamp: Date.now() }); questionsCompleted++; } const synthesis = await synthesize(toolCalls.map(t => t.result)); qualityScore = synthesis.score; if (qualityScore >= 0.85) { break; } } return { results: toolCalls, iterations: currentIteration, finalScore: qualityScore }; } }); ``` ### Interacting with the Agent **Start the research:** ```bash theme={null} curl -X POST http://localhost:3001/workflow/start \ -H "Content-Type: application/json" \ -d '{ "workflowName": "research_agent", "input": { "topic": "AI safety" } }' ``` **Check progress (summary):** ```bash theme={null} curl -X POST http://localhost:3001/workflow/research_agent-abc123/query/getProgress \ -H "Content-Type: application/json" \ -d '{ "payload": {} }' # { "iteration": 2, "questionsCompleted": 3, "totalQuestions": 5, "qualityScore": 0.72 } ``` **Check progress (with full tool call history):** ```bash theme={null} curl -X POST http://localhost:3001/workflow/research_agent-abc123/query/getProgress \ -H "Content-Type: application/json" \ -d '{ "payload": { "verbose": true } }' # { "iteration": 2, ..., "toolCalls": [{ "id": "tc-1", "question": "...", "result": {...} }, ...] } ``` **Inspect a specific tool call:** ```bash theme={null} curl -X POST http://localhost:3001/workflow/research_agent-abc123/query/getProgress \ -H "Content-Type: application/json" \ -d '{ "payload": { "toolCallId": "tc-3" } }' # { "toolCall": { "id": "tc-3", "question": "What are current AI safety challenges?", ... } } ``` **Add a question the agent should investigate:** ```bash theme={null} curl -X POST http://localhost:3001/workflow/research_agent-abc123/signal/addQuestion \ -H "Content-Type: application/json" \ -d '{ "payload": { "question": "What are the key alignment proposals?" } }' ``` **Extend the research (and see old limit):** ```bash theme={null} curl -X POST http://localhost:3001/workflow/research_agent-abc123/update/setMaxIterations \ -H "Content-Type: application/json" \ -d '{ "payload": { "max": 5 } }' # Returns: 3 ``` **Stop early when quality is good enough:** ```bash theme={null} curl -X POST http://localhost:3001/workflow/research_agent-abc123/signal/stop ``` ## Reference ### Outbound Functions Both are imported from `@outputai/core` and used inside workflow `fn`. **`sendHttpRequest(options)`** — Fire-and-forget HTTP request. | Option | Type | Required | | - | - | - | | `url` | `string` | Yes | | `method` | `'GET' \| 'POST' \| 'PUT' \| 'DELETE' \| 'PATCH'` | No (default: `GET`) | | `payload` | `object` | No | | `headers` | `Record` | No | | `responseOptions.includeHeaders` | `boolean` | No (default: `false`) | | `responseOptions.includeBody` | `boolean` | No (default: `false`) | **`sendPostRequestAndAwaitWebhook(options)`** — POST then pause until callback. | Option | Type | Required | | - | - | - | | `url` | `string` | Yes | | `payload` | `object` | No | | `headers` | `Record` | No | Header values can reference worker environment variables with `$ENV_VAR_NAME`, for example `Authorization: 'Bearer $API_TOKEN'`. Response headers are redacted when included by `sendHttpRequest`. Response bodies are not redacted, so only set `includeBody: true` when the body is safe to store in workflow history and trace files. > [!WARNING] > > These helpers are not primarily designed for secure or sensitive HTTP exchanges. Activity inputs and outputs are stored in Temporal history and can appear in trace files, so secrets can leak if they are placed directly in URLs, payloads, literal headers, or opt-in response bodies. Callback endpoint: `POST /workflow/:id/feedback` with `{ "payload": {...} }`. ### Inbound Primitives All are imported from `@temporalio/workflow` and used inside workflow `fn`. **Signal** — Async, no return value. ```typescript theme={null} const mySignal = defineSignal<[PayloadType]>('signalName'); setHandler(mySignal, (payload) => { /* mutate state */ }); ``` HTTP: `POST /workflow/:id/signal/signalName` with `{ "payload": {...} }` **Query** — Sync, read-only, returns value. ```typescript theme={null} const myQuery = defineQuery('queryName'); setHandler(myQuery, () => { return currentState; }); ``` HTTP: `POST /workflow/:id/query/queryName` **Update** — Sync, can mutate, returns value. ```typescript theme={null} const myUpdate = defineUpdate('updateName'); setHandler(myUpdate, (payload) => { /* mutate */ return result; }); ``` HTTP: `POST /workflow/:id/update/updateName` with `{ "payload": {...} }` **Condition** — Pause until predicate is true. ```typescript theme={null} await condition(() => someState !== null); ``` ### Error Handling If the workflow doesn't exist, the API returns a `404` error. If the workflow exists but doesn't have a handler for the given signal/query/update name, Temporal throws an error. Make sure your handler names match between the workflow code and the API calls. For advanced patterns (validators, async handlers, timeouts), see [Temporal's message passing docs](https://docs.temporal.io/develop/typescript/message-passing). # The workflow.ts File Source: https://docs.output.ai/workflows/index Define durable, deterministic orchestration logic Every Output project starts with a `workflow.ts` file. This is where you define **what** happens and **in what order** — fetch company data, then enrich it with an LLM, then push it to your CRM. The workflow orchestrates; the [steps](/steps) do the actual work. ## Basic Workflow Here's a workflow that enriches a sales lead by looking up the company and generating a summary: ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { lookupCompany, generateSummary } from './steps.js'; import { LeadEnrichmentInput, LeadEnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', description: 'Enrich a sales lead with company data and AI summary', inputSchema: LeadEnrichmentInput, outputSchema: LeadEnrichmentOutput, fn: async (input) => { const company = await lookupCompany(input.companyDomain); const summary = await generateSummary(company); return { company: company.name, summary }; }, }); // types.ts // import { z } from '@outputai/core'; // // export const LeadEnrichmentInput = z.object({ // companyDomain: z.string() // }); // // export const LeadEnrichmentOutput = z.object({ // company: z.string(), // summary: z.string() // }); ``` The `fn` function is your workflow logic. It calls steps in sequence, and each step's result is automatically cached — if a step fails and the workflow retries, previously completed steps won't re-execute. ## Workflow Function | Option | Type | Description | | - | - | - | | `name` | `string` | Unique identifier for the workflow | | `description` | `string` | Human-readable description | | `inputSchema` | `ZodSchema` | Zod schema for input; values are **parsed** before `fn` runs | | `outputSchema` | `ZodSchema` | Zod schema for output; values are **parsed** before returning to callers | | `fn` | `function` | The workflow implementation | | `options` | `object` | Optional workflow options (see [Options](#options)) | | `aliases` | `string[]` | Optional alternative names for backward-compatible renaming (see [Aliases](#aliases)) | Workflow names must start with a letter or underscore, followed by letters, numbers, or underscores. Hyphens, spaces, dots, and other punctuation are not allowed. > [!NOTE] > > Schemas parse workflow values; they do not only validate them. The workflow `fn` receives the value returned by `inputSchema`, and the workflow caller receives the value returned by `outputSchema`. Zod transforms, coercions, defaults, and object-key stripping therefore apply at runtime. ### Schema transforms and Temporal Workflow `inputSchema` / `outputSchema` run inside the Temporal workflow sandbox on every activation, including replay and every `continueAsNew` run (continuations are not special-cased — args are parsed like any other start). * Prefer wire-format schemas on workflows: types, `.default()`, and careful use of `z.coerce`. * Any `.transform()` / `.preprocess()` on a workflow schema must be **deterministic** (safe under Temporal replay). * Prefer **idempotent** transforms on workflow `inputSchema`, or pass wire-format payloads into `continueAsNew`. A non-idempotent transform applied to already-parsed values will run again on the next execution. * One-shot or non-idempotent shaping belongs in a [step](/steps) or inside `fn` after you have accepted wire input. ## Workflow Rules Workflows must be **deterministic** — given the same input, they must always follow the same path. This is because Output (via Temporal) replays your workflow code to recover state after failures. If the code produces different results on replay, recovery breaks. In practice this means: > [card] Do > > **Do:** > > * Call steps and evaluators > * Call other workflows as functions > * Use conditionals and loops > * Import from allowed files > [card] Don't > > **Don't:** > > * Make API calls directly > * Use `Date.now()` or `Math.random()` > * Import component files from wrong locations > * Start child workflows with `executeChild` or `startChild` (they work, but won't appear in the trace file) Any I/O (API calls, LLM requests, database queries) goes in steps. The workflow just decides which steps to call and in what order. ### Allowed Imports Workflows can import from: **Components (detected by convention):** * `steps.ts` — A single file named `steps.ts` in the workflow directory * `steps/*.ts` — Any file inside a `steps/` directory in the workflow directory * `evaluators.ts` — A single file named `evaluators.ts` in the workflow directory * `evaluators/*.ts` — Any file inside an `evaluators/` directory in the workflow directory * `shared/steps/*.ts` — Shared steps available to all workflows * `shared/evaluators/*.ts` — Shared evaluators available to all workflows **Non-component files (any name or organization):** * Type definitions, constants, helpers, utilities * API clients from `src/clients/` **Other workflows:** * Import another workflow's default export and call it like a function. It runs as a child workflow with its own retry boundaries. See [Child Workflows](/workflows/child-workflows). ```typescript theme={null} import enrichCompanyWorkflow from '../enrich_company/workflow.js'; const company = await enrichCompanyWorkflow({ domain: input.domain }); ``` ## Project Structure Each workflow is a self-contained directory with a standard set of files. API clients live in `src/clients/` at the top level — they're standalone modules any step can import: ``` src/ ├── clients/ # API clients (one file per external API) │ ├── clearbit.ts │ ├── hubspot.ts │ └── tavily.ts ├── shared/ # Shared steps and evaluators │ ├── steps/ │ │ └── normalize_company.ts │ └── evaluators/ │ └── data_quality.ts └── workflows/ ├── lead_enrichment/ # A typical workflow │ ├── workflow.ts # Orchestration logic │ ├── steps.ts # Step definitions │ ├── types.ts # TypeScript types │ ├── prompts/ # Prompt files │ │ └── summarize_company@v1.prompt │ └── scenarios/ # Test inputs │ └── test_input.json │ └── outreach/ # Related workflows can be grouped ├── personalization/ │ ├── workflow.ts │ └── steps.ts └── sequence_builder/ ├── workflow.ts └── steps.ts ``` > [!NOTE] > > The workflow file must be named `workflow.ts`. Steps are detected from `steps.ts` or any file inside a `steps/` directory. Evaluators follow the same pattern with `evaluators.ts` or `evaluators/`. Shared components must be under `shared/steps/` or `shared/evaluators/`. Everything else (types, utils, clients) can be organized however you prefer. ## Options ### Activity options You can configure how steps behave — timeouts, retry counts, backoff — using the `options.activityOptions` property. These apply to all steps in the workflow: ```typescript workflow.ts theme={null} import { workflow } from '@outputai/core'; import { lookupCompany, generateSummary } from './steps.js'; import { LeadEnrichmentInput, LeadEnrichmentOutput } from './types.js'; export default workflow({ name: 'lead_enrichment', inputSchema: LeadEnrichmentInput, outputSchema: LeadEnrichmentOutput, options: { activityOptions: { retry: { maximumAttempts: 5 }, startToCloseTimeout: '10m' } }, fn: async (input) => { const company = await lookupCompany(input.companyDomain); return { summary: await generateSummary(company) }; }, }); ``` Individual steps can override these with their own `options.activityOptions` — see [step options](/steps#options). When this workflow is called as a child workflow, the caller can also pass invocation-level `activityOptions` for that child branch; step options still take final precedence. See [Child Workflows](/workflows/child-workflows#activity-options-override). The fields under `activityOptions` are supported by Output and relayed directly to [Temporal](https://temporal.io/), our runtime. Output accepts Temporal [Activity options](https://typescript.temporal.io/api/interfaces/common.ActivityOptions), except `versioningIntent`, `taskQueue`, and `allowEagerDispatch`: * `activityId` * `cancellationType` * `heartbeatTimeout` * `priority` * `retry` * `scheduleToCloseTimeout` * `scheduleToStartTimeout` * `startToCloseTimeout` * `summary` Default values: ```js theme={null} { startToCloseTimeout: '20m', heartbeatTimeout: '5m', retry: { initialInterval: '10s', backoffCoefficient: 2.0, maximumInterval: '2m', maximumAttempts: 3, nonRetryableErrorTypes: [ 'FatalError' ] } } ``` Steps that throw `ValidationError` or `FatalError` are never retried — these signal problems that won't fix themselves on retry (bad input, missing credentials). Custom `nonRetryableErrorTypes` are added alongside `FatalError`; activity options cannot make `FatalError`, `ValidationError`, or `TransparentFatalError` retryable. ### Native options Output supports one native workflow option besides activity options: | Option | Type | Description | | - | - | - | | `disableTrace` | `boolean` | When `true`, disables trace file generation for this workflow. Only has effect when [tracing](/operations/tracing) is enabled globally. | Example — skip tracing for high-volume workflows you don't need to inspect: ```typescript workflow.ts theme={null} export default workflow({ name: 'internal_sync', description: 'High-volume sync — no trace needed', inputSchema: SyncInput, outputSchema: SyncOutput, options: { disableTrace: true }, fn: async (input) => { /* ... */ } }); ``` This only has effect when tracing is enabled globally; if tracing is off, the flag does nothing. ## Aliases When you rename a workflow, existing callers still reference the old name. Aliases let you declare alternative names that resolve to the canonical workflow, so you can rename without a coordinated multi-deploy process: ```typescript workflow.ts theme={null} export default workflow({ name: 'lead_enrichment_v2', description: 'Enriches sales leads with company data', aliases: [ 'lead_enrichment', 'enrich_lead' ], inputSchema: LeadInput, outputSchema: LeadOutput, fn: async (input) => { const company = await lookupCompany(input.domain); return { summary: await generateSummary(company) }; }, }); ``` Callers using `lead_enrichment` or `enrich_lead` are resolved to `lead_enrichment_v2` before execution. The workflow runs under its canonical name, keeping execution history consistent. Alias names follow the same naming rules as workflow names: start with a letter or underscore, then use only letters, numbers, or underscores. Uniqueness is enforced case-insensitively at startup — an alias cannot conflict with any workflow name or another alias. ## Workflow Context The `fn` function receives a `context` object as its second argument, giving you access to workflow execution info: ```typescript workflow.ts theme={null} fn: async (input, context) => { const workflowId = context.info.workflowId; // ... } ``` * `context.control.continueAsNew()` — Continue the workflow as a new execution with fresh history * `context.control.isContinueAsNewSuggested()` — Check if continue-as-new is recommended * `context.info.workflowId` — The workflow execution ID See the [Execution Context guide](/workflows/context) for the full API. ## File Structure Workflows support two organization patterns: **Flat files:** ``` src/workflows/lead_enrichment/ ├── workflow.ts # Workflow definition (required) ├── steps.ts # Step implementations (required) ├── evaluators.ts # Evaluators (optional) ├── types.ts # TypeScript types (optional, any name works) └── prompts/ # LLM prompts (optional) ``` **Folder-based:** ``` src/workflows/lead_enrichment/ ├── workflow.ts ├── steps/ │ ├── lookup_company.ts │ └── generate_summary.ts ├── evaluators/ │ └── quality.ts ├── types.ts └── prompts/ ``` Both patterns can be used together in the same project. Use flat files when you have a few steps, switch to folders when a workflow grows. ## What's Next Once you have a workflow, you'll want to explore these related concepts: * [Steps](/steps) — Where I/O happens: API calls, LLM requests, database queries * [Child Workflows](/workflows/child-workflows) — Compose workflows by calling other workflows * [Parallel Execution](/workflows/parallel-execution) — Run multiple steps concurrently with `executeInParallel` * [External Integration](/workflows/external-integration) — Send data out, receive input, and query status * [Connecting to External APIs](/clients) — Build typed, traced API clients # Parallel Execution Source: https://docs.output.ai/workflows/parallel-execution Run steps, evaluators, or child workflows in parallel with optional concurrency control Some workflows need to do multiple things at once — look up company data from three APIs simultaneously, enrich 50 leads in a batch, or run quality checks in parallel after generating content. `executeInParallel` handles this: run multiple steps concurrently with optional rate limiting, and get all results back in order. ## Basic Usage Wrap each job in an arrow function and pass them as an array. Results come back in the same order you submitted them, with each result telling you whether the job succeeded or failed: ```typescript workflow.ts theme={null} import { workflow, executeInParallel } from '@outputai/core'; import { lookupCompany, searchNews } from './steps.js'; import { CompanyResearchInput, CompanyResearchOutput } from './types.js'; export default workflow({ name: 'company_research', description: 'Research a company from multiple sources in parallel', inputSchema: CompanyResearchInput, outputSchema: CompanyResearchOutput, fn: async (input) => { const results = await executeInParallel({ jobs: [ () => lookupCompany(input.companyDomain), () => searchNews(input.companyName) ] }); const [companyResult, newsResult] = results; return { company: companyResult.ok ? companyResult.result : null, articles: newsResult.ok ? newsResult.result : [] }; } }); // types.ts // import { z } from '@outputai/core'; // // export const CompanyResearchInput = z.object({ // companyDomain: z.string(), // companyName: z.string() // }); // // export const CompanyResearchOutput = z.object({ // company: z.any(), // articles: z.array(z.any()) // }); ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `jobs` | `Array<() => Promise \| T>` | Array of functions that return a step, evaluator, or child workflow call (or any value). Do not pass promises directly. | | `concurrency` | `number` | Maximum number of jobs running at once. Default: `Infinity` (no limit). | | `onJobCompleted` | `(result: ParallelJobResult) => void` | Optional callback invoked as each job completes, in completion order (not submission order). | ## Result Type The function returns `Promise>>`, sorted by **original job index** (so results stay in the same order you submitted them). Each element is a discriminated union: | When | Shape | Fields | | - | - | - | | Success | `{ ok: true; result: T; index: number }` | `result` is the job's return value | | Failure | `{ ok: false; error: unknown; index: number }` | `error` is the thrown value | Handling successes and failures: ```typescript theme={null} const results = await executeInParallel({ jobs: input.domains.map(domain => () => enrichCompany(domain)) }); const enriched = results.filter((r): r is { ok: true; result: Company; index: number } => r.ok).map(r => r.result); const failed = results.filter(r => !r.ok); ``` ## Concurrency Limit When you're calling an external API that has rate limits, use `concurrency` to cap how many jobs run at once: ```typescript theme={null} const results = await executeInParallel({ jobs: input.domains.map(domain => () => enrichCompany(domain)), concurrency: 3 }); ``` With `concurrency: 3`, at most three enrichment calls run at a time. When one finishes, the next starts. ## onJobCompleted Callback `onJobCompleted` fires once per job in **completion order** (fastest first), not submission order. Use it for logging progress or streaming partial results: ```typescript theme={null} const results = await executeInParallel({ jobs: leads.map(lead => () => enrichLead(lead)), onJobCompleted: (result) => { if (result.ok) { // Log progress as each lead completes } else { // Log failure at result.index } } }); ``` ## Examples ### Batch enrichment with rate limiting Enrich a list of leads, capping concurrency to respect API rate limits: ```typescript workflow.ts theme={null} import { workflow, executeInParallel } from '@outputai/core'; import { enrichLead } from './steps.js'; import { BatchInput, BatchOutput } from './types.js'; export default workflow({ name: 'batch_enrich', description: 'Enrich leads in parallel with rate limiting', inputSchema: BatchInput, outputSchema: BatchOutput, fn: async (input) => { const results = await executeInParallel({ jobs: input.leads.map(lead => () => enrichLead(lead)), concurrency: 5 }); const enriched = []; const failedIds = []; results.forEach((r, i) => { if (r.ok) { enriched.push(r.result); } else { failedIds.push(input.leads[r.index].id); } }); return { enriched, failedIds }; } }); // types.ts // import { z } from '@outputai/core'; // // export const BatchInput = z.object({ // leads: z.array(z.object({ id: z.string(), domain: z.string() })) // }); // // export const BatchOutput = z.object({ // enriched: z.array(z.any()), // failedIds: z.array(z.string()) // }); ``` ### Gather data from multiple sources Run different steps in one batch — results stay in job order: ```typescript theme={null} const results = await executeInParallel({ jobs: [ () => lookupCompany(input.domain), () => searchLinkedIn(input.companyName), () => searchNews(input.companyName) ] }); const [companyResult, linkedInResult, newsResult] = results; const company = companyResult.ok ? companyResult.result : null; const linkedIn = linkedInResult.ok ? linkedInResult.result : null; const news = newsResult.ok ? newsResult.result : []; ``` ### Child workflows in parallel Run multiple child workflows with a concurrency cap: ```typescript theme={null} import enrichCompanyWorkflow from '../enrich_company/workflow.js'; const results = await executeInParallel({ jobs: input.domains.map(domain => () => enrichCompanyWorkflow({ domain })), concurrency: 4 }); const enriched = results.filter(r => r.ok).map(r => r.result); ``` ## Important: Wrap in arrow functions Jobs must be **functions** that return the step, evaluator, or child workflow call. Do not pass promises: ```typescript theme={null} // Correct: each job is a function executeInParallel({ jobs: [ () => enrichLead(data1), () => enrichLead(data2) ] }); // Wrong: passing promises directly executeInParallel({ jobs: [ enrichLead(data1), // Don't do this enrichLead(data2) ] }); ``` Passing promises would start all work immediately and break determinism; wrapping in functions lets `executeInParallel` control when each job runs and respect the concurrency limit. # Running Workflows Source: https://docs.output.ai/workflows/running Execute workflows from the CLI — synchronously, asynchronously, and with scenario files You've defined a workflow. Now you need to run it. Output gives you two execution modes: * **Synchronous** — `output workflow run` executes the workflow and waits for the result. Use this during development and for short-lived workflows. * **Asynchronous** — `output workflow start` kicks off the workflow and returns immediately. Use `status` and `result` to check on it later. Use this for long-running workflows or batch jobs. Both modes accept input the same way: either a **scenario file** or inline JSON. Scenario files are covered [at the end of this page](#scenario-files). ## Running a Workflow `output workflow run` executes a workflow and waits for the result: ```bash theme={null} # Using a scenario file (recommended) output workflow run lead_enrichment acme # Using inline JSON output workflow run lead_enrichment --input '{"companyDomain": "acme.com"}' # Using a JSON file path output workflow run lead_enrichment --input ./test_input.json ``` The command blocks until the workflow completes, then prints the output: ``` Using scenario: src/workflows/lead_enrichment/scenarios/acme.json Executing workflow: lead_enrichment... Workflow ID: lead_enrichment-22b798f9-4812-4f48-80b2-89fac07285ed Output: { "company": "Acme Corp", "summary": "Enterprise software company focused on..." } ``` Use `--format json` if you need machine-readable output, for example when piping to another command or in scripts: ```bash theme={null} output workflow run lead_enrichment acme --format json ``` If the workflow fails, the command prints the error and exits with code 1. | Flag | Default | Description | | - | - | - | | `--input, -i` | — | JSON string or file path (overrides scenario) | | `--catalog, -c` | `OUTPUT_CATALOG_ID` | Catalog name (the deprecated `--task-queue, -q` aliases still work) | | `--format, -f` | text | Output format: `json`, `text` | ## Starting a Workflow Asynchronously `output workflow start` fires off a workflow without waiting. It returns a workflow ID immediately: ```bash theme={null} output workflow start lead_enrichment acme ``` ``` Workflow started successfully Workflow ID: lead_enrichment-a1b2c3d4-5678-90ab-cdef-1234567890ab Use "workflow status " to check the workflow status Use "workflow result " to get the workflow result when complete ``` This is the right choice when: * The workflow takes minutes or longer to complete * You're launching multiple workflows in a batch * You want to check results later rather than keeping a terminal open The flags are the same as `run`, minus `--format` (there's no result to format yet). ## Checking Status Poll a running workflow with `output workflow status`: ```bash theme={null} output workflow status lead_enrichment-a1b2c3d4-5678-90ab-cdef-1234567890ab ``` ``` Workflow ID: lead_enrichment-a1b2c3d4-5678-90ab-cdef-1234567890ab Status: running Started At: 2026-03-06T10:30:45.123Z ``` The status will be one of: | Status | Meaning | | - | - | | `running` | Still executing | | `completed` | Finished successfully | | `failed` | Completed with an error | | `canceled` | Stopped gracefully via `workflow stop` | | `terminated` | Force-stopped via `workflow terminate` | | `timed_out` | Exceeded the execution timeout | ## Getting Results Once a workflow completes, retrieve its output with `output workflow result`: ```bash theme={null} output workflow result lead_enrichment-a1b2c3d4-5678-90ab-cdef-1234567890ab ``` ``` Workflow ID: lead_enrichment-a1b2c3d4-5678-90ab-cdef-1234567890ab Output: { "company": "Acme Corp", "summary": "Enterprise software company focused on..." } ``` If the workflow failed, you'll see the error instead: ``` Workflow ID: lead_enrichment-a1b2c3d4-5678-90ab-cdef-1234567890ab Status: failed Error: Step 'lookup_company' failed: 404 Not Found ``` Use `--format json` for the full structured response including status, output, error, and execution metadata fields. See the [CLI package docs](/packages/cli#workflow-result-json-format) for the JSON format. ## Debugging Execution When something goes wrong — or you just want to understand what happened — use `output workflow debug` to see the execution trace: ```bash theme={null} output workflow debug lead_enrichment-a1b2c3d4-5678-90ab-cdef-1234567890ab ``` This prints a tree showing every step that ran, what it received, what it returned, and how long it took: ``` Trace Log: ────────────────────────────────────────────────────────────────────────────── ┌─ [lead_enrichment] completed │ ├─ [lookup_company] [END] 150ms │ │ ├─ input: {"companyDomain":"acme.com"} │ │ └─ output: {"name":"Acme Corp","domain":"acme.com",...} │ └─ [generate_summary] [END] 1200ms │ ├─ input: {"name":"Acme Corp","domain":"acme.com",...} │ └─ output: "Enterprise software company focused on..." ────────────────────────────────────────────────────────────────────────────── ``` The text format truncates long values for readability. Use `--format json` to get the full untruncated trace — this is especially useful when you need to see complete LLM inputs and outputs: ```bash theme={null} output workflow debug lead_enrichment-a1b2c3d4-5678-90ab-cdef-1234567890ab --format json ``` > [!TIP] > > Traces are also saved as JSON files in your project's `logs/runs/` directory. You can open these directly, share them with teammates, or feed them to Claude Code for analysis. ## Stopping Workflows If you need to cancel a running workflow: * **`output workflow stop `** — Graceful cancellation. The workflow has a chance to clean up. * **`output workflow terminate `** — Immediate kill. Use for stuck workflows or cleanup after branch switches. ```bash theme={null} # Graceful stop output workflow stop lead_enrichment-a1b2c3d4 # Force terminate with a reason output workflow terminate lead_enrichment-a1b2c3d4 --reason "Cleaning up old runs" ``` ## Rerunning From a Step When a workflow fails late — or you've edited a prompt that only affects a downstream step — you usually don't want to re-run the whole thing. Early steps may have made expensive LLM calls, or slow API requests whose results haven't changed. `output workflow reset` creates a new run that replays up to a given completed step (reusing its recorded output), then re-executes every step after it: ```bash theme={null} # After editing a prompt used by `generate_blog_post`, rerun just the steps # after `consolidate_competitors` — the upstream competitor analysis is reused. output workflow reset lead_enrichment-a1b2c3d4 \ --step consolidate_competitors \ --reason "Retry with updated blog-post prompt" ``` Find valid step names with `output workflow debug --format json`. The step itself is not re-executed; only the steps after it. ## Quick Reference | What you want to do | Command | | - | - | | Run and wait for result | `output workflow run [scenario]` | | Start without waiting | `output workflow start [scenario]` | | Check if still running | `output workflow status ` | | Get the final output | `output workflow result ` | | See the execution trace | `output workflow debug ` | | Stop gracefully | `output workflow stop ` | | Force stop | `output workflow terminate ` | | Rerun from after a step | `output workflow reset --step ` | For the full CLI reference including all flags and additional commands like `workflow cost` and `workflow test`, see the [CLI package docs](/packages/cli). ## Scenario Files A scenario file is a plain JSON file that contains the input for a workflow run. It lives in the workflow's `scenarios/` directory and matches the workflow's `inputSchema`: ``` src/workflows/lead_enrichment/ ├── workflow.ts ├── steps.ts └── scenarios/ ├── acme.json └── small_company.json ``` ```json scenarios/acme.json theme={null} { "companyDomain": "acme.com" } ``` Scenarios are useful because they're repeatable — you can re-run the same input without retyping it, share them with teammates, and check them into version control. Think of them as saved test inputs for your workflow. The scenario name is the filename without `.json`. To run with the `acme` scenario: ```bash theme={null} output workflow run lead_enrichment acme ```