> ## Documentation Index
> Fetch the complete documentation index at: https://docs.anyway.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript SDK Tracing

> Trace your LLM operations with withWorkflow, withTask, and decorators

## Overview

The Anyway JS SDK provides functions and decorators to structure your traces:

* **`withWorkflow`** - High-level operations that orchestrate multiple tasks
* **`withTask`** - Individual units of work (like LLM calls)
* **`withAgent`** - Agent operations with automatic agent name propagation
* **`withTool`** - Tool executions within agents

## Basic Setup

```typescript theme={null}
import { initialize, withWorkflow, withTask } from "@anyway-sh/node-server-sdk";

initialize({ appName: "my-app" });
```

## withWorkflow and withTask

Use `withWorkflow` for top-level operations and `withTask` for individual steps:

<Tabs>
  <Tab title="OpenAI">
    ```typescript theme={null}
    import OpenAI from "openai";
    import { initialize, withWorkflow, withTask } from "@anyway-sh/node-server-sdk";

    initialize({
      appName: "document-processor",
      instrumentModules: { openAI: OpenAI },
    });

    const client = new OpenAI();

    async function summarize(text: string): Promise<string> {
      return withTask({ name: "summarize" }, async () => {
        const response = await client.chat.completions.create({
          model: "gpt-4o-mini",
          messages: [
            { role: "system", content: "Summarize the text concisely." },
            { role: "user", content: text },
          ],
        });
        return response.choices[0].message.content!;
      });
    }

    async function extractKeywords(text: string): Promise<string[]> {
      return withTask({ name: "extract_keywords" }, async () => {
        const response = await client.chat.completions.create({
          model: "gpt-4o-mini",
          messages: [
            { role: "system", content: "Extract 5 keywords. Return comma-separated." },
            { role: "user", content: text },
          ],
        });
        return response.choices[0].message.content!.split(", ");
      });
    }

    async function processDocument(document: string) {
      return withWorkflow({ name: "process_document" }, async () => {
        const summary = await summarize(document);
        const keywords = await extractKeywords(document);
        return { summary, keywords };
      });
    }

    // Run it
    const result = await processDocument("Your document text here...");
    ```
  </Tab>

  <Tab title="Anthropic">
    ```typescript theme={null}
    import Anthropic from "@anthropic-ai/sdk";
    import { initialize, withWorkflow, withTask } from "@anyway-sh/node-server-sdk";

    initialize({
      appName: "document-processor",
      instrumentModules: { anthropic: Anthropic },
    });

    const client = new Anthropic();

    async function summarize(text: string): Promise<string> {
      return withTask({ name: "summarize" }, async () => {
        const message = await client.messages.create({
          model: "claude-sonnet-4-20250514",
          max_tokens: 1024,
          system: "Summarize the text concisely.",
          messages: [{ role: "user", content: text }],
        });
        return (message.content[0] as any).text;
      });
    }

    async function processDocument(document: string) {
      return withWorkflow({ name: "process_document" }, async () => {
        const summary = await summarize(document);
        return { summary };
      });
    }
    ```
  </Tab>
</Tabs>

## Class Decorators

For TypeScript projects with `experimentalDecorators` enabled:

```typescript theme={null}
import { workflow, task } from "@anyway-sh/node-server-sdk";

class DocumentProcessor {
  @workflow({ name: "process" })
  async process(document: string) {
    const summary = await this.summarize(document);
    const keywords = await this.extractKeywords(document);
    return { summary, keywords };
  }

  @task({ name: "summarize" })
  async summarize(text: string) {
    // LLM call here
  }

  @task({ name: "extract_keywords" })
  async extractKeywords(text: string) {
    // LLM call here
  }
}
```

## Agent Tracing

Use `withAgent` to trace agent operations. Agent names automatically propagate to all child spans:

```typescript theme={null}
import { withWorkflow, withAgent, withTask } from "@anyway-sh/node-server-sdk";

async function runAgent(query: string) {
  return withWorkflow({ name: "support_agent" }, async () => {
    return withAgent({ name: "classifier" }, async () => {
      const category = await withTask({ name: "classify" }, async () => {
        // LLM classification call
        return "billing";
      });

      const response = await withTask({ name: "draft_response" }, async () => {
        // LLM response generation
        return "Here is your response...";
      });

      return { category, response };
    });
  });
}
```

## Association Properties

Attach metadata to traces for filtering and grouping in the dashboard:

```typescript theme={null}
await withWorkflow(
  {
    name: "chat",
    associationProperties: {
      userId: "user-123",
      sessionId: "session-abc",
      environment: "production",
    },
  },
  async () => {
    // All spans in this workflow carry these properties
  },
);
```

## Conversation Tracking

Track multi-turn conversations:

```typescript theme={null}
import { withConversation } from "@anyway-sh/node-server-sdk";

async function handleMessage(conversationId: string, message: string) {
  return withConversation(conversationId, async () => {
    // All spans are tagged with the conversation ID
    const response = await client.chat.completions.create({
      model: "gpt-4o",
      messages: [{ role: "user", content: message }],
    });
    return response.choices[0].message.content;
  });
}
```

## View in Dashboard

After running your code, view traces in the [Anyway Dashboard](https://app.anyway.sh):

1. Navigate to **Traces**
2. Find your workflow trace
3. Expand to see nested task spans
4. View timing, inputs, and outputs for each operation

## Next Steps

<CardGroup cols={3}>
  <Card title="Configuration" icon="gear" href="/sdk/js/configuration">
    Configure endpoints and authentication
  </Card>

  <Card title="Customer & Order Attribution" icon="users" href="/features/customer-order-attribution">
    Link traces to customers and orders
  </Card>

  <Card title="Cost Tracking" icon="dollar-sign" href="/features/cost-tracking">
    Monitor your AI spend
  </Card>
</CardGroup>
