> ## 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.

# Inngest AgentKit

> Capture AgentKit network runs and tool calls with the Agnost AI SDK or OpenTelemetry spans

## 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 Inngest AgentKit application.
Org ID: your-org-id
Instrument the real network.run() or agent.run() path and verify one fresh interaction.
```

## Manual setup: Agnost AI SDK

Wrap each `network.run()` call with `begin()` / `end()`. Use AgentKit's `threadId` as the conversation ID so every turn of a chat lands in one conversation.

```bash theme={null}
npm install agnostai @inngest/agent-kit inngest zod
```

```typescript theme={null}
import * as agnost from 'agnostai';
import { anthropic, createAgent, createNetwork, createState, createTool, type AgentResult } from '@inngest/agent-kit';
import { z } from 'zod';

agnost.init('your-org-id');

const getWeather = createTool({
  name: 'get_weather',
  description: 'Get the current weather for a city',
  parameters: z.object({ city: z.string() }),
  handler: async ({ city }) => `Sunny and 21 C in ${city}`,
});

const supportAgent = createAgent({
  name: 'support-agent',
  system: 'You are a helpful assistant. Answer in one short sentence.',
  model: anthropic({ model: 'claude-haiku-4-5', defaultParameters: { max_tokens: 512 } }),
  tools: [getWeather],
});

const network = createNetwork({
  name: 'support-network',
  agents: [supportAgent],
  maxIter: 5,
  // Run the agent again after a tool call so it can answer with the result.
  router: ({ callCount, lastResult }) =>
    callCount === 0 || lastResult?.toolCalls.length ? supportAgent : undefined,
});

// The last assistant text the network produced.
function finalText(results: AgentResult[]): string {
  for (const result of [...results].reverse()) {
    for (const message of [...result.output].reverse()) {
      if (message.type === 'text' && message.role === 'assistant') {
        return typeof message.content === 'string'
          ? message.content
          : message.content.map((part) => part.text).join('');
      }
    }
  }
  return '';
}

export async function chat(threadId: string, userId: string, message: string) {
  const interaction = agnost.begin({
    userId,
    agentName: network.name,
    input: message,
    conversationId: threadId,
  });
  if (!interaction) throw new Error('Agnost is not initialized. Call agnost.init() first.');
  try {
    const run = await network.run(message, { state: createState({}, { threadId }) });
    const reply = finalText(run.state.results);
    interaction.end(reply);
    return reply;
  } catch (error) {
    interaction.end(String(error), false);
    throw error;
  }
}
```

`network.run()` returns a `NetworkRun`. Its `state.results` holds one `AgentResult` per agent call, and `finalText()` reads the last assistant message from them. The SDK records one event per turn. To also record each tool call as its own event, use the OpenTelemetry setup below.

Call `await agnost.shutdown()` once when the application exits, not after each request.

## Manual setup: OpenTelemetry

AgentKit doesn't emit OpenTelemetry spans of its own, and its model calls go through `fetch`, so provider instrumentations don't see them. Add two small spans instead: one around `network.run()` for the turn, and one around each tool handler. They use the OpenTelemetry GenAI attributes that Agnost AI reads.

### Install

**Already have an OTel SDK and the OTLP exporter installed?** Skip.

**No OTel yet?**

```bash theme={null}
npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-proto
```

### Setup

#### 1. Export spans to Agnost AI

**Already have a `NodeSDK` or tracer provider?** OpenTelemetry JS 2.x can't add processors after construction. Add this exporter to your existing `spanProcessors` (inside a `BatchSpanProcessor`) where the provider is created.

**No OTel yet?** Load this file before anything else in your app:

```typescript theme={null}
// instrumentation.ts
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';

export const otel = new NodeSDK({
  serviceName: 'my-agentkit-app',
  traceExporter: new OTLPTraceExporter({
    url: 'https://otel.agnost.ai/v1/traces',
    headers: { 'X-Agnost-Org-ID': process.env.AGNOST_ORG_ID! },
  }),
});
otel.start();
```

#### 2. Add the span helpers

```typescript theme={null}
// agnost-tracing.ts
import { SpanStatusCode, trace, type Span, type SpanOptions } from '@opentelemetry/api';
import { createState, type AgentResult, type Network, type Tool } from '@inngest/agent-kit';

const tracer = trace.getTracer('agentkit');

function text(value: unknown): string {
  return typeof value === 'string' ? value : JSON.stringify(value);
}

async function inSpan<T>(name: string, options: SpanOptions, fn: (span: Span) => Promise<T>) {
  return tracer.startActiveSpan(name, options, async (span) => {
    try {
      return await fn(span);
    } catch (error) {
      span.recordException(error as Error);
      span.setStatus({ code: SpanStatusCode.ERROR, message: String(error) });
      throw error;
    } finally {
      span.end();
    }
  });
}

// The last assistant text the network produced.
export function finalText(results: AgentResult[]): string {
  for (const result of [...results].reverse()) {
    for (const message of [...result.output].reverse()) {
      if (message.type === 'text' && message.role === 'assistant') {
        return typeof message.content === 'string'
          ? message.content
          : message.content.map((part) => part.text).join('');
      }
    }
  }
  return '';
}

// One span per user turn: input, reply, conversation, and user.
export function runNetwork(
  network: Network<any>,
  input: string,
  { threadId, userId }: { threadId: string; userId: string },
) {
  return inSpan(
    `invoke_agent ${network.name}`,
    {
      // Start a new trace so the turn is a top-level event in Agnost AI.
      root: true,
      attributes: {
        'gen_ai.operation.name': 'invoke_agent',
        'gen_ai.agent.name': network.name,
        'gen_ai.conversation.id': threadId,
        'enduser.id': userId,
        'input.value': input,
      },
    },
    async (span) => {
      const run = await network.run(input, { state: createState({}, { threadId }) });
      span.setAttribute('output.value', finalText(run.state.results));
      return run;
    },
  );
}

// Wraps a createTool handler so each call becomes a tool event.
export function traceTool<I, O>(
  name: string,
  handler: (input: I, opts: Tool.Options<any>) => O | Promise<O>,
) {
  return (input: I, opts: Tool.Options<any>): Promise<O> => {
    const attributes: Record<string, string> = {
      'gen_ai.operation.name': 'execute_tool',
      'gen_ai.tool.name': name,
      'gen_ai.tool.call.arguments': text(input),
    };
    const threadId = opts.network?.state.threadId;
    if (threadId) attributes['gen_ai.conversation.id'] = threadId;
    return inSpan(`execute_tool ${name}`, { attributes }, async (span) => {
      const result = await handler(input, opts);
      span.setAttribute('gen_ai.tool.call.result', text(result));
      return result;
    });
  };
}
```

#### 3. Use them in your network

Wrap each tool handler in `traceTool()`, and call the network through `runNetwork()`:

```typescript theme={null}
import './instrumentation.js';
import { anthropic, createAgent, createNetwork, createTool } from '@inngest/agent-kit';
import { z } from 'zod';
import { runNetwork, finalText, traceTool } from './agnost-tracing.js';

const getWeather = createTool({
  name: 'get_weather',
  description: 'Get the current weather for a city',
  parameters: z.object({ city: z.string() }),
  handler: traceTool('get_weather', async ({ city }) => `Sunny and 21 C in ${city}`),
});

const supportAgent = createAgent({
  name: 'support-agent',
  system: 'You are a helpful assistant. Answer in one short sentence.',
  model: anthropic({ model: 'claude-haiku-4-5', defaultParameters: { max_tokens: 512 } }),
  tools: [getWeather],
});

const network = createNetwork({
  name: 'support-network',
  agents: [supportAgent],
  maxIter: 5,
  router: ({ callCount, lastResult }) =>
    callCount === 0 || lastResult?.toolCalls.length ? supportAgent : undefined,
});

export async function chat(threadId: string, userId: string, message: string) {
  const run = await runNetwork(network, message, { threadId, userId });
  return finalText(run.state.results);
}
```

Each turn becomes an `invoke_agent` span with the user's message in `input.value` and the reply in `output.value`. `gen_ai.conversation.id` groups turns by `threadId`, and `enduser.id` sets the user. The turn span starts a new trace, so it is a top-level event even when a web framework or Inngest already has a span open. Tool spans run inside the turn span, so each tool call appears under its turn.

#### 4. Inside an Inngest function

The same helpers work when the network runs inside an Inngest function. Load `instrumentation.ts` in the process that serves your functions:

```typescript theme={null}
import { Inngest } from 'inngest';
// ...the imports, tool, agent, and network from step 3

export const inngest = new Inngest({ id: 'support-app' });

export const supportChat = inngest.createFunction(
  { id: 'support-chat', triggers: [{ event: 'support/chat' }] },
  async ({ event }) => {
    const { threadId, userId, message } = event.data;
    const run = await runNetwork(network, message, { threadId, userId });
    return finalText(run.state.results);
  },
);
```

Inngest runs the function handler again after each step, and AgentKit makes each model call a step. Only the final pass finishes the turn span, so each turn is recorded once, but its latency covers only that final pass. AgentKit calls tool handlers outside steps, so a tool can run again on a later pass. Each run is recorded, and `traceTool()` tags it with the `threadId` so it stays in the right conversation. To run a tool once, put its work inside `step.run()` as the [AgentKit multi-step tools guide](https://agentkit.inngest.com/advanced-patterns/multi-steps-tools) shows.

### What appears in Agnost AI

* **Conversations** grouped by `threadId`.
* **User-level analytics** grouped by the `userId` you pass to `runNetwork()`.
* **Events** for each turn (input and reply) and each traced tool call (arguments and result).

### Verify

Send one message that makes the agent call a tool, then a second message with the same `threadId`. Open **Conversations** in Agnost AI. Confirm both turns are in one conversation with your user ID, each turn shows the message and the reply, and the tool event sits under the first turn with its arguments and result.

### Troubleshooting

* **Nothing arrives:** import `instrumentation.ts` before AgentKit, and confirm `AGNOST_ORG_ID` is set in that process. Short scripts must `await otel.shutdown()` before exiting so the last batch is sent.
* **Each turn is its own conversation:** pass the same `threadId` to `runNetwork()` on every turn.
* **Tool calls missing:** wrap every `createTool` handler in `traceTool()`. MCP tools aren't covered by the wrapper.
* **Tool calls appear as separate conversations:** call the network through `runNetwork()`, so tool spans run inside the turn span.
* **Empty reply:** if the network stops after a tool call, the last result has no text. Route back to the agent after tool calls, as the router above does.

### References

* [AgentKit networks](https://agentkit.inngest.com/concepts/networks)
* [AgentKit routers](https://agentkit.inngest.com/concepts/routers)
* [AgentKit tools](https://agentkit.inngest.com/concepts/tools)
* [AgentKit createState](https://agentkit.inngest.com/reference/state)
* [OpenTelemetry GenAI spans](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/)
* [Agnost AI OpenTelemetry endpoint](https://docs.agnost.ai/otel.md)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review each AgentKit thread turn by turn.
* [Events](https://docs.agnost.ai/using-events.md): inspect turns and tool calls.
* [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.