Documentation

Everything you need to instrument, monitor, and audit your AI agents.

On this page

    Quick Start

    One-Click Templates

    Authentication

    Trace Schema

    Compliance Fields

    SDK Reference

    Frameworks

Quick Start

Get up and running with AgentTraceHQ in under 5 minutes. Install the SDK, initialize it with your API key, and send your first trace.

1. Install the SDK
Terminal
npm install @agenttracehq/sdk
2. Initialize
index.js
import { AgentTraceHQ } from '@agenttracehq/sdk';

const ath = new AgentTraceHQ({
  apiKey: process.env.AGENTTRACEHQ_API_KEY,
  agentId: 'my-agent-001',
});
3. Send your first trace
index.js
// Send your first trace
await ath.trace({
  event: 'llm.completion',
  input: { prompt: 'Summarize this document...' },
  output: { text: 'The document discusses...' },
  metadata: {
    model: 'gpt-4',
    tokens: 342,
    latencyMs: 1250,
  },
});

console.log('Trace sent!');
One-Click Templates
Copy & paste ready

Complete, working integration snippets for popular frameworks. Copy, paste, replace your API key, and you are done.

Drop-in callback for any LangChain agent with automatic tracing of every LLM call, tool use, and chain step.

LangChain Integration
// 1. Install: npm install @agenttracehq/sdk
// 2. Paste this into your LangChain agent file
// 3. Replace YOUR_API_KEY with your key from dashboard

import { AgentTraceHQ } from '@agenttracehq/sdk';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';

const ath = new AgentTraceHQ({
  apiKey: 'YOUR_API_KEY',
  agentId: 'my-langchain-agent',
});

// Add this ONE line to your existing agent:
const agent = AgentExecutor.fromAgentAndTools({
  agent: myAgent,
  tools: myTools,
  callbacks: [ath.langchainCallback()],
});

// That's it. Every LLM call, tool use, and chain step
// is now traced with cryptographic hash chains.

Instrument your CrewAI agents with one callback per agent to trace all steps, delegations, and tool calls.

CrewAI Integration
# 1. Install: pip install agenttracehq
# 2. Paste this into your CrewAI file
# 3. Replace YOUR_API_KEY with your key from dashboard

from agenttracehq import AgentTraceHQ
from crewai import Agent, Task, Crew

ath = AgentTraceHQ(
    api_key="YOUR_API_KEY",
    agent_id="my-crewai-team"
)

# Add callbacks=[ath.crewai_callback()] to each agent:
researcher = Agent(
    role="Researcher",
    goal="Find latest data",
    callbacks=[ath.crewai_callback()],
)

crew = Crew(agents=[researcher], tasks=[...])
result = crew.kickoff()
# All agent steps are now immutably traced.

Wrap your AutoGen multi-agent conversations with a context manager to trace every message exchange.

AutoGen Integration
# 1. Install: pip install agenttracehq
# 2. Paste this into your AutoGen file

from agenttracehq import AgentTraceHQ
import autogen

ath = AgentTraceHQ(
    api_key="YOUR_API_KEY",
    agent_id="my-autogen-group"
)

assistant = autogen.AssistantAgent(
    name="assistant",
    llm_config={"model": "gpt-4"},
)

user_proxy = autogen.UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER",
)

# Wrap the chat with tracing:
with ath.autogen_trace():
    user_proxy.initiate_chat(assistant, message="Analyze Q4 revenue")

Add session-based tracing to your Express API endpoints that invoke AI agents.

Express.js Integration
// 1. Install: npm install @agenttracehq/sdk
// 2. Paste this middleware into your Express app

import { AgentTraceHQ } from '@agenttracehq/sdk';
import express from 'express';

const ath = new AgentTraceHQ({
  apiKey: 'YOUR_API_KEY',
  agentId: 'my-api-agent',
});

const app = express();

// Trace every AI agent call in your API
app.post('/api/agent', async (req, res) => {
  const session = ath.session({ name: 'api-request' });

  await session.trace({
    event: 'agent.start',
    input: req.body,
  });

  const result = await runMyAgent(req.body);

  await session.trace({
    event: 'agent.complete',
    output: result,
    riskLevel: result.riskLevel,
    reasoning: result.reasoning,
  });

  await session.end();
  res.json(result);
});
Authentication

All API requests require an API key. You can generate keys from your Dashboard > Settings > API Keys page. Keys are prefixed with ath_live_ for production and ath_test_ for development.

Pass your API key via the SDK constructor or as a Bearer token in the Authorization header for direct API calls.

Direct API usage
// API keys are passed in the Authorization header
const response = await fetch('https://api.agenttracehq.com/v1/traces', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer ath_live_abc123...',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    event: 'tool.call',
    input: { tool: 'web_search', query: 'latest AI news' },
    output: { results: [...] },
  }),
});
Trace Schema

Every trace is an immutable record of an agent action. Traces are cryptographically linked via hash chains, ensuring tamper-proof audit trails. Below is the full trace object schema:

Trace Object
{
  "id": "trc_a3f29c1e...",
  "agentId": "agent-001",
  "sessionId": "ses_7c1eb9d4...",
  "event": "llm.completion",
  "timestamp": "2025-01-15T10:30:00.000Z",
  "input": {
    "prompt": "Analyze the sales data...",
    "context": { ... }
  },
  "output": {
    "text": "Based on the data...",
    "confidence": 0.95
  },
  "metadata": {
    "model": "gpt-4",
    "tokens": 512,
    "latencyMs": 1800,
    "cost": 0.032
  },
  "riskLevel": "low",
  "piiDetected": false,
  "policyViolations": [],
  "parentTraceId": "trc_parent...",
  "hash": "sha256:e5a8f2c1...",
  "previousHash": "sha256:b9d47c1e...",
  "tags": ["production", "sales-analysis"]
}
Compliance Fields

AgentTraceHQ supports optional fields on every trace that directly map to compliance framework requirements. Adding these fields improves your compliance scores for SOC 2, ISO 27001, and the EU AI Act.

FieldTypeDescription
riskLevel"low" | "medium" | "high" | "critical"Classifies the risk level of the agent action. Used for ISO 27001 risk assessment and EU AI Act Art. 9 risk management.
piiDetectedbooleanFlags whether the trace involves personally identifiable information. Relevant for GDPR and data protection compliance.
policyViolationsstring[]Array of policy rule identifiers that were violated during this action. Drives SOC 2 and EU AI Act monitoring.
reasoningstringHuman-readable explanation of why the agent took this action. Required for EU AI Act transparency (Art. 13).
Compliance-enriched trace
await ath.trace({
  event: 'tool.call',
  input: { tool: 'database_query', query: 'SELECT * FROM users' },
  output: { rows: 42 },

  // Risk level — used for ISO 27001 risk assessment
  // and EU AI Act risk classification (Art. 9)
  riskLevel: 'medium',       // "low" | "medium" | "high" | "critical"

  // PII detection — flags traces containing personal data
  piiDetected: true,

  // Policy violations — records any rule breaches
  policyViolations: ['accessed-pii-without-consent'],

  // Reasoning — documents why the agent made this decision
  // Important for EU AI Act transparency requirements (Art. 13)
  reasoning: 'User requested account summary, queried user table',
});
SDK Reference
trace(event)

Log a single trace event. This is the primary method for recording agent actions. Each trace is automatically assigned a unique ID, timestamp, and hash-chain link.

trace()
// ath.trace(event) - Log a single trace event
await ath.trace({
  event: 'tool.call',          // Event type (required)
  input: { ... },              // Input data (optional)
  output: { ... },             // Output data (optional)
  metadata: { ... },           // Arbitrary metadata (optional)
  tags: ['prod', 'v2'],        // Searchable tags (optional)
  parentTraceId: 'trc_...',    // Parent trace for nesting (optional)
  riskLevel: 'low',            // Risk classification (optional)
});
session(options)

Start a session to logically group related traces. Useful for multi-step agent workflows where you want to track an entire conversation or task from start to finish.

session()
// ath.session(options) - Start a session to group traces
const session = ath.session({
  name: 'customer-support-flow',
  metadata: { userId: 'usr_123' },
});

// All traces within the session are automatically linked
await session.trace({ event: 'llm.completion', ... });
await session.trace({ event: 'tool.call', ... });

// End the session
await session.end();
flush()

Ensure all pending traces in the buffer are sent to the AgentTraceHQ API. Critical for serverless environments where the process may terminate before the buffer is flushed.

flush()
// ath.flush() - Ensure all pending traces are sent
// Call this before your process exits
await ath.flush();

// Useful in serverless environments
export async function handler(event) {
  const result = await processWithAgent(event);
  await ath.flush(); // Ensure traces are sent before Lambda exits
  return result;
}
Frameworks

AgentTraceHQ integrates with popular AI agent frameworks out of the box. Use our callback handlers to automatically capture all agent activity with zero manual instrumentation.

LangChain
LangChain Integration
import { AgentTraceHQ } from '@agenttracehq/sdk';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor } from 'langchain/agents';

const ath = new AgentTraceHQ({
  apiKey: process.env.AGENTTRACEHQ_API_KEY,
  agentId: 'langchain-agent',
});

// Wrap your LangChain agent with tracing
const agent = AgentExecutor.fromAgentAndTools({
  agent: myAgent,
  tools: myTools,
  callbacks: [ath.langchainCallback()],
});

// All LLM calls, tool invocations, and chain steps
// are automatically traced
const result = await agent.invoke({
  input: 'What is the weather in San Francisco?',
});
CrewAI
CrewAI Integration
from agenttracehq import AgentTraceHQ

ath = AgentTraceHQ(
    api_key="ath_live_abc123...",
    agent_id="crewai-team"
)

from crewai import Agent, Task, Crew

# Instrument CrewAI with the callback
researcher = Agent(
    role="Researcher",
    goal="Find latest AI papers",
    callbacks=[ath.crewai_callback()],
)

writer = Agent(
    role="Writer",
    goal="Summarize findings",
    callbacks=[ath.crewai_callback()],
)

crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, write_task],
)

# Every agent step, delegation, and tool call is traced
result = crew.kickoff()