OpenTelemetry Cohere Instrumentation

0.58.0 · active · verified Thu Apr 09

This library provides OpenTelemetry instrumentation for the Cohere Python SDK, enabling automatic tracing of calls to Cohere's language model endpoints. It helps monitor performance, token usage, and costs associated with LLM applications. Regularly updated, the current version is 0.58.0, with releases occurring frequently, sometimes multiple times a month.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up OpenTelemetry tracing for Cohere API calls. It initializes a basic OpenTelemetry SDK with a console exporter, instruments the Cohere library, and then makes a sample chat completion request. Ensure the `COHERE_API_KEY` environment variable is set before running.

import os
import cohere
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.cohere import CohereInstrumentor

# 1. Set up OpenTelemetry SDK for console output
resource = Resource.create({"service.name": "my-cohere-app"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# 2. Instrument Cohere
CohereInstrumentor().instrument()

# 3. Use Cohere client (ensure COHERE_API_KEY environment variable is set)
cohere_api_key = os.environ.get('COHERE_API_KEY', '')

if not cohere_api_key:
    print("Warning: COHERE_API_KEY environment variable not set. Cohere client may fail.")
    # For demonstration, you might want to uncomment and replace 'YOUR_COHERE_API_KEY' for testing
    # cohere_api_key = 'YOUR_COHERE_API_KEY'

if cohere_api_key:
    try:
        client = cohere.Client(cohere_api_key)
        response = client.chat(
            model="command",
            message="Hello, how are you today?"
        )
        print("\nCohere Response:", response.text)
        print("\nTraces should be printed to the console above.")
    except Exception as e:
        print(f"Error calling Cohere: {e}")
else:
    print("Skipping Cohere call because API key is not available.")

view raw JSON →