> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agnost.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Motia

> Capture LLM calls made inside Motia steps

## Choose a setup method

| Method | Use it when |
| - | - |
| **Agnost AI skill** | You want your coding agent to inspect the app, make the change, and verify it. |
| **Agnost AI SDK** | You want explicit control over the interaction boundaries and fields. |
| **OpenTelemetry** | The framework already emits useful spans or you operate an OTel pipeline. |

Start with one method for a call path. Combining SDK tracking with framework
OpenTelemetry on the same call can create duplicate interactions.

## Recommended: Agnost AI skill

> [!NOTE]
>
> **Recommended.** Choose this path when you want your coding agent to inspect the
> project, select a supported transport, make the smallest instrumentation change,
> send a test event, and verify that it reached Agnost AI.

Install the skill once in your coding-agent environment:

```bash theme={null}
npx skills add AgnostAI/skills --skill agnost-ai
```

Run the framework-specific prompt below from the application root. Review the
resulting diff before deploying it.

```text theme={null}
Use the agnost-ai skill to add Agnost AI analytics to this Motia application.
Org ID: your-org-id
Instrument the real step handler that calls the model and verify one fresh interaction.
```

This guide covers Motia 1.0 TypeScript steps (`motia` on npm) running on the iii engine.
Motia's own traces describe step and function execution and carry no model data, so the
setup below captures the model calls your steps make.

## Manual setup: Agnost AI SDK

```bash theme={null}
npm install agnostai
```

Initialize once in a shared module, for example `src/lib/agnost.ts`:

```typescript theme={null}
import * as agnost from 'agnostai'

agnost.init(process.env.AGNOST_ORG_ID!)

export { agnost }
```

Then wrap the model call in your step handler:

```typescript theme={null}
import { type Handlers, type StepConfig } from 'motia'
import { generateText } from 'ai'
import { anthropic } from '@ai-sdk/anthropic'
import { z } from 'zod'
import { agnost } from './lib/agnost'

export const config = {
  name: 'Chat',
  triggers: [
    {
      type: 'http',
      method: 'POST',
      path: '/chat',
      bodySchema: z.object({ message: z.string(), userId: z.string(), sessionId: z.string() }),
    },
  ],
  enqueues: [],
} as const satisfies StepConfig

export const handler: Handlers<typeof config> = async ({ request }) => {
  const { message, userId, sessionId } = request.body

  const interaction = agnost.begin({
    userId,
    agentName: 'motia-chat',
    input: message,
    conversationId: sessionId,
  })
  if (!interaction) throw new Error('Agnost is not initialized. Call agnost.init() first.')
  try {
    const { text } = await generateText({ model: anthropic('claude-haiku-4-5'), prompt: message })
    interaction.end(text)
    return { status: 200, body: { reply: text } }
  } catch (error) {
    interaction.end(String(error), false)
    throw error
  }
}
```

Use any model client inside the `try` block. The SDK only needs the input and the output.
Call `await agnost.shutdown()` once when the process exits, not inside a step.

## Manual setup: OpenTelemetry

Motia's runtime (`iii-sdk`) registers the global OpenTelemetry tracer provider in every step
process and sends those spans to the iii engine. The engine exports over OTLP gRPC only, and
its spans have no GenAI attributes, so Agnost AI would not ingest them. Instead, give the
Vercel AI SDK a tracer from a provider of your own that exports to Agnost AI. Model calls,
tool calls, prompts, and answers then arrive as GenAI spans.

### Install

```bash theme={null}
npm install ai @ai-sdk/anthropic @ai-sdk/otel @opentelemetry/api@^1.10.0 \
  @opentelemetry/sdk-trace @opentelemetry/exporter-trace-otlp-proto
```

Installing `@opentelemetry/api@^1.10.0` explicitly avoids an npm peer conflict between the
current OTLP exporter and the older OpenTelemetry packages that `motia` depends on.

### Setup

**1. Add `src/lib/agnost-otel.ts`**

```typescript theme={null}
import { TracerProvider, BatchSpanProcessor } from '@opentelemetry/sdk-trace'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'
import { registerTelemetry } from 'ai'
import { OpenTelemetry } from '@ai-sdk/otel'

// A provider of our own: Motia's runtime already registers the global one,
// and that one exports to the iii engine, not to Agnost AI.
const provider = new TracerProvider({
  spanProcessors: [
    new BatchSpanProcessor({
      exporter: new OTLPTraceExporter({
        url: 'https://otel.agnost.ai/v1/traces',
        headers: { 'X-Agnost-Org-ID': process.env.AGNOST_ORG_ID! },
      }),
    }),
  ],
})

registerTelemetry(
  new OpenTelemetry({ tracer: provider.getTracer('motia-ai'), runtimeContext: true }),
)
```

**2. Import it in the step and turn telemetry on**

```typescript theme={null}
import './lib/agnost-otel'
import { type Handlers, type StepConfig } from 'motia'
import { generateText, stepCountIs, tool } from 'ai'
import { anthropic } from '@ai-sdk/anthropic'
import { z } from 'zod'

export const config = {
  name: 'Chat',
  triggers: [
    {
      type: 'http',
      method: 'POST',
      path: '/chat',
      bodySchema: z.object({ message: z.string(), userId: z.string(), sessionId: z.string() }),
    },
  ],
  enqueues: [],
} as const satisfies StepConfig

export const handler: Handlers<typeof config> = async ({ request }) => {
  const { message, userId, sessionId } = request.body

  const { text } = await generateText({
    model: anthropic('claude-haiku-4-5'),
    prompt: message,
    tools: {
      getWeather: tool({
        description: 'Get the weather for a city',
        inputSchema: z.object({ city: z.string() }),
        execute: async ({ city }) => ({ city, forecast: 'sunny, 22 C' }),
      }),
    },
    stopWhen: stepCountIs(3),
    runtimeContext: { userId, sessionId },
    telemetry: {
      isEnabled: true,
      functionId: 'motia-chat',
      includeRuntimeContext: { userId: true, sessionId: true },
    },
  })

  return { status: 200, body: { reply: text } }
}
```

Set `AGNOST_ORG_ID` in the environment that starts the engine (`iii -c iii-config.yaml`), so
the step process inherits it.

### What appears in Agnost AI

* **Conversations** grouped by `sessionId`.
* **User-level analytics** grouped by `userId`.
* **Events**: one `motia-chat` agent event per `generateText` call, with `agent_step` and
  `chat` children for each model request and a tool event (here `getWeather`) for each tool
  call, with its arguments and result.

### Verify

Call the endpoint once, for example
`curl -X POST localhost:3111/chat -H 'content-type: application/json' -d '{"message":"What is the weather in Paris?","userId":"u-42","sessionId":"conv-abc123"}'`,
then open **Events** in Agnost AI. Confirm a `motia-chat` event with the message as input and
the reply as output, a `getWeather` tool event, and the session and user on the conversation.

### Troubleshooting

* No events: confirm the step imports `./lib/agnost-otel` and that `AGNOST_ORG_ID` is set
  in the engine's environment. Spans are batched and sent within about five seconds.
* A process has one global tracer provider, and Motia's runtime registers it. Calling
  `NodeSDK.start()` or `provider.register()` in a step either fails or takes over Motia's
  tracing, depending on load order. Pass the tracer to `new OpenTelemetry({ tracer })` as
  shown instead.
* The iii engine's own OTLP exporter (`OtelModule` in `iii-config.yaml`) uses gRPC and
  sends function spans without model data. Do not point it at Agnost AI.
* Python steps: wrap the model call with the [Python SDK](https://docs.agnost.ai/python-conversation.md) the same way
  as the TypeScript SDK example above.

### References

* [Motia example project](https://github.com/MotiaDev/motia-iii-example)
* [Migrating from Motia to iii](https://iii.dev/docs/changelog/0-11-0/migrating-from-motia-js)
* [Vercel AI SDK telemetry](https://ai-sdk.dev/docs/ai-sdk-core/telemetry)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review the complete Motia interaction.
* [Events](https://docs.agnost.ai/using-events.md): inspect model and tool calls made by your steps.
* [Patterns](https://docs.agnost.ai/using-patterns.md): organize production conversations by what users wanted.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.