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

# Letta

> Capture Letta agent turns, replies, and tool calls in Agnost AI

## 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 Letta application.
Org ID: your-org-id
Instrument the real session.send() and session.stream() turn and verify one fresh interaction.
```

## Manual setup: Agnost AI SDK

Letta applications talk to agents through the Letta Agent SDK (`@letta-ai/letta-agent-sdk`).
Each turn is one `session.send()` followed by one `session.stream()` loop that ends with a
`result` message. Wrap that turn with `agnost.begin()` and `interaction.end()`.

```bash theme={null}
npm install @letta-ai/letta-agent-sdk agnostai
```

```typescript theme={null}
import * as agnost from "agnostai";
import { LettaAgentClient, type AnyAgentTool } from "@letta-ai/letta-agent-sdk";

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

const client = new LettaAgentClient({
  backend: "cloud",
  apiKey: process.env.LETTA_API_KEY,
});

// Optional: a client tool that runs in your process.
const getWeather = {
  label: "Get weather",
  name: "get_weather",
  description: "Get the current weather for a city.",
  parameters: {
    type: "object",
    properties: { city: { type: "string" } },
    required: ["city"],
  },
  async execute(_toolCallId, args) {
    const { city } = args as { city: string };
    return { content: [{ type: "text" as const, text: `It is sunny and 22 C in ${city}.` }] };
  },
} satisfies AnyAgentTool;

export async function runTurn(agentId: string, userId: string, chatId: string, prompt: string) {
  const interaction = agnost.begin({
    userId,
    agentName: "letta-support",
    input: prompt,
    conversationId: chatId, // your chat or thread ID; groups turns into one conversation
  });
  if (!interaction) throw new Error("Agnost is not initialized. Call agnost.init() first.");

  const toolNames = new Map<string, string>();
  try {
    await using session = client.resumeSession(agentId, {
      tools: [getWeather],
      canUseTool: async (toolName) =>
        toolName === "get_weather" ? { behavior: "allow" } : { behavior: "deny", message: "not allowed" },
    });
    await session.send(prompt);

    for await (const message of session.stream()) {
      if (message.type === "tool_call") {
        toolNames.set(message.toolCallId, message.toolName);
      }
      if (message.type === "result") {
        interaction.setProperties({
          "letta.agent_id": agentId,
          "letta.conversation_id": message.conversationId ?? "",
          "letta.tools": [...new Set(toolNames.values())].join(","),
        });
        if (message.success) {
          interaction.end(message.result ?? "");
        } else {
          interaction.end(message.errorCode ?? "letta turn failed", false);
        }
        return message.result;
      }
    }
    interaction.end("stream ended without a result", false);
  } catch (error) {
    interaction.end(String(error), false);
    throw error;
  }
}
```

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

What this records for each turn:

* the user message as input and the turn's final assistant text (`result.result`) as output
* `success: false` with the Letta `errorCode` when the turn fails, for example `llm_api_error`, `max_steps`, or `approval_conflict`
* the Letta agent ID, the Letta conversation ID, and the names of the tools the agent called, as event properties

The same code works with `backend: "local"` (the SDK starts Letta Code on the same machine) and
`backend: "remote"` (your own Letta App Server). Only the `LettaAgentClient` options change.

Tool calls stream as several `tool_call` fragments that share one `toolCallId`, which is why the
example keys tool names by `toolCallId`. Custom tools need approval in the default `standard`
permission mode, so the example allows `get_weather` through `canUseTool`. Without that, the turn
ends with `errorCode: "approval_conflict"`, which the example records as a failed interaction.

## Why there is no OpenTelemetry section

Letta Code, the runtime behind the Agent SDK, the CLI, and the App Server, does not export
OpenTelemetry traces. The OpenTelemetry support in the older Python Letta server went away when
that server was retired to the `archive` branch of `letta-ai/letta`. OpenLIT's Letta instrumentation
patches module paths from the old `letta-client` 0.x Python client, which the current 1.x client no
longer has. Use the Agnost AI SDK wrapper above.

## Verify and troubleshoot

### Verify

Run one turn, then open **Conversations** in Agnost AI and find the `chatId` you passed. Confirm
the event shows your user ID, the prompt as input, the assistant reply as output, and
`letta.tools` listing any tool the agent called.

### Troubleshooting

* No events: confirm `agnost.init("your-org-id")` runs before the first turn, and that the process calls `await agnost.shutdown()` before it exits.
* Output is empty: read the reply from the `result` message (`message.result`). `assistant` messages carry text fragments, not the whole reply.
* Failed events with `approval_conflict`: a tool needed approval. Approve it in `canUseTool` or set a `permissionMode` that fits your app.
* Every turn is a separate conversation: pass the same `conversationId` to `agnost.begin()` for every turn in one chat.
* Python apps: the Letta Agent SDK is TypeScript only. Wrap your own turn boundary with the [Python SDK](https://docs.agnost.ai/python-conversation.md) in the same way.

### References

* [Letta Agent SDK quickstart](https://docs.letta.com/agent-sdk/quickstart)
* [Sending messages and message types](https://docs.letta.com/agent-sdk/messages)
* [MCP and client tools](https://docs.letta.com/agent-sdk/mcp)
* [Permissions](https://docs.letta.com/agent-sdk/permissions)
* [Self-hosting and the local backend](https://docs.letta.com/self-hosting)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review each Letta turn in context.
* [Events](https://docs.agnost.ai/using-events.md): inspect inputs, outputs, and tool properties.
* [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.