---
title: "Cohere (tracing)"
description: "Trace Cohere SDK chat, streaming, embeddings, and rerank calls with Respan in Python or TypeScript."
---

<Accordion title="Set up Respan">
1. **Sign up** - Create an account at [platform.respan.ai](https://platform.respan.ai)
2. **Create an API key** - Generate one on the [API keys page](https://platform.respan.ai/platform/gateway/api-keys)
</Accordion>

Paste this into your coding agent:

```text
Help me set up Respan tracing with the Cohere integration.
Follow https://www.respan.ai/docs/integrations/cohere.md
```

## What is Cohere?

The [Cohere SDKs](https://docs.cohere.com/) provide chat, streaming chat, embedding, and rerank APIs. `respan-instrumentation-cohere` and `@respan/instrumentation-cohere` normalize Cohere spans to the Respan span contract before export.

## Setup

<Steps>
<Step title="Install packages">

<Tabs>
<Tab title={"Python"}>

```bash
pip install respan-ai respan-instrumentation-cohere cohere python-dotenv
```

</Tab>
<Tab title={"TypeScript"}>

```bash
npm install @respan/respan @respan/tracing @respan/instrumentation-cohere cohere-ai dotenv
```

</Tab>
</Tabs>

</Step>

<Step title="Set environment variables">

```bash
export RESPAN_API_KEY="YOUR_RESPAN_API_KEY"
export CO_API_KEY="YOUR_COHERE_API_KEY"
export COHERE_API_KEY="YOUR_COHERE_API_KEY"
```

Optional:

```bash
export RESPAN_BASE_URL="https://api.respan.ai/api"
export COHERE_CHAT_MODEL="command-a-03-2025"
```

`CO_API_KEY` is used by the Python SDK. `COHERE_API_KEY` is used by the TypeScript SDK. `RESPAN_API_KEY` is used by Respan for trace export.

</Step>

<Step title="Initialize and run">

<Tabs>
<Tab title={"Python"}>

```python
import os

import cohere
from dotenv import load_dotenv
from respan import Respan, workflow
from respan_instrumentation_cohere import CohereInstrumentor

load_dotenv()

respan = Respan(
    api_key=os.environ["RESPAN_API_KEY"],
    base_url=os.getenv("RESPAN_BASE_URL", "https://api.respan.ai/api"),
    instrumentations=[CohereInstrumentor()],
)
client = cohere.ClientV2(api_key=os.environ["CO_API_KEY"])


@workflow(name="cohere_chat.workflow")
def run_chat() -> str:
    response = client.chat(
        model=os.getenv("COHERE_CHAT_MODEL", "command-a-03-2025"),
        messages=[
            {
                "role": "user",
                "content": "In one sentence, explain what Cohere rerank is useful for.",
            }
        ],
        temperature=0.1,
        max_tokens=80,
    )
    return response.message.content[0].text


with respan.propagate_attributes(
    trace_group_identifier="cohere_chat.workflow",
    metadata={"workflow_name": "cohere_chat.workflow"},
):
    print(run_chat())
```

</Tab>
<Tab title={"TypeScript"}>

```typescript
import "dotenv/config";
import * as Cohere from "cohere-ai";
import { CohereClientV2 } from "cohere-ai";
import { Respan } from "@respan/respan";
import { CohereInstrumentor } from "@respan/instrumentation-cohere";

const respan = new Respan({
  apiKey: process.env.RESPAN_API_KEY,
  baseURL: process.env.RESPAN_BASE_URL,
  instrumentations: [new CohereInstrumentor({ sdkModule: Cohere })],
});
await respan.initialize();

const cohere = new CohereClientV2({
  token: process.env.COHERE_API_KEY,
});

try {
  const result = await respan.withWorkflow({ name: "cohere_chat.workflow" }, async () => {
    return cohere.chat({
      model: process.env.COHERE_CHAT_MODEL ?? "command-a-03-2025",
      messages: [
        {
          role: "user",
          content: "In one sentence, explain what Cohere rerank is useful for.",
        },
      ],
      temperature: 0.1,
      maxTokens: 80,
    });
  });
  console.log(result.message?.content);
} finally {
  await respan.shutdown();
}
```

</Tab>
</Tabs>

</Step>

<Step title="View your trace">

Open the [Traces page](https://platform.respan.ai/platform/traces) and search for the workflow name `cohere_chat.workflow`.

</Step>
</Steps>

## Configuration

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `exception_logger` | `logging.Logger \| None` | `None` | Optional logger passed to the underlying Cohere OpenTelemetry instrumentor. |
| `sdkModule` | `object \| undefined` | `undefined` | TypeScript only. Pass the imported `cohere-ai` module so the instrumentor patches the same module instance used by your app. |
| `use_legacy_attributes` | `bool` | `True` | Python only. Emits span attributes compatible with the existing Respan span contract. |
| `**instrumentor_kwargs` | `dict` | `{}` | Python only. Extra keyword arguments forwarded to the upstream instrumentor. |

## Attributes

Attach customer identifiers, thread IDs, and metadata to Cohere calls with `propagate_attributes` or `propagateAttributes`.

<Tabs>
<Tab title={"Python"}>

```python
with respan.propagate_attributes(
    customer_identifier="user_123",
    session_identifier="conversation_456",
    trace_group_identifier="cohere_support_chat.workflow",
    metadata={"plan": "pro", "workflow_name": "cohere_support_chat.workflow"},
):
    response = client.chat(
        model="command-a-03-2025",
        messages=[{"role": "user", "content": "Summarize our support policy."}],
    )
```

</Tab>
<Tab title={"TypeScript"}>

```typescript
await respan.propagateAttributes(
  {
    customer_identifier: "user_123",
    session_identifier: "conversation_456",
    trace_group_identifier: "cohere_support_chat.workflow",
    metadata: { plan: "pro", workflow_name: "cohere_support_chat.workflow" },
  },
  async () => {
    return cohere.chat({
      model: "command-a-03-2025",
      messages: [{ role: "user", content: "Summarize our support policy." }],
    });
  }
);
```

</Tab>
</Tabs>

| Attribute | Type | Description |
|-----------|------|-------------|
| `customer_identifier` | `str` | Identifies the end user in Respan analytics. |
| `session_identifier` | `str` | Groups related messages into a conversation. |
| `trace_group_identifier` | `str` | Groups spans by workflow name. |
| `metadata` | `dict` | Custom key-value pairs merged with default metadata. |

## Examples

### Streaming chat

<Tabs>
<Tab title={"Python"}>

```python
stream = client.chat_stream(
    model="command-a-03-2025",
    messages=[{"role": "user", "content": "Write a short haiku about observability."}],
)

for event in stream:
    if event.type == "content-delta":
        print(event.delta.message.content.text, end="", flush=True)
```

</Tab>
<Tab title={"TypeScript"}>

```typescript
const stream = await cohere.chatStream({
  model: "command-a-03-2025",
  messages: [{ role: "user", content: "Write a short haiku about observability." }],
});

for await (const event of stream) {
  if (event.type === "content-delta") {
    process.stdout.write(event.delta?.message?.content?.text ?? "");
  }
}
```

</Tab>
</Tabs>

### Embeddings

<Tabs>
<Tab title={"Python"}>

```python
response = client.embed(
    model="embed-v4.0",
    input_type="search_document",
    texts=[
        "Respan records traces and spans for AI systems.",
        "Cohere embeddings convert text into vectors.",
    ],
    embedding_types=["float"],
)
print(len(response.embeddings.float_))
```

</Tab>
<Tab title={"TypeScript"}>

```typescript
const response = await cohere.embed({
  model: "embed-v4.0",
  inputType: "search_document",
  texts: [
    "Respan records traces and spans for AI systems.",
    "Cohere embeddings convert text into vectors.",
  ],
  embeddingTypes: ["float"],
});
console.log(response.embeddings?.float?.length);
```

</Tab>
</Tabs>

### Rerank

<Tabs>
<Tab title={"Python"}>

```python
response = client.rerank(
    model="rerank-v3.5",
    query="Which document explains search result ranking?",
    documents=[
        "Rerank models reorder candidate documents by query relevance.",
        "Chat models generate conversational responses.",
    ],
    top_n=1,
)
print(response.results[0].index)
```

</Tab>
<Tab title={"TypeScript"}>

```typescript
const response = await cohere.rerank({
  model: "rerank-v3.5",
  query: "Which document explains search result ranking?",
  documents: [
    "Rerank models reorder candidate documents by query relevance.",
    "Chat models generate conversational responses.",
  ],
  topN: 1,
});
console.log(response.results?.[0]?.index);
```

</Tab>
</Tabs>
