Skip to main content

Observability Exports

import {
  createTraceCollector,
  RunflowTraceCollector,
  RunflowTraceSpan,
  traced
} from '@runflow-ai/sdk';

Conversation Messages

import { message } from '@runflow-ai/sdk/observability';

message(data, options?)

Emit a conversation_message trace. The portal renders these as chat bubbles and uses them to populate the thread sidebar preview. See Conversation Messages for the full guide and examples.
message({ role: 'user',      content: 'Quais acomodações?' });
message({ role: 'assistant', content: 'Oferecemos duas opções...' });
Parameters (MessageData):
NameTypeDescription
role'user' | 'assistant' | 'system' | 'tool' | stringSpeaker. Custom strings are accepted.
contentstring | Record<string, any>Plain text or a structured object with a type field (e.g. { type: 'buttons', items: [...] }).
metadataRecord<string, any>Optional extra fields (citations, confidence, custom flags).
parentIdstringOptional explicit parent span’s traceId. Falls back to the active startSpan() context.
LogOptions:
NameTypeDescription
parentIdstringSame as data.parentId. Provided for symmetry with log() / logError().
Available since @runflow-ai/sdk@1.1.10.

Code-first Metrics

import { metrics, MetricsRegistry } from '@runflow-ai/sdk/observability';

metrics (singleton)

Process-wide MetricsRegistry instance. import { metrics } returns the same object across modules, mirroring how track() and identify() share state.

metrics.defineTab(input)

Idempotent on name — re-registering updates the sortOrder.
metrics.defineTab({ name: 'Vendas', sortOrder: 0 });

metrics.defineCard(input)

Validates synchronously via shared Zod schemas. Throws on invalid cardType, invalid gridLayout, or duplicate (cardType, title) pairs. Legacy aliases (e.g. tableMode → mode) are auto-normalized before validation.
metrics.defineCard({
  tab: 'Vendas',
  title: 'Funil de checkout',
  cardType: 'funnel',
  config: {
    funnelMode: 'multi_event',
    steps: [
      { eventName: 'cart_open',        label: 'Carrinho aberto' },
      { eventName: 'checkout_started', label: 'Início checkout' },
      { eventName: 'sale',             label: 'Pagamento' },
    ],
  },
  gridLayout: { x: 0, y: 0, w: 6, h: 5 },
});

metrics.sync(options?)

Two-phase upsert against the runtime endpoints. Returns a tally:
const result = await metrics.sync();
// { agentId, tabs: { created, updated, total }, cards: { created, updated, failed, total } }
SyncOptions:
NameTypeDefaultDescription
agentIdstringRUNFLOW_AGENT_ID envOverride the target agent.
baseUrlstringRUNFLOW_API_URL envOverride the API host.
apiKeystringRUNFLOW_API_KEY envOverride the API key.
strictbooleanfalseThrow on any tab/card error instead of warning.
Each card carries a deterministic idempotencyKey = ${cardType}:${title}:${tab ?? ''} so repeated sync() calls are safe. See Metrics Registry for the full guide.

Execution Reviews

import { Reviews } from '@runflow-ai/sdk';

new Reviews(options?)

Programmatic access to execution reviews. Requires an underlying RunflowAPIClient exposing the reviews namespace (SDK ≥ 1.1.13).
const reviews = new Reviews();
// or with a custom client:
const reviews = new Reviews({ apiClient: customClient });
Methods:
MethodSignatureDescription
create(args: CreateExecutionReviewArgs) => Promise<CreateExecutionReviewResult>Create a review. comment must be ≥ 10 chars.
checkHasReview(executionId: string) => Promise<CheckHasReviewResult>Idempotent check before create().
list(filters?: ListReviewsFilters) => Promise<ListReviewsResult>List with filters. Backend caps limit at 100 (defaults to 50).
get(reviewId: string) => Promise<ExecutionReview>Fetch a single review.
update(reviewId, args: UpdateExecutionReviewArgs) => Promise<UpdateReviewResult>Partial update. Setting status: 'resolved' auto-stamps resolvedBy / resolvedAt.
delete(reviewId: string) => Promise<DeleteReviewResult>Hard delete.
stats(filters: { agentId }) => Promise<ReviewsStats>Aggregate counts + avgResolutionHours.
exportForTraining(filters: ExportForTrainingFilters) => Promise<ExportForTrainingResult>Export as OpenAI conversational fine-tuning examples.
Typed errors (all extend ReviewsError):
ClassStatusWhen
ReviewAlreadyExistsError409Execution already has a review.
ReviewNotFoundError404reviewId not found (or wrong tenant).
ReviewsErroranyOther failures — exposes status and raw body.
See Execution Reviews for the feedback-loop pattern.

Business Events Tracking

import { track, flushTrackEvents } from '@runflow-ai/sdk/observability';

track(eventName, properties?, options?)

Emit a business event for the portal dashboard.
track('alert_received', { company: 'NW', severity: 'High' });
Parameters:
NameTypeDescription
eventNamestringEvent name (e.g. 'order_placed')
propertiesRecord<string, any>Key-value event data
optionsTrackOptionsOptional overrides
TrackOptions:
NameTypeDescription
threadIdstringOverride auto-resolved thread ID
executionIdstringOverride auto-resolved execution ID
timestampstringISO-8601 timestamp (defaults to now)

flushTrackEvents()

Manually flush all buffered events. Returns a Promise<void>.
await flushTrackEvents();

Next Steps

API Client

View API client exports

Standalone Modules

View standalone modules