Skip to main content

A helper package, to support implementation to AnoSys platform easly

Project description

AnoSys Logger for OpenAI - Python

License: MIT Python

Automatically capture and send OpenAI API calls to AnoSys for monitoring, analytics, and observability.

Features

Automatic OpenAI Instrumentation - Captures all OpenAI API calls via OpenTelemetry
Streaming Support - Detects and logs streaming responses
Custom Function Decorators - Log any Python function (sync or async)
OpenTelemetry Semantic Conventions - Follows Gen AI standards
Error Tracking - Captures exceptions with full stack traces
Zero Configuration - Works out of the box with just your API key

Installation

pip install anosys-logger-4-openai

Quick Start

1. Get Your AnoSys API Key

Visit https://console.anosys.ai/collect/integrationoptions to get your API key.

2. Basic Usage with OpenAI

import os
from openai import OpenAI
from AnosysLoggers import AnosysOpenAILogger

# Set your API keys
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["ANOSYS_API_KEY"] = "your-anosys-api-key"

# Initialize AnoSys logger (do this once)
AnosysOpenAILogger()

# Use OpenAI as normal - all calls are automatically logged
client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain why AnoSys is great for AI observability"}
    ]
)

print(response.choices[0].message.content)

That's it! All your OpenAI calls are now being sent to AnoSys. 🎉

Advanced Usage

Streaming Responses

Streaming is automatically detected and logged:

from openai import OpenAI
from AnosysLoggers import AnosysOpenAILogger

AnosysOpenAILogger()
client = OpenAI()

stream = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Write a haiku about AI"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

The complete aggregated response will be logged to AnoSys.

Custom Function Decorators

Log any Python function (sync or async):

from AnosysLoggers import anosys_logger

@anosys_logger(source="my_app.calculations")
def calculate_score(data):
    # Your function logic
    return sum(data) / len(data)

# Function calls are automatically logged
result = calculate_score([85, 90, 78, 92])

Async Functions:

@anosys_logger(source="my_app.async_tasks")
async def fetch_data(url):
    # Your async logic
    return await some_async_operation()

# Async calls are also logged
result = await fetch_data("https://api.example.com")

Raw Logger

Send custom data directly:

from AnosysLoggers import anosys_raw_logger

# Log any custom data
anosys_raw_logger({
    "event": "user_action",
    "action": "button_click",
    "timestamp": "2024-01-15T10:30:00Z",
    "user_id": "12345"
})

Custom Configuration

from AnosysLoggers import setup_api

# Use a custom endpoint (advanced)
setup_api(path="https://custom.anosys.endpoint")

# Or with custom index starting points (rarely needed)
setup_api(starting_indices={
    "string": 200,
    "number": 10,
    "bool": 5
})

What Data is Captured?

OpenTelemetry Semantic Conventions

Following the OpenTelemetry Gen AI standards:

  • gen_ai.system - Always "openai"
  • gen_ai.request.model - Model requested (e.g., "gpt-4o-mini")
  • gen_ai.response.model - Model that responded
  • gen_ai.request.temperature - Temperature parameter
  • gen_ai.request.max_tokens - Max tokens parameter
  • gen_ai.request.top_p - Top-p parameter
  • gen_ai.response.finish_reasons - Why the response ended
  • gen_ai.usage.input_tokens - Input token count
  • gen_ai.usage.output_tokens - Output token count

Additional Fields

  • Request/response messages
  • Timestamps and duration
  • Error details (if any)
  • Trace IDs for distributed tracing
  • Custom metadata

Error Handling

Errors are automatically captured with full context:

@anosys_logger(source="my_app.risky_function")
def risky_operation():
    raise ValueError("Something went wrong")

try:
    risky_operation()
except ValueError:
    pass  # Error is still logged to AnoSys with stack trace

Environment Variables

Variable Required Description
ANOSYS_API_KEY Yes Your AnoSys API key
OPENAI_API_KEY Yes Your OpenAI API key
ANOSYS_DEBUG_LOGS No Set to false to disable raw span logging

Requirements

  • Python 3.9 - 3.12
  • OpenAI Python SDK
  • OpenTelemetry SDK
  • traceai-openai

Troubleshooting

No data appearing in AnoSys?

  1. Check your API key: Ensure ANOSYS_API_KEY is set correctly
  2. Initialize before OpenAI calls: Call AnosysOpenAILogger() before making OpenAI requests
  3. Check network: Ensure you can reach https://api.anosys.ai

Import errors?

Make sure all dependencies are installed:

pip install --upgrade anosys-logger-4-openai

Support

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

anosys_logger_4_openai-0.0.11.tar.gz (18.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

anosys_logger_4_openai-0.0.11-py3-none-any.whl (16.8 kB view details)

Uploaded Python 3

File details

Details for the file anosys_logger_4_openai-0.0.11.tar.gz.

File metadata

  • Download URL: anosys_logger_4_openai-0.0.11.tar.gz
  • Upload date:
  • Size: 18.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for anosys_logger_4_openai-0.0.11.tar.gz
Algorithm Hash digest
SHA256 48d433499928779464e90e7ea1ce44e2abcd9898f21a54435d21d0efc52aaab1
MD5 7b69304fc55214585d7f969fcb1b0f56
BLAKE2b-256 26f79d6a2b152b3f7da15890cacf2f2d59bc2bb281b3bc4d2a529085221092af

See more details on using hashes here.

Provenance

The following attestation bundles were made for anosys_logger_4_openai-0.0.11.tar.gz:

Publisher: python-publish.yml on moisisv/anosys-logger-4-openai

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file anosys_logger_4_openai-0.0.11-py3-none-any.whl.

File metadata

File hashes

Hashes for anosys_logger_4_openai-0.0.11-py3-none-any.whl
Algorithm Hash digest
SHA256 7e1de9e46f35aac3c0e419ad983c2928c3de07675365b7ea715d9833a88b113d
MD5 9a990e4a1e9c36ed5e01889a0d2d63ab
BLAKE2b-256 520acfd7c8cb75fbfa3a46441ddc14919cf96942bee0c5c9bc36f8ba52136dfb

See more details on using hashes here.

Provenance

The following attestation bundles were made for anosys_logger_4_openai-0.0.11-py3-none-any.whl:

Publisher: python-publish.yml on moisisv/anosys-logger-4-openai

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page