### Start NodeSDK and Instrument AI SDK Calls Source: https://docs.thecontext.company/frameworks/ai-sdk/setup Demonstrates starting the OpenTelemetry NodeSDK with the `TCCSpanProcessor` and then making AI SDK calls with telemetry enabled. Includes examples for basic usage and integration with an Express server. ```typescript import { generateText } from "ai"; import { tcc } from "./tcc"; // Start listening for traces tcc.start(); async function main() { const result = await generateText({ // ... experimental_telemetry: { isEnabled: true }, // required }); } ``` ```typescript import { streamText } from "ai"; import express, { Request, Response } from "express"; import { tcc } from "./tcc"; const app = express(); // Start listening for traces tcc.start(); app.post("/", async (req: Request, res: Response) => { const result = streamText({ // ... experimental_telemetry: { isEnabled: true }, // required }); result.pipeUIMessageStreamToResponse(res); }); app.listen(8080, () => { console.log(`Server listening on port ${8080}`); }); ``` -------------------------------- ### Install LangChain Observability Dependencies (poetry) Source: https://docs.thecontext.company/frameworks/langchain Installs the necessary Python package for LangChain observability using poetry. ```bash poetry add "tcc-otel[langchain]" ``` -------------------------------- ### Install Dependencies (npm) Source: https://docs.thecontext.company/frameworks/ai-sdk/local Installs the necessary @contextcompany/otel, @vercel/otel, and @opentelemetry/api packages using npm. ```bash npm i @contextcompany/otel @vercel/otel @opentelemetry/api ``` -------------------------------- ### Install LangChain Observability Dependencies (pip) Source: https://docs.thecontext.company/frameworks/langchain Installs the necessary Python package for LangChain observability using pip. ```bash pip install "tcc-otel[langchain]" ``` -------------------------------- ### Install Mastra Dependencies (pnpm, npm) Source: https://docs.thecontext.company/frameworks/mastra/setup Installs the necessary Mastra package for your project using either pnpm or npm. This package provides the core functionality for integrating with The Context Company. ```shell pnpm add @contextcompany/mastra ``` ```shell npm i @contextcompany/mastra ``` -------------------------------- ### Install Claude Agent SDK Dependencies Source: https://docs.thecontext.company/frameworks/claude-agent-sdk/setup Install the necessary packages for integrating The Context Company's SDK with the Claude Agent SDK. Supports both pnpm and npm package managers. ```pnpm pnpm add @contextcompany/claude @anthropic-ai/claude-agent-sdk ``` ```npm npm i @contextcompany/claude @anthropic-ai/claude-agent-sdk ``` -------------------------------- ### Install Dependencies (pnpm) Source: https://docs.thecontext.company/frameworks/ai-sdk/local Installs the necessary @contextcompany/otel, @vercel/otel, and @opentelemetry/api packages using pnpm. ```bash pnpm add @contextcompany/otel @vercel/otel @opentelemetry/api ``` -------------------------------- ### Install Dependencies for Next.js and Node.js Source: https://docs.thecontext.company/frameworks/vercel Installs the necessary packages for instrumenting AI SDK calls with The Context Company. This includes the `@contextcompany/otel` package and OpenTelemetry core packages. ```bash pnpm add @contextcompany/otel @vercel/otel @opentelemetry/api ``` ```bash npm add @contextcompany/otel @vercel/otel @opentelemetry/api ``` -------------------------------- ### Install AI SDK Dependencies (Node.js) Source: https://docs.thecontext.company/frameworks/ai-sdk/setup Installs the necessary packages for AI SDK instrumentation in a Node.js application using either pnpm or npm. ```shell pnpm add @contextcompany/otel @opentelemetry/sdk-node @opentelemetry/api ``` ```shell npm i @contextcompany/otel @opentelemetry/sdk-node @opentelemetry/api ``` -------------------------------- ### Install Dependencies for Node.js Source: https://docs.thecontext.company/frameworks/vercel Installs the necessary packages for instrumenting AI SDK calls within a Node.js environment. This includes the `@contextcompany/otel` package and OpenTelemetry Node.js SDK components. ```bash pnpm add @contextcompany/otel @opentelemetry/sdk-node @opentelemetry/api ``` ```bash npm add @contextcompany/otel @opentelemetry/sdk-node @opentelemetry/api ``` -------------------------------- ### Install AI SDK Dependencies (Next.js) Source: https://docs.thecontext.company/frameworks/ai-sdk/setup Installs the necessary packages for AI SDK instrumentation in a Next.js application using either pnpm or npm. ```shell pnpm add @contextcompany/otel @vercel/otel @opentelemetry/api ``` ```shell npm i @contextcompany/otel @vercel/otel @opentelemetry/api ``` -------------------------------- ### Start OpenTelemetry NodeSDK and Instrument AI SDK Calls Source: https://docs.thecontext.company/frameworks/vercel Starts the OpenTelemetry `NodeSDK` with the configured `TCCSpanProcessor` and demonstrates how to instrument AI SDK calls within a Node.js application. This ensures that traces generated by AI SDK calls are captured and sent to The Context Company. ```typescript import { generateText } from "ai"; import { tcc } from "./tcc"; // Start listening for traces tcc.start(); async function main() { const result = await generateText({ // ... experimental_telemetry: { isEnabled: true }, // required }); } ``` -------------------------------- ### Instrument Claude Agent SDK with The Context Company Source: https://docs.thecontext.company/frameworks/claude-agent-sdk/setup Wrap the Claude Agent SDK with the `instrumentClaudeAgent` function from The Context Company's SDK. This enables automatic export of agent-related traces to The Context Company platform. ```typescript import { instrumentClaudeAgent } from "@contextcompany/claude"; import * as claudeSDK from "@anthropic-ai/claude-agent-sdk"; const { query, tool, createSdkMcpServer } = instrumentClaudeAgent(claudeSDK); // Now use query, tool, and createSdkMcpServer as you normally would ``` -------------------------------- ### Install LangGraph Observability Dependencies Source: https://docs.thecontext.company/frameworks/langgraph Installs the necessary TCC OpenTelemetry package for LangGraph and LangChain integration. Supports both pip and poetry package managers. ```shell pip install "tcc-otel[langchain]" ``` ```shell poetry add "tcc-otel[langchain]" ``` -------------------------------- ### Submit User Feedback for Agent Runs (TypeScript) Source: https://docs.thecontext.company/frameworks/mastra/usage Provides a code example for submitting user feedback using the `submitFeedback` function from `@contextcompany/mastra`. This function takes a `runId`, an optional `score` (thumbs up/down), and optional `text` feedback. At least one of `score` or `text` must be provided. The feedback is associated with the agent run identified by `runId`. ```typescript import { submitFeedback } from "@contextcompany/mastra"; // Submit both score and text feedback: await submitFeedback({ runId: runId, // The run ID from your agent execution score: "thumbs_up", // Optional: "thumbs_up" or "thumbs_down" text: "This was a helpful response!", // Optional: up to 2000 characters }); ``` -------------------------------- ### Instrument Mastra with TCC Exporter (TypeScript) Source: https://docs.thecontext.company/frameworks/mastra/setup Integrates The Context Company's Mastra exporter into your Mastra configuration. This allows Mastra agent runs, steps, and tool calls to be exported as traces to The Context Company dashboard. ```typescript import { Mastra } from "@mastra/core/mastra"; import { exampleAgent } from "./agents/example-agent"; import { TCCMastraExporter } from "@contextcompany/mastra"; // Initialize Mastra with TCC observability exporter export const mastra = new Mastra({ agents: { exampleAgent }, observability: { configs: { otel: { serviceName: "mastra-weather-agent", exporters: [new TCCMastraExporter({})], }, }, }, }); ``` -------------------------------- ### Set TCC Environment Variables (.env.local) Source: https://docs.thecontext.company/frameworks/mastra/setup Sets the TCC_API_KEY environment variable, which is used by The Context Company SDKs to authenticate API requests. Ensure this key is kept confidential. ```env TCC_API_KEY="your-api-key" ``` -------------------------------- ### Instrument LangChain Application Source: https://docs.thecontext.company/frameworks/langchain Initializes LangChain instrumentation before importing LangChain. Requires TCC_API_KEY environment variable. This code snippet demonstrates setting up observability for LangChain applications. ```python from dotenv import load_dotenv import os load_dotenv() # Import and initialize TCC instrumentation BEFORE importing LangChain from tcc_otel import instrument_langchain instrument_langchain( api_key=os.getenv("TCC_API_KEY"), ) # Your existing LangChain code from langchain_openai import ChatOpenAI from langchain.agents import create_openai_functions_agent, AgentExecutor model = ChatOpenAI(model="gpt-4") agent = create_openai_functions_agent(model, tools=[]) executor = AgentExecutor(agent=agent, tools=[]) ``` -------------------------------- ### Submit User Feedback for Agent Runs (TypeScript) Source: https://docs.thecontext.company/frameworks/ai-sdk/usage Illustrates how to submit user feedback, including a score (thumbs up/down) and optional text comments, for a specific agent run using its `runId`. This function requires the '@contextcompany/otel' package and allows for collecting user satisfaction data. ```typescript import { submitFeedback } from "@contextcompany/otel"; // Submit both score and text feedback: await submitFeedback({ runId: runId, // The run ID from your agent execution score: "thumbs_up", // Optional: "thumbs_up" or "thumbs_down" text: "This was a helpful response!", // Optional: up to 2000 characters }); ``` -------------------------------- ### Add Custom Metadata to LangChain Agent Run Source: https://docs.thecontext.company/frameworks/langchain Demonstrates how to add custom metadata to LangChain agent runs by passing it through LangChain's RunnableConfig. This allows for filtering and analysis of agent runs based on custom properties. ```python result = agent_executor.invoke( {"input": "Hello!"}, { "metadata": { # e.g. tag this agent run with a user id "userId": "4a6b111c-b53a-4d00-a877-67185022ab9e", } } ) ``` -------------------------------- ### Add Custom Metadata to Agent Runs (TypeScript) Source: https://docs.thecontext.company/frameworks/mastra/usage Demonstrates how to add custom key-value metadata to agent runs using the `tracingOptions.metadata` object. This allows for filtering and analysis of agent runs based on custom business logic, such as user IDs or feature tags. Ensure the metadata is correctly formatted as a key-value pair. ```typescript await agent.stream( // ... { // Pass metadata to track and filter this execution tracingOptions: { metadata: { // e.g. tag this agent run with a user id userId: "4a6b111c-b53a-4d00-a877-67185022ab9e", customMetadata1: "1234567890", customMetadata2: "context is key", }, }, } ); ``` -------------------------------- ### Enable Debug Mode for OTel in Node.js (TypeScript) Source: https://docs.thecontext.company/frameworks/ai-sdk/usage This snippet demonstrates how to enable debug mode for OpenTelemetry tracing in a standard Node.js environment. It involves creating a `TCCSpanProcessor` with `debug: true` and configuring the `NodeSDK`. It requires the `@opentelemetry/sdk-node` and `@contextcompany/otel` packages. ```typescript import { TCCSpanProcessor } from "@contextcompany/otel"; import { NodeSDK } from "@opentelemetry/sdk-node"; export const tcc = new NodeSDK({ spanProcessors: [new TCCSpanProcessor({ debug: true })], }); ``` -------------------------------- ### Configure NodeSDK with TCCSpanProcessor Source: https://docs.thecontext.company/frameworks/vercel Sets up a `NodeSDK` instance for Node.js applications, incorporating the `TCCSpanProcessor`. This configuration is typically placed in a dedicated file (e.g., `tcc.ts`) for easy management and reuse. ```typescript import { TCCSpanProcessor } from "@contextcompany/otel"; import { NodeSDK } from "@opentelemetry/sdk-node"; export const tcc = new NodeSDK({ spanProcessors: [new TCCSpanProcessor()], }); ``` -------------------------------- ### Add Custom Metadata to Agent Runs (TypeScript) Source: https://docs.thecontext.company/frameworks/ai-sdk/usage Demonstrates how to add custom metadata to agent runs using the Vercel AI SDK. This allows for tagging agent runs with specific identifiers like userId for filtering and analysis in the dashboard. It requires the '@ai-sdk/openai' and 'ai' packages. ```typescript import { openai } from "@ai-sdk/openai"; import { generateText } from "ai"; const { text } = await generateText({ // ... experimental_telemetry: { isEnabled: true, metadata: { // e.g. tag this agent run with a user id userId: "4a6b111c-b53a-4d00-a877-67185022ab9e", }, }, }); ``` -------------------------------- ### Instrument Next.js with TCCSpanProcessor and @vercel/otel Source: https://docs.thecontext.company/frameworks/vercel Provides an alternative method for instrumenting Next.js applications by directly using `TCCSpanProcessor` with the `registerOTel` function from `@vercel/otel`. This allows for additional span processors to be configured. ```typescript import { TCCSpanProcessor } from "@contextcompany/otel"; import { registerOTel } from "@vercel/otel"; export function register() { if (process.env.NEXT_RUNTIME === "nodejs") registerOTel({ spanProcessors: [new TCCSpanProcessor()], }); } ``` -------------------------------- ### Enable Debug Mode for OTel in Next.js (TypeScript) Source: https://docs.thecontext.company/frameworks/ai-sdk/usage This code snippet enables debug mode for OpenTelemetry tracing within a Next.js application's Node.js runtime. It uses the `@contextcompany/otel/nextjs` package to register the OTel configuration. Ensure you are within the `process.env.NEXT_RUNTIME === "nodejs"` check. ```typescript import { registerOTelTCC } from "@contextcompany/otel/nextjs"; export function register() { if (process.env.NEXT_RUNTIME === "nodejs") { registerOTelTCC({ debug: true }); } } ``` -------------------------------- ### Generate and Pass Run ID for User Feedback (TypeScript) Source: https://docs.thecontext.company/frameworks/claude-agent-sdk/usage Shows how to generate a unique run ID (UUID) and pass it to the `query` function for tracking agent runs that will later receive user feedback. This involves using `randomUUID` from 'crypto' and `instrumentClaudeAgent`. ```typescript import { instrumentClaudeAgent } from "@contextcompany/claude"; import * as claudeSDK from "@anthropic-ai/claude-agent-sdk"; import { randomUUID } from "crypto"; const { query } = instrumentClaudeAgent(claudeSDK); // Generate a unique run ID (must be a UUID) before your agent execution const runId = randomUUID(); const result = query({ // ... tcc: { runId: runId, // Pass the run ID }, }); // Return the runId to your client return { result, runId }; ``` -------------------------------- ### Add Custom Metadata to Agent Runs (TypeScript) Source: https://docs.thecontext.company/frameworks/claude-agent-sdk/usage Demonstrates how to add custom key-value metadata to agent runs using the Claude Agent SDK. This allows for filtering and analysis based on custom dimensions like user ID. It requires importing `instrumentClaudeAgent` from '@contextcompany/claude' and the Claude SDK. ```typescript import { instrumentClaudeAgent } from "@contextcompany/claude"; import * as claudeSDK from "@anthropic-ai/claude-agent-sdk"; const { query } = instrumentClaudeAgent(claudeSDK); const result = query({ // ... tcc: { metadata: { // e.g. tag this agent run with a user id userId: "4a6b111c-b53a-4d00-a877-67185022ab9e", }, }, }); ``` -------------------------------- ### Initialize LangGraph Instrumentation Source: https://docs.thecontext.company/frameworks/langgraph Initializes TCC OpenTelemetry instrumentation for LangGraph and LangChain. This must be done before importing LangGraph or LangChain. Requires TCC_API_KEY environment variable. ```python from dotenv import load_dotenv import os load_dotenv() # Import and initialize TCC instrumentation BEFORE importing LangGraph from tcc_otel import instrument_langchain instrument_langchain( api_key=os.getenv("TCC_API_KEY"), ) # Your existing LangChain code from langchain_openai import ChatOpenAI from langgraph.prebuilt import create_react_agent model = ChatOpenAI(model="gpt-4") agent = create_react_agent(model, tools=[]) ``` -------------------------------- ### Submit User Feedback for Agent Runs (TypeScript) Source: https://docs.thecontext.company/frameworks/claude-agent-sdk/usage Illustrates how to submit user feedback, including an optional score ('thumbs_up' or 'thumbs_down') and text, for a specific agent run using the `submitFeedback` function. This requires the `runId` generated previously. ```typescript import { submitFeedback } from "@contextcompany/claude"; // Submit both score and text feedback: await submitFeedback({ runId: runId, // The run ID from your agent execution score: "thumbs_up", // Optional: "thumbs_up" or "thumbs_down" text: "This was a helpful response!", // Optional: up to 2000 characters }); ``` -------------------------------- ### Enable Debug Mode for Mastra Exporter (TypeScript) Source: https://docs.thecontext.company/frameworks/mastra/usage Shows how to enable debug mode for the `TCCMastraExporter` by setting the `debug` option to `true` within the observability configuration. This will log all created and exported spans, aiding in debugging and understanding the agent's execution flow. Ensure the Mastra instance is configured with the `TCCMastraExporter`. ```typescript import { Mastra } from "@mastra/core/mastra"; import { exampleAgent } from "./agents/example-agent"; import { TCCMastraExporter } from "@contextcompany/mastra"; export const mastra = new Mastra({ agents: { exampleAgent }, observability: { configs: { otel: { serviceName: "mastra-weather-agent", exporters: [new TCCMastraExporter({ debug: true })], // Add debug: true here }, }, }, }); ``` -------------------------------- ### Track Agent Sessions with Session ID (TypeScript) Source: https://docs.thecontext.company/frameworks/claude-agent-sdk/usage Explains how to group multiple agent runs into a single agent session by providing a `sessionId` within the `tcc` parameter of the `query` function. This is useful for tracking conversations. It uses `instrumentClaudeAgent` from '@contextcompany/claude'. ```typescript import { instrumentClaudeAgent } from "@contextcompany/claude"; import * as claudeSDK from "@anthropic-ai/claude-agent-sdk"; const { query } = instrumentClaudeAgent(claudeSDK); const result = query({ // ... tcc: { sessionId: "some-session-id", // Track agent sessions }, }); ``` -------------------------------- ### Enable Telemetry for AI SDK Calls (Next.js) Source: https://docs.thecontext.company/frameworks/ai-sdk/setup Enables experimental telemetry for AI SDK calls in Next.js by setting the `experimental_telemetry.isEnabled` flag to `true` within `generateText` or `streamText` configurations. ```typescript import { generateText } from "ai"; const result = generateText({ // ... experimental_telemetry: { isEnabled: true }, // required }); ``` ```typescript import { streamText } from "ai"; const result = streamText({ // ... experimental_telemetry: { isEnabled: true }, // required }); ``` -------------------------------- ### Track Agent Sessions with Session ID (TypeScript) Source: https://docs.thecontext.company/frameworks/ai-sdk/usage Shows how to group multiple agent runs into a single session by setting a `tcc.sessionId` in the metadata. This is useful for tracking conversations in chatbot interfaces. It requires the 'ai' package. ```typescript import { generateText } from "ai"; const { text } = await generateText({ // ... experimental_telemetry: { isEnabled: true, metadata: { // use tcc.sessionId to track agent sessions "tcc.sessionId": "some-session-id", }, }, }); ``` -------------------------------- ### Generate and Pass Run ID for User Feedback (TypeScript) Source: https://docs.thecontext.company/frameworks/mastra/usage Explains how to generate a unique run ID using `crypto.randomUUID()` and pass it to the agent's `tracingOptions.metadata` under the key `tcc.runId`. This run ID is crucial for associating user feedback with specific agent executions. The generated `runId` should be returned to the client for subsequent feedback submission. ```typescript import { randomUUID } from "crypto"; // Generate a unique run ID (must be a UUID) before your agent execution const runId = randomUUID(); const response = await agent.stream( // ... { tracingOptions: { metadata: { "tcc.runId": runId, // Pass the run ID in metadata }, }, } ); // Return the runId to your client return { response, runId }; ``` -------------------------------- ### Instrument Next.js Application Source: https://docs.thecontext.company/frameworks/ai-sdk/local Registers OpenTelemetry for The Context Company within a Next.js application by calling registerOTelTCC with local mode enabled. This should be placed in an instrumentation.[js|ts] file. ```typescript export async function register() { if (process.env.NEXT_RUNTIME === "nodejs") { const { registerOTelTCC } = await import("@contextcompany/otel/nextjs"); registerOTelTCC({ local: true }); } } ``` -------------------------------- ### Enable Telemetry for AI SDK Calls Source: https://docs.thecontext.company/frameworks/vercel Enables experimental telemetry for AI SDK v5 and later by setting the `experimental_telemetry.isEnabled` flag to `true`. This flag must be included in all AI SDK calls to ensure telemetry data is collected. ```typescript import { generateText } from "ai"; const result = generateText({ // ... experimental_telemetry: { isEnabled: true }, // required }); ``` -------------------------------- ### Add Local Mode Widget to Layout Source: https://docs.thecontext.company/frameworks/ai-sdk/local Includes the The Context Company Local Mode widget script in the root layout of a Next.js application. This allows the widget to be available globally. ```tsx import Script from "next/script"; export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( {/* add TCC script: */}