---
source: ⚠️ Jupyter Notebook
title: Observability for TypeSafe Jev JS/TS with Langfuse
sidebarTitle: TypeSafe (Jev JS/TS)
logo: /images/integrations/typesafe_icon.png
description: Trace TypeSafe Jev System One calls from the JavaScript SDK with Langfuse by wrapping systemOne in observe() and exporting spans through LangfuseSpanProcessor.
category: Integrations
---

# Observability for TypeSafe Jev JS/TS with Langfuse

<a href="https://langfuse.com/integrations/model-providers/typesafe"><img className="inline" alt="Python" src="https://img.shields.io/badge/Python-3776AB?style=flat&logo=python&logoColor=white" /></a> <a href="https://langfuse.com/integrations/model-providers/typesafe-js"><img className="inline" alt="JS/TS" src="https://img.shields.io/badge/JS/TS-d4d4d8?style=flat&logo=javascript&logoColor=white" /></a>

This notebook shows how to trace **TypeSafe** [Jev](https://typesafe.ai/blog/introducing-system-one-models-and-jev) System One calls from the [JavaScript SDK](https://docs.typesafe.ai/sdk/javascript) with **Langfuse**. `@typesafe-ai/sdk` has no OpenTelemetry hook, and there is no `@arizeai/openinference-instrumentation-typesafe`. Wrap `systemOne` with Langfuse `observe()` and register `LangfuseSpanProcessor` so the generation actually exports.

> **What is TypeSafe Jev?** [Jev](https://docs.typesafe.ai/introduction) is TypeSafe's System One model. You send state plus typed [Choice](https://docs.typesafe.ai/primitives/choice), [Score](https://docs.typesafe.ai/primitives/score), and [Noul](https://docs.typesafe.ai/primitives/noul) questions; it returns structured answers with probabilities. It does not generate text. Official [Python](https://docs.typesafe.ai/sdk/python) and [JavaScript](https://docs.typesafe.ai/sdk/javascript) SDKs wrap `POST /v1/systemone`.

> **What is Langfuse?** [Langfuse](https://langfuse.com) is an open-source LLM engineering platform that helps teams trace, debug, and evaluate LLM applications. Use [Langfuse Cloud](https://langfuse.com/cloud) or [self-host](https://langfuse.com/self-hosting) it.

<Steps>
## Step 1: Install Dependencies

Install the TypeSafe JavaScript SDK, the Langfuse tracing packages, and the OpenTelemetry Node SDK. Node.js 20 or newer is required.

```bash
npm install @typesafe-ai/sdk @langfuse/tracing @langfuse/otel @opentelemetry/sdk-node
```

## Step 2: Set Up Environment Variables

Get your Langfuse keys from the project settings in [Langfuse Cloud](https://langfuse.com/cloud) or set up [self-hosting](https://langfuse.com/self-hosting). Get a TypeSafe API key from the [TypeSafe console](https://console.typesafe.ai/settings/keys).

```bash
# Get keys from your project settings: https://langfuse.com/cloud
export LANGFUSE_PUBLIC_KEY="pk-lf-..."
export LANGFUSE_SECRET_KEY="sk-lf-..."
export LANGFUSE_BASE_URL="https://cloud.langfuse.com" # 🇪🇺 EU region (API host)
# Other Langfuse data regions include 🇺🇸 US: https://us.cloud.langfuse.com, 🇯🇵 Japan: https://jp.cloud.langfuse.com and ⚕️ HIPAA: https://hipaa.cloud.langfuse.com

export TYPESAFE_API_KEY="sk-..." # https://console.typesafe.ai/settings/keys
```

## Step 3: Initialize OpenTelemetry with Langfuse

`observe()` only creates spans. They do not reach Langfuse until you register [`LangfuseSpanProcessor`](/docs/observability/sdk/overview#setup) on a Node OpenTelemetry SDK and start that SDK **before** any `systemOne` call.

```typescript
// instrumentation.ts
import { NodeSDK } from "@opentelemetry/sdk-node";
import { LangfuseSpanProcessor } from "@langfuse/otel";

export const sdk = new NodeSDK({
  spanProcessors: [new LangfuseSpanProcessor()],
});

sdk.start();
```

Import this file at the top of your app entry point so the processor is registered before you create observations.

## Step 4: Wrap `systemOne` with `observe()`

Wrap `client.systemOne` with [`observe()`](/docs/observability/sdk/instrumentation#observe-wrapper). Use `asType: "generation"` so Langfuse stores the call as a generation. Keep the `SystemOneRequest<Q>` generic so TypeSafe still infers `response.answers` from your questions. `observe()` captures the request and response automatically. Pass `{ asType: "generation" }` to `updateActiveObservation()` after the SDK returns so the generation also gets the resolved model name and token usage.

Ask Jev three questions about one ticket: a yes/no (Noul), a label (Choice), and a rubric (Score). The same shape covers tool routers, compaction gates, and eval verdicts. Pin `jev-1.13.0` when a threshold depends on a specific model version; `jev-latest` moves when TypeSafe ships a new release.

```typescript
// index.ts
import { sdk } from "./instrumentation";
import { observe, updateActiveObservation } from "@langfuse/tracing";
import {
  TypeSafeClient,
  noul,
  choice,
  score,
  type Questions,
  type SystemOneRequest,
} from "@typesafe-ai/sdk";

const client = new TypeSafeClient({ defaultModel: "jev-1.13.0" });

const systemOne = observe(
  async <Q extends Questions>(request: SystemOneRequest<Q>) => {
    const response = await client.systemOne(request);
    updateActiveObservation(
      {
        model: response.model,
        usageDetails: {
          input: response.usage.input_tokens,
          output: response.usage.output_tokens,
        },
      },
      { asType: "generation" },
    );
    return response;
  },
  { name: "typesafe-system-one", asType: "generation" },
);

async function main() {
  const response = await systemOne({
    state: { document: "I was charged twice. Please fix this ASAP." },
    questions: {
      billing: noul("Is this ticket about billing?"),
      tone: choice("What is the customer's tone?", {
        calm: null,
        frustrated: null,
        angry: null,
      }),
      urgency: score("How urgent is this ticket?", [
        "can wait",
        "this week",
        "today",
      ]),
    },
  });

  console.log(response.model);
  console.log(response.answers.billing.noul);
  console.log(response.answers.tone.choice, response.answers.tone.confidence);
  console.log(response.answers.urgency.score, response.answers.urgency.confidence);
}

main().finally(() => sdk.shutdown());
```

Run the script with `npx tsx index.ts`. `sdk.shutdown()` flushes buffered spans. That call is required in short-lived scripts; a long-running server can skip it until process exit.

To write Jev verdicts back onto Langfuse traces as scores, see [Using TypeSafe's Jev for evals](/blog/2026-09-18-using-typesafes-jev-for-evals).

## Step 5: View Traces in Langfuse

After running the example, open [Langfuse Cloud](https://langfuse.com/cloud) to see the System One generation: request `state` and questions, typed answers with probabilities, token usage, and latency.

![TypeSafe Jev System One trace from the JavaScript SDK in Langfuse](https://langfuse.com/images/cookbook/integration-typesafe/typesafe-example-trace-js.png)

[Example trace in Langfuse](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/45498ea8f1e000c6b112960bfbe63f76?observation=c6ac8287d7cc7837&timestamp=2026-09-22T15:13:29.994Z)

</Steps>

## Interoperability with the JS/TS SDK

You can use this integration together with the Langfuse [SDKs](/docs/observability/sdk/overview) to add additional attributes or group observations into a single trace.

<Tabs items={["Context Manager", "Observe Wrapper"]}>
<Tab>

The [Context Manager](/docs/observability/sdk/instrumentation#context-management-with-callbacks) allows you to wrap your instrumented code using context managers (with `with` statements), which allows you to add additional attributes to the trace. Any observation created inside the callback will automatically be nested under the active observation, and the observation will be ended when the callback finishes.

```typescript
import { startActiveObservation, propagateAttributes } from "npm:@langfuse/tracing";

await startActiveObservation("context-manager", async (span) => {
  span.update({
    input: { query: "What is the capital of France?" },
  });

  // Propagate userId to all child observations
  await propagateAttributes(
    {
      userId: "user-123",
      sessionId: "session-123",
      metadata: {
        source: "api",
        region: "us-east-1",
      },
      tags: ["api", "user"],
      version: "1.0.0",
    },
    async () => {

      // YOUR CODE HERE
      const { text } = await generateText({
        model: openai("gpt-5"),
        prompt: "What is the capital of France?",
        experimental_telemetry: { isEnabled: true },
      });
    }
  );
  span.update({ output: "Paris" });
});
```

Learn more about using the Context Manager in the [Langfuse SDK instrumentation docs](https://langfuse.com/docs/observability/sdk/instrumentation#context-management-with-callbacks).

</Tab>
<Tab>

The [`observe` wrapper](/docs/observability/sdk/instrumentation#observe-wrapper) is a powerful tool for tracing existing functions without modifying their internal logic. It acts as a decorator that automatically creates a span or generation around the function call. You can use the `propagateAttributes` function to add attributes to the observation from within the wrapped function.

```typescript
import { observe, propagateAttributes } from "@langfuse/tracing";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";

// An existing function
const processUserRequest = observe(
  async (userQuery: string) => {

    // Propagate attributes to all child observations
    return await propagateAttributes(
      {
        userId: "user-123",
        sessionId: "session-123",
        metadata: {
          source: "api",
          region: "us-east-1",
        },
        tags: ["api", "user"],
        version: "1.0.0",
      },
      async () => {

        // YOUR CODE HERE
        const { text } = await generateText({
          model: openai("gpt-5"),
          prompt: userQuery,
          experimental_telemetry: { isEnabled: true },
        });

        return text;
      }
    );
  },
  { name: "process-user-request" }
);

const result = await processUserRequest("some query");
```

Learn more about using the Decorator in the [Langfuse SDK instrumentation docs](/docs/observability/sdk/instrumentation#observe-wrapper).

</Tab>
</Tabs>

## Troubleshooting

<details>
<summary>No traces appearing</summary>

First, enable [debug mode](/docs/observability/sdk/advanced-features#logging--debugging) in the JS/TS SDK:

```bash
export LANGFUSE_LOG_LEVEL="DEBUG"
```

Then run your application and check the debug logs:

- **OTel spans appear in the logs:** Your application is instrumented correctly but traces are not reaching Langfuse. To resolve this:
  1. Call [`forceFlush()`](/docs/observability/sdk/instrumentation#client-lifecycle--flushing) at the end of your application to ensure all traces are exported. This is especially important in short-lived environments like serverless functions.
  2. Verify that you are using the correct API keys and base URL.
- **No OTel spans in the logs:** Your application is not instrumented correctly. Make sure the instrumentation runs before your application code.

</details>

<details>
<summary>Unwanted observations in Langfuse</summary>

The Langfuse SDK is based on OpenTelemetry. Other libraries in your application may emit OTel spans that are not relevant to you. These still count toward your [billable units](/docs/administration/billable-units), so you should filter them out. See [Unwanted spans in Langfuse](/faq/all/unwanted-http-database-spans) for details.

</details>

<details>
<summary>Missing attributes</summary>

Some attributes may be stored in the metadata object of the observation rather than being mapped to the Langfuse data model. If a mapping or integration does not work as expected, please [raise an issue on GitHub](/issues).

</details>

## Next Steps

Once you have instrumented your code, you can manage, evaluate and debug your application:

- [Manage prompts in Langfuse](/docs/prompt-management/get-started)
- [Add evaluation scores](/docs/evaluation/evaluation-methods/scores-via-sdk)
- [Run LLM-as-a-judge Evaluators](/docs/evaluation/evaluation-methods/llm-as-a-judge)
- [Create datasets](/docs/evaluation/experiments/datasets)
- [Create custom dashboards](/docs/metrics/features/custom-dashboards)
- [Test queries in the Playground](/docs/prompt-management/features/playground)

<!-- agent-instructions -->

---

## Agent Instructions

This page is part of the [Langfuse](https://langfuse.com) documentation, published as plain Markdown for AI agents. Every page is available as Markdown by appending `.md` to its URL, or by sending an `Accept: text/markdown` header. This page: `https://langfuse.com/integrations/model-providers/typesafe-js.md`.

### Querying these docs

If the answer is not on this page, query the documentation instead of guessing:

- **Semantic search** across all Langfuse docs, returning an answer with the relevant pages and excerpts. Ask a specific, self-contained question:

  ```bash
  curl -sG "https://langfuse.com/api/search-docs" --data-urlencode "query=How do I trace a LangGraph agent?"
  ```

- **Index of every page**: <https://langfuse.com/llms.txt>, with per-section indexes [llms-docs.txt](https://langfuse.com/llms-docs.txt), [llms-integrations.txt](https://langfuse.com/llms-integrations.txt), and [llms-self-hosting.txt](https://langfuse.com/llms-self-hosting.txt).

### Before writing Langfuse code

- **Install the [Langfuse Agent Skill](https://langfuse.com/docs/api-and-data-platform/features/agent-skill).** It encodes Langfuse's own best practices for instrumentation, prompt management, and evaluation, and materially improves results.
- **Read [What does a good trace look like?](https://langfuse.com/docs/observability/best-practices.md)** before instrumenting an application.
- **Verify endpoints, parameters, and response fields** against the [API reference](https://api.reference.langfuse.com) instead of inferring them from code examples.
- **Use the [Langfuse CLI](https://langfuse.com/docs/api-and-data-platform/features/cli)** (`npx @langfuse/cli api <resource> <action>`) to read or write traces, prompts, datasets, and scores from the terminal.

Found an error in these docs? Please open an issue at <https://github.com/langfuse/langfuse-docs/issues>.
