Skip to main content

TraceAI Cohere Instrumentation

OpenTelemetry instrumentation for Cohere - embeddings, chat, and rerank APIs.

Installation

pip install traceai-cohere

Features

  • Automatic tracing of Cohere API calls
  • Support for chat, embed, and rerank endpoints
  • Streaming response support
  • Token usage tracking
  • Rerank relevance scores
  • Full OpenTelemetry semantic conventions compliance

Usage

Basic Setup

import cohere
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor

from traceai_cohere import CohereInstrumentor

# Set up tracing
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)

# Instrument Cohere
CohereInstrumentor().instrument(tracer_provider=provider)

# Use Cohere
client = cohere.Client(api_key="your-api-key")
response = client.chat(message="Hello!")
print(response.text)

Chat

import cohere

client = cohere.Client()

# Simple chat
response = client.chat(
    model="command-r-plus",
    message="What is machine learning?"
)
print(response.text)

# With chat history
response = client.chat(
    model="command-r-plus",
    message="What's my name?",
    chat_history=[
        {"role": "USER", "message": "My name is Alice"},
        {"role": "CHATBOT", "message": "Hello Alice!"}
    ]
)

# With preamble (system prompt)
response = client.chat(
    model="command-r-plus",
    message="Write a poem",
    preamble="You are a creative poet who writes in haiku format."
)

Streaming Chat

import cohere

client = cohere.Client()

# Streaming
for event in client.chat_stream(
    model="command-r-plus",
    message="Tell me a story"
):
    if event.event_type == "text-generation":
        print(event.text, end="", flush=True)

Embeddings

import cohere

client = cohere.Client()

# Generate embeddings
response = client.embed(
    model="embed-english-v3.0",
    texts=["Hello world", "Machine learning is great"],
    input_type="search_document"
)
print(f"Generated {len(response.embeddings)} embeddings")
print(f"Dimensions: {len(response.embeddings[0])}")

Rerank (for RAG)

import cohere

client = cohere.Client()

# Rerank documents for a query
query = "What is the capital of France?"
documents = [
    "Paris is the capital of France.",
    "London is the capital of England.",
    "The Eiffel Tower is in Paris.",
    "France is a country in Europe."
]

response = client.rerank(
    model="rerank-english-v3.0",
    query=query,
    documents=documents,
    top_n=3
)

for result in response.results:
    print(f"Index: {result.index}, Score: {result.relevance_score:.4f}")
    print(f"  {documents[result.index]}")

RAG with Cohere

import cohere

client = cohere.Client()

# Documents for context
documents = [
    {"title": "Paris", "text": "Paris is the capital of France."},
    {"title": "London", "text": "London is the capital of England."},
]

response = client.chat(
    model="command-r-plus",
    message="What is the capital of France?",
    documents=documents
)

print(response.text)
if response.citations:
    print("\nCitations:")
    for citation in response.citations:
        print(f"  - {citation}")

Tool Use

import cohere

client = cohere.Client()

tools = [
    {
        "name": "get_weather",
        "description": "Get the weather for a location",
        "parameter_definitions": {
            "location": {
                "type": "str",
                "description": "The city name",
                "required": True
            }
        }
    }
]

response = client.chat(
    model="command-r-plus",
    message="What's the weather in Paris?",
    tools=tools
)

if response.tool_calls:
    for tool_call in response.tool_calls:
        print(f"Tool: {tool_call.name}")
        print(f"Parameters: {tool_call.parameters}")

Configuration Options

TraceConfig

from fi_instrumentation import TraceConfig
from traceai_cohere import CohereInstrumentor

config = TraceConfig(
    hide_inputs=False,
    hide_outputs=False,
)

CohereInstrumentor().instrument(
    tracer_provider=provider,
    config=config
)

Captured Attributes

Chat Attributes

Attribute Description
gen_ai.span.kind "LLM"
gen_ai.provider.name "cohere"
gen_ai.request.model Model name (command-r-plus, etc.)
gen_ai.usage.input_tokens Input token count
gen_ai.usage.output_tokens Output token count
cohere.finish_reason Response finish reason
cohere.citations_count Number of citations
cohere.tool_calls_count Number of tool calls

Embed Attributes

Attribute Description
gen_ai.span.kind "EMBEDDING"
embedding.model_name Embedding model name
cohere.texts_count Number of texts embedded
cohere.embedding_dimensions Vector dimensions

Rerank Attributes

Attribute Description
gen_ai.span.kind "RERANKER"
reranker.model_name Rerank model name
reranker.query Search query
reranker.top_k Top N results requested
cohere.results_count Number of results
cohere.rerank.scores Relevance scores

Available Models

Category Models
Chat command-r-plus, command-r, command
Embed embed-english-v3.0, embed-multilingual-v3.0
Rerank rerank-english-v3.0, rerank-multilingual-v3.0

Real-World Use Cases

import cohere

client = cohere.Client()

# Index documents
documents = ["doc1", "doc2", "doc3"]
doc_embeddings = client.embed(
    model="embed-english-v3.0",
    texts=documents,
    input_type="search_document"
).embeddings

# Search query
query_embedding = client.embed(
    model="embed-english-v3.0",
    texts=["search query"],
    input_type="search_query"
).embeddings[0]

# Compute similarity (not shown: use vector DB)

Two-Stage RAG

import cohere

client = cohere.Client()

# Stage 1: Semantic search (not shown)
initial_results = ["doc1", "doc2", "doc3", "doc4", "doc5"]

# Stage 2: Rerank for precision
reranked = client.rerank(
    model="rerank-english-v3.0",
    query="user question",
    documents=initial_results,
    top_n=3
)

# Stage 3: Generate with top results
top_docs = [initial_results[r.index] for r in reranked.results]
response = client.chat(
    model="command-r-plus",
    message="user question",
    documents=[{"text": d} for d in top_docs]
)

License

Apache-2.0

Metadata

Release files for traceAI-cohere 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for traceAI-cohere 0.1.1
File Size Uploaded Provenance Actions
traceai_cohere-0.1.1.tar.gz 11.0 kB With provenance Details for traceai_cohere-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for traceAI-cohere 0.1.1
File Interpreter ABI Platform Actions
traceai_cohere-0.1.1-py3-none-any.whl Python 3 none any Details for traceai_cohere-0.1.1-py3-none-any.whl

Total release size: 22.8 kB

Release files / traceai_cohere-0.1.1.tar.gz

Download URL traceai_cohere-0.1.1.tar.gz
Size 11.0 kB
Tags Source
SHA-256 checksum
How to use checksums
08f124785035568bd91cb8f6509065363cfae6aac5d6b87518cadd8569a8c445
BLAKE2b-256 checksum
How to use checksums
1b73b9f31639725fb3719631a3fd6aa7974ff56ad008514649a1a5d5b300da12
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 31, 2026.

Transparency log

Release files / traceai_cohere-0.1.1-py3-none-any.whl

Download URL traceai_cohere-0.1.1-py3-none-any.whl
Size 11.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a1588f5972ec2db42fd5a1b55c67daa3b47568586fadc9f57b28a3445c3f6c1e
BLAKE2b-256 checksum
How to use checksums
fb4eb50ff2656655fe02736fc059b522d25f501240fd116a262cde63f6c9a600
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 31, 2026.

Transparency log

Security for traceAI-cohere 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for traceai_cohere-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 31, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page