<!-- AI frameworks — Heystack docs. Rendered: https://heystack.dev/docs/ai-frameworks · Index: https://heystack.dev/llms.txt -->
# AI frameworks

**AI & Safety** in the console shows your app's AI calls. It shows:
- how many calls there were and which models they used;
- tokens, cost and failures;
- how long each call took, and how long until the first word on streamed answers;
- the tools each call used;
- the feature or agent that made it.

Where those numbers come from depends on how your app calls the model:
- **On Cloudflare Workers**, the SDK records AI calls by itself.
- **Everywhere else**, you turn on your AI library's own OpenTelemetry output and send it to Heystack.

Heystack reads the formats these libraries use (OpenTelemetry GenAI, the Vercel AI SDK, OpenInference, OpenLLMetry, LiteLLM, Mastra, Pydantic AI and MCP) and shows them the same way.

The recipes below were checked against recordings of each library's real output, except where the table says otherwise.

> **Being rolled out.** Reading the OpenInference, OpenLLMetry, LiteLLM, Mastra, Pydantic AI and MCP formats, and the counting rules on this page, is switching on for organisations in stages. Until it is on for yours, calls from those libraries may not be recognised, or may show under the library's own provider label (for example `openai.chat`).

## What Heystack shows from each source

| Source | What appears | Not shown |
| --- | --- | --- |
| Cloudflare Workers, `@heystack/otel/workers` (automatic) | Calls, model, tokens, cost, errors and latency for `fetch` calls to OpenAI, Anthropic, Mistral, Google and Cloudflare AI Gateway, and for Workers AI. No extra code. See [Cloudflare Workers](https://heystack.dev/docs/cloudflare-workers) | Prompt and answer text unless you turn it on. Tokens and text of streamed Workers AI answers |
| Vercel AI SDK 7, 6 and 5 on Node.js, Next.js on Node or Workers | Calls, model, tokens, cost, errors, latency, time to first word, tools, text, and the feature name from `functionId` | |
| OpenAI Python, official instrumentation (`opentelemetry-instrumentation-openai-v2`) | Calls, model, tokens, cost, errors and latency | Prompt and answer text: this library sends them separately from the call, and Heystack doesn't join them yet |
| Anthropic Python, its own OpenTelemetry output or OpenLLMetry | Calls, model, tokens, cost, errors, latency and text | |
| OpenAI or Anthropic through OpenLLMetry (`opentelemetry-instrumentation-openai` / `-anthropic`), old and current versions | Calls, model, tokens, cost, errors, latency and text | |
| LangChain and LangGraph through OpenInference | Calls, model, tokens, cost, tools, text, and each chain, agent and tool step | LangSmith's own export is not confirmed |
| LlamaIndex through OpenInference | Calls, model, tokens, cost, text, retrieval and embedding steps | |
| OpenAI Agents SDK (Python) through OpenInference | Calls, model, tokens, cost, tools, text, and the agent name as the feature | The JavaScript SDK is not confirmed |
| Mastra (built-in observability export) | Calls, model, tokens, cost, tools, text, time to first word, and the agent name | |
| Pydantic AI (built-in OpenTelemetry output) | Calls, model, tokens, the cost it reports, tools, text, and the agent name | |
| LiteLLM proxy or library (`otel` callback) | Calls, model, tokens, the cost LiteLLM reports, text, and which team or key made the call. See [AI gateways](https://heystack.dev/docs/ai-gateways) | |
| MCP servers (the MCP Python SDK's OpenTelemetry output) | Each tool call, with its tool name, errors and latency | |
| AWS Bedrock on Node.js (the AWS SDK instrumentation) | Calls, model, tokens, errors and latency. Bedrock model ids show **No price** | Text: the instrumentation doesn't send it. Python (botocore) is not confirmed |
| Vercel AI Gateway (the AI SDK `gateway` provider) | As for the AI SDK, with the real provider (for example OpenAI) and the cost the gateway reports | |
| Cloudflare AI Gateway | Through `@heystack/otel/workers`: as for Workers, with the real provider (for example OpenAI, not "Cloudflare"). Its own logs and export: see [AI gateways](https://heystack.dev/docs/ai-gateways) | |
| Google Vertex AI, Azure OpenAI, OpenRouter, Groq, Together, xAI, DeepSeek | Not confirmed. Anything that sends OpenTelemetry GenAI attributes (`gen_ai.*`) is read; see [Any other framework](#any-other-framework) | |

Cost is the amount the source reports when it reports one. Otherwise it is an estimate from public prices, or **No price** when Heystack doesn't know the model's price. A model with no price is never counted as $0. Heystack measures the cost, speed and failures of AI calls; it does not score answer quality.

**Each call is counted once.** Heystack counts only the model call itself. It doesn't count the agent run or step that wraps the call, and it doesn't count a second record of the same call from another layer. For example, with `@heystack/otel/workers` and the AI SDK both on, the call is counted once. Read-only keys never see prompt or answer text, whichever library sent it.

**Setup check tells you when something is missing.** If your app calls a known AI provider but Heystack receives no AI details for those calls, **Settings › App** shows "Your app is calling OpenAI but Heystack isn't receiving AI details", with a link back to this page.

## Next.js or Node.js with the Vercel AI SDK

1. Set up the SDK as in the [Next.js](https://heystack.dev/docs/nextjs) or [Node.js](https://heystack.dev/docs/nodejs) guide. In Next.js:

   ```ts
   // instrumentation.ts
   export async function register() {
     const { registerHeystack } = await import("@heystack/otel/next");
     await registerHeystack({ service: "my-app" }); // apiKey from process.env.HEYSTACK_API_KEY
   }
   ```

   In a Node.js server, as the very first import:

   ```ts
   import { initHeystack } from "@heystack/otel/node";

   initHeystack({ apiKey: process.env.HEYSTACK_API_KEY, service: "my-app" });
   ```

2. **AI SDK 7:** install `@ai-sdk/otel` and register its integration once at startup. Then name the feature on each call with `telemetry.functionId`, so you can tell calls apart. In version 7, `experimental_telemetry` on its own sends nothing.

   ```bash
   npm install @ai-sdk/otel
   ```

   ```ts
   import { generateText, registerTelemetry } from "ai";
   import { OpenTelemetry } from "@ai-sdk/otel";
   import { openai } from "@ai-sdk/openai";

   registerTelemetry(new OpenTelemetry()); // once, at startup

   const { text } = await generateText({
     model: openai("gpt-4o-mini"),
     prompt: question,
     telemetry: { functionId: "support-answer" },
   });
   ```

   `streamText`, `generateObject`, `streamObject` and tool calls take the same `telemetry` option.

   **AI SDK 5 and 6:** turn on telemetry on each call instead:

   ```ts
   const { text } = await generateText({
     model: openai("gpt-4o-mini"),
     prompt: question,
     experimental_telemetry: { isEnabled: true, functionId: "support-answer" },
   });
   ```

### On Cloudflare Workers

`@heystack/otel/workers` already records each `fetch` to the provider. If you also turn on the AI SDK's telemetry, as in step 2, you get tools, steps and the feature name too, and the call is still counted once.

Keep **one copy of `@opentelemetry/api`** in your Worker bundle. If `@ai-sdk/otel` and `@heystack/otel` resolve different versions, the AI SDK's records are silently dropped. Check with `npm ls @opentelemetry/api`. If two versions appear, pin one with `overrides` (npm) or `pnpm.overrides`.

AI capture for Next.js on Cloudflare (OpenNext) is not confirmed yet.

## Python

There is no Heystack Python package. Use the standard OpenTelemetry SDK, and send OTLP/HTTP to `https://ingest.heystack.dev` with your server key:

```bash
pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
```

```python
import os

from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

provider = TracerProvider(resource=Resource.create({
    "service.name": "my-python-app",
    "service.version": "1.4.0",            # your release
    "deployment.environment": "production",
}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(
    endpoint="https://ingest.heystack.dev/v1/traces",
    headers={"Authorization": f"Bearer {os.environ['HEYSTACK_API_KEY']}"},
)))
trace.set_tracer_provider(provider)
```

Run this once at startup, before your app creates its AI client. Keep the server key (`sk_live_…`) in an environment variable. Heystack accepts both protobuf (the Python exporter's default) and JSON.

Then turn on **one** instrumentation for your library:

| Library | Install | Turn on |
| --- | --- | --- |
| OpenAI | `opentelemetry-instrumentation-openai-v2` | `from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor`; `OpenAIInstrumentor().instrument()` |
| OpenAI or Anthropic (OpenLLMetry, includes text) | `opentelemetry-instrumentation-openai` or `opentelemetry-instrumentation-anthropic` | `OpenAIInstrumentor().instrument()` / `AnthropicInstrumentor().instrument()` from `opentelemetry.instrumentation.openai` / `.anthropic` |
| LangChain, LangGraph | `openinference-instrumentation-langchain` | `from openinference.instrumentation.langchain import LangChainInstrumentor`; `LangChainInstrumentor().instrument()` |
| LlamaIndex | `openinference-instrumentation-llama-index` | `LlamaIndexInstrumentor().instrument()` from `openinference.instrumentation.llama_index` |
| OpenAI Agents SDK | `openinference-instrumentation-openai-agents` | `OpenAIAgentsInstrumentor().instrument()` from `openinference.instrumentation.openai_agents` |
| Pydantic AI (2.x) | nothing extra | `Agent(..., capabilities=[Instrumentation()])` (from `pydantic_ai.capabilities.instrumentation`), or `Agent.instrument_all()` |
| MCP server | nothing extra | The MCP Python SDK sends OpenTelemetry once a tracer provider is set |
| LiteLLM | nothing extra | `litellm.callbacks = ["otel"]`, or `callbacks: ["otel"]` in the proxy config. See [AI gateways](https://heystack.dev/docs/ai-gateways#litellm) |

For the Anthropic SDK you need nothing extra. Recent versions send OpenTelemetry by themselves once a tracer provider is set. To include prompt and answer text, set `ANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE=content`.

> **Anthropic: turn on one instrumentation, not two.** Recent versions of the Anthropic Python SDK send OpenTelemetry themselves. If OpenLLMetry's Anthropic instrumentation is also on, each call is recorded twice, and the two records aren't linked. Heystack merges the pair when both arrive in the same upload, but not across uploads, so a call can be counted twice. Keep one.

> **MCP: report a tool call from one side.** If both your MCP client and your MCP server send OpenTelemetry, each tool call is recorded twice (once by each side) and counted twice in tool counts. Turn it on in one of them.

## Node.js with Mastra

Mastra's observability export works as it is. Point its OpenTelemetry exporter at Heystack:

```ts
import { Mastra } from "@mastra/core";
import { Observability } from "@mastra/observability";
import { OtelExporter } from "@mastra/otel-exporter";

export const mastra = new Mastra({
  agents: { weatherAgent },
  observability: new Observability({
    configs: {
      heystack: {
        serviceName: "my-app",
        exporters: [new OtelExporter({
          provider: {
            custom: {
              endpoint: "https://ingest.heystack.dev/v1/traces",
              protocol: "http/json",
              headers: { Authorization: `Bearer ${process.env.HEYSTACK_API_KEY}` },
            },
          },
        })],
      },
    },
  }),
});
```

## Any other framework

If your framework or its instrumentation sends OpenTelemetry GenAI attributes (`gen_ai.*`), point its OTLP/HTTP exporter at `https://ingest.heystack.dev` with `Authorization: Bearer <server key>`. If you already run an OpenTelemetry Collector, add Heystack as an exporter instead: see [OpenTelemetry Collector](https://heystack.dev/docs/collector).

## Safety checks next to a model call

[Heystack Security](https://heystack.dev/docs/security) runs your published AI safety policy inside your app with `@heystack/guard` (0.2.0 or later). Your app fetches a signed policy outside the request path, checks each message in-process, and calls the provider directly: Heystack is never in the path between your app and the model. Your app owns the boundary: it decides which messages to check, and what the person sees when a message is blocked. A block throws `HeystackBlockedError`; a redaction returns the cleaned text as `content`, and that is what you send on, never the original.

Both recipes use an AI safety runtime key (`hg_live_…`, created under **Settings › App › Connection & keys**) and a policy published for this app, for the profile and environment you name. Use the profile name your policy was created with; an app with no published policy of its own gets no policy to check against.

The recipes use the profile `chat`. The console's **Create policy** and runtime-key form currently offer only a fixed list of profile names (`voice-live`, `enrichment`, `moderation`, `voice-clone`), and a runtime key can fetch only the profiles it was created for. To use `chat`, create both through the API as an admin: the policy with `POST /api/security/policies` (`{app_id, deployment_environment, profile: "chat", config}`; it then appears under **Settings › App › AI safety policy**, where you publish it as usual), and the key with `POST /api/security/keys` (`{app_id, deployment_environment, allowed_profiles: ["chat"]}`, using the same `deployment_environment` as the policy; it answers `201 {id, key, prefix}`, and the `hg_live_…` key is shown only in that response); see [API](https://heystack.dev/docs/api). Or pick a listed name in the console and use it for `PROFILE` here. If there is no published policy for that profile (or the key isn't allowed it), `guard.policy()` throws a `HeystackPolicyError` instead of returning an empty policy, so at startup your app fails loudly rather than running unchecked. After a policy has loaded once, a failed refresh keeps the last good policy only until it expires.

```bash
npm install "@heystack/guard@>=0.2.0"
```

### A plain OpenAI or Anthropic call

```ts
import OpenAI from "openai";
import { createGuard, HeystackBlockedError } from "@heystack/guard";

const guard = createGuard({
  endpoint: "https://guard.heystack.dev",
  key: process.env.HEYSTACK_GUARD_KEY!, // hg_live_…
  defaultEnvironment: "production",
});
const openai = new OpenAI();
const PROFILE = "chat"; // the profile your policy uses

// Outside the request path: at startup, then refresh on a timer.
// If a refresh fails, the last good policy is kept until it expires.
let policy = await guard.policy(PROFILE);
setInterval(() => {
  guard.policy(PROFILE).then((next) => { policy = next; }, () => undefined);
}, 60_000);

export async function answer(userId: string, question: string): Promise<string> {
  const request = {
    profile: PROFILE,
    deployment_environment: "production",
    surface: "input" as const,
    source_trust: "user" as const,
    user_id: userId,
    content: question,
  };
  let content: string | undefined;
  try {
    ({ content } = guard.enforceLocal(policy, request));
  } catch (error) {
    if (error instanceof HeystackBlockedError) return "Sorry, I can't help with that."; // your app decides
    throw error;
  }

  // Review by a model, when your policy turns it on: started alongside the provider
  // call and never awaited before it.
  const controller = new AbortController();
  if (policy.config.rules.model_judge?.enabled) {
    guard.startConcurrentReview({ ...request, content }, { policy, abortController: controller })
      .catch(() => undefined); // a failed review that should stop the call has already aborted it
  }

  const completion = await openai.chat.completions.create(
    { model: "gpt-4o-mini", messages: [{ role: "user", content: content ?? "" }] },
    { signal: controller.signal },
  );
  return completion.choices[0]?.message.content ?? "";
}
```

An Anthropic call has the same shape: check the message with `enforceLocal`, send the returned `content` to `anthropic.messages.create`, and pass the controller's `signal` in the request options.

### Vercel AI SDK middleware

Check every user message before the model sees it by wrapping the model. `guard`, `policy` and `PROFILE` are set up as in the recipe above.

```ts
import { generateText, wrapLanguageModel } from "ai";
import { openai } from "@ai-sdk/openai";
import { HeystackBlockedError } from "@heystack/guard";

const guardedModel = wrapLanguageModel({
  model: openai("gpt-4o-mini"),
  middleware: {
    transformParams: async ({ params }) => ({
      ...params,
      prompt: params.prompt.map((message) => message.role !== "user" ? message : {
        ...message,
        content: message.content.map((part) => {
          if (part.type !== "text") return part;
          // Throws HeystackBlockedError on a block; returns the redacted text on a redaction.
          const { content } = guard.enforceLocal(policy, {
            profile: PROFILE,
            deployment_environment: "production",
            surface: "input",
            source_trust: "user",
            content: part.text,
          });
          return { ...part, text: content ?? "" };
        }),
      }),
    }),
  },
});

try {
  const { text } = await generateText({ model: guardedModel, prompt: question });
} catch (error) {
  if (error instanceof HeystackBlockedError) {
    // your app decides what the person sees
  } else {
    throw error;
  }
}
```

The check runs in your process and adds no network round trip. Recipes for LangChain and the OpenAI Agents SDK are not available yet.
