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

# Python

> Reference documentation for the HoneyHive Logger SDK functions: `start`, `log`, and `update`.

## Overview

The `honeyhive_logger` provides a lightweight, dependency-free way to send session and event data to HoneyHive. It directly wraps HoneyHive's `/session/start` and `/events` API endpoints.

This SDK has **no external dependencies** beyond built-in Python packages, making it ideal for:

* Serverless execution environments (like AWS Lambda, Google Cloud Functions).
* Highly regulated environments with strict security requirements where adding dependencies is difficult.
* Situations where you need simple, stateless logging without the overhead of a full tracing implementation.

For more comprehensive tracing capabilities, including automatic instrumentation and context propagation, consider using the [HoneyHive's Python Tracer SDK](/sdk-reference/python-tracer-ref).

For detailed schema information, refer to the [Schema Overview](/schema-overview) in the main HoneyHive documentation.

## Installation

```bash theme={null}
pip install honeyhive-logger
```

## Basic Usage

```python theme={null}
from honeyhive_logger import start, log, update
import os

# Start a new session
# Session ID is required for subsequent log/update calls if not passed explicitly
session_id = start(
    api_key=os.environ["HH_API_KEY"],
    project=os.environ["HH_PROJECT"],
    session_name="v1",
    source="dev",
    config={
        "model": "gpt-4",
        "temperature": 0.7
    }
)

# Log an event (e.g., a model call) within the session
event_id = log(
    session_id=session_id,
    event_name="model_inference",
    event_type="model",
    config={
        "model": "gpt-4",
        "temperature": 0.7
    },
    inputs={
        "prompt": "Hello world"
    },
    outputs={
        "response": "Hi there!"
    }
)

# Update the event later (e.g., with user feedback)
update(
    event_id=event_id,
    feedback={
        "rating": 5,
        "comment": "Great response!"
    },
    metrics={
        "latency": 100,
        "tokens": 50
    }
)

# You can also update the session itself
update(
    event_id=session_id,
    metadata={
        "status": "completed"
    }
)


print(f"Session Started: {session_id}")
print(f"Event Logged: {event_id}")
print("Event and Session Updated.")
```

## API Reference

### `start()`

Starts a new session in HoneyHive. A session acts as a container for related events.

**Parameters:**

* **api\_key** (`str`, optional): Your HoneyHive API key. If not provided, the logger checks the `HH_API_KEY` environment variable. **Required** either as an argument or environment variable.
* **project** (`str`, optional): The name of your project in HoneyHive. If not provided, the logger checks the `HH_PROJECT` environment variable. **Required** either as an argument or environment variable.
* **session\_name** (`str`, optional): An optional name or tag for the session (e.g., "v1.2", "user\_chat\_abc", commit hash). Helps in filtering sessions later. Defaults to the `project` name if not provided.
* **source** (`str`, optional): Identifier for the environment or component where the session originates (e.g., "production", "staging", "sdk\_test"). Defaults to the `HH_SOURCE` environment variable or "dev".
* **config** (`dict`, optional): Dictionary containing configuration details relevant to the entire session (e.g., system prompts, global settings). Defaults to `{}`.
* **inputs** (`dict`, optional): Dictionary containing initial input parameters for the session. Defaults to `{}`.
* **metadata** (`dict`, optional): Dictionary for additional arbitrary metadata associated with the session. Defaults to `{}`.
* **user\_properties** (`dict`, optional): Dictionary for user-defined properties associated with the session. Defaults to `{}`.
* **session\_id** (`str`, optional): A specific UUIDv4 string to use as the session ID. Useful for correlating with external logs or resuming sessions. If not provided, a new UUIDv4 is generated automatically.
* **server\_url** (`str`, optional): The URL of the HoneyHive API server. Defaults to the `HH_API_URL` environment variable or `"https://api.honeyhive.ai"`.
* **verbose** (`bool`, optional): If `True`, prints detailed debug information, including request data and error messages, to the console. Defaults to `False`.
* **ca\_bundle\_path** (`str`, optional): Path to a custom Certificate Authority (CA) bundle file for SSL verification. If `None`, uses the system's default CA store. See [SSL Certificate Handling](#ssl-certificate-handling). Defaults to `None`.

**Returns:**

* `str`: The unique session ID (UUIDv4 format) for the created session. This ID is needed to log events within this session or to update the session later.

**Raises:**

* `Exception`: If `api_key` or `project` is missing (and not set via environment variables).
* `Exception`: If the API call fails after retries (e.g., network error, invalid API key, server error). More details are printed if `verbose=True`.

**Example:**

```python theme={null}
session_id = start(
    project="Chatbot-Prod",
    session_name="customer-support-chat-xyz",
    source="prod-web-server-1",
    config={"base_prompt_version": "v3"},
    inputs={"initial_query": "How do I reset my password?"},
    metadata={"customer_tier": "gold"},
    user_properties={"user_id": "usr_12345"}
)
print(f"Session started with ID: {session_id}")
```

***

### `log()`

Logs a specific event (like a model call, tool usage, or a step in a chain) within a session to HoneyHive.

**Parameters:**

* **api\_key** (`str`, optional): Your HoneyHive API key. Defaults to `HH_API_KEY` env var. **Required**.
* **project** (`str`, optional): Your project name. Defaults to `HH_PROJECT` env var. **Required**.
* **source** (`str`, optional): Environment identifier. Defaults to `HH_SOURCE` env var or "dev".
* **event\_name** (`str`): A descriptive name for the event being logged (e.g., "generate\_summary", "vector\_db\_lookup"). **Required**.
* **event\_type** (`str`, optional): The type of the event. Must be one of `"model"`, `"tool"`, or `"chain"` (case-insensitive). Defaults to `"tool"`.
* **config** (`dict`, optional): Configuration details specific to this event (e.g., model parameters like temperature, tool parameters). Defaults to `{}`.
* **inputs** (`dict`, optional): Input parameters for this specific event (e.g., prompt for a model, query for a tool). Defaults to `{}`.
* **outputs** (`dict`, optional): Output data generated by this event (e.g., model response, tool result). Defaults to `{}`.
* **metadata** (`dict`, optional): Additional arbitrary metadata for this event. Defaults to `{}`.
* **session\_id** (`str`): The ID of the session this event belongs to (obtained from `start()`). **Required**.
* **duration\_ms** (`int`, optional): The duration of the event execution in milliseconds. If not provided, defaults to `10`.
* **server\_url** (`str`, optional): HoneyHive API server URL. Defaults to `HH_API_URL` env var or `"https://api.honeyhive.ai"`.
* **verbose** (`bool`, optional): Enable detailed debug logging. Defaults to `False`.
* **ca\_bundle\_path** (`str`, optional): Path to a custom CA bundle file. Defaults to `None`.

**Returns:**

* `str`: The unique event ID (UUIDv4 format) for the logged event. This ID can be used with `update()` to add feedback or metrics later.

**Raises:**

* `Exception`: If `api_key`, `project`, `event_name`, or `session_id` is missing.
* `Exception`: If `event_type` is not one of the valid types ("model", "tool", "chain").
* `Exception`: If the API call fails after retries. More details if `verbose=True`.

**Example:**

```python theme={null}
# Assuming session_id was obtained from start()
event_id = log(
    session_id=session_id,
    event_name="retrieve_documents",
    event_type="tool", # Or "model", "chain"
    config={"vector_db_index": "product_docs_v2"},
    inputs={"query": "features of product X"},
    outputs={"retrieved_docs": ["doc1_content", "doc2_content"]},
    metadata={"retrieval_score_threshold": 0.8},
    duration_ms=150 # Measured duration
)
print(f"Event logged with ID: {event_id}")
```

***

### `update()`

Updates an existing event or session with additional data, such as feedback, metrics, or updated metadata/outputs.

**Parameters:**

* **api\_key** (`str`, optional): Your HoneyHive API key. Defaults to `HH_API_KEY` env var. **Required**.
* **event\_id** (`str`): The ID of the item to update. This **must** be either:
  * A `session_id` returned from `start()` to update the session.
  * An `event_id` returned from `log()` to update a specific event.
    **Required**.
* **metadata** (`dict`, optional): Dictionary of metadata to add or update. Existing keys will be overwritten.
* **feedback** (`dict`, optional): Dictionary containing user feedback (e.g., ratings, corrections, comments).
* **metrics** (`dict`, optional): Dictionary containing computed metrics (e.g., latency, token counts, evaluation scores).
* **config** (`dict`, optional): Dictionary of configuration settings to add or update.
* **outputs** (`dict`, optional): Dictionary of output data to add or update.
* **user\_properties** (`dict`, optional): Dictionary of user properties to add or update (typically used when updating a session).
* **duration\_ms** (`int`, optional): Update the duration of the event in milliseconds.
* **server\_url** (`str`, optional): HoneyHive API server URL. Defaults to `HH_API_URL` env var or `"https://api.honeyhive.ai"`.
* **verbose** (`bool`, optional): Enable detailed debug logging. Defaults to `False`.
* **ca\_bundle\_path** (`str`, optional): Path to a custom CA bundle file. Defaults to `None`.

**Returns:**

* `None`

**Raises:**

* `Exception`: If `api_key` or `event_id` is missing.
* `Exception`: If `event_id` is not a valid UUID.
* `Exception`: If the API call fails after retries. More details if `verbose=True`.

**Example:**

```python theme={null}
# Update an event (using event_id from log())
update(
    event_id=event_id, # ID from log()
    feedback={"user_rating": 1, "reason": "Inaccurate information"},
    metrics={"similarity_score": 0.65}
)

# Update a session (using session_id from start())
update(
    event_id=session_id, # ID from start()
    metadata={"final_status": "escalated_to_human"},
    user_properties={"conversation_length": 15}
)
print("Event and Session updated.")
```

## Error Handling

Without `verbose` set to True, all errors are swallowed.

If true, the logger will raise exceptions for:

* Invalid API keys
* Network errors
* Invalid parameters
* Server errors

Each error includes detailed information about what went wrong and how to fix it. For example:

* Missing required parameters
* Invalid event types
* API key or project not found
* Network connectivity issues
* Server-side errors

## SSL Certificate Handling

The logger uses HTTPS for secure communication. If you operate in an environment with specific SSL/TLS requirements (like behind a corporate proxy with custom certificates), you might encounter SSL certificate verification errors.

### Using a Custom CA Bundle

The recommended solution is to provide a path to a custom Certificate Authority (CA) bundle file using the `ca_bundle_path` parameter available in `start()`, `log()`, and `update()`:

```python theme={null}
start(
    # ... other args ...
    ca_bundle_path="/path/to/your/company/ca-bundle.pem"
)

log(
    # ... other args ...
    ca_bundle_path="/path/to/your/company/ca-bundle.pem"
)

update(
    # ... other args ...
    ca_bundle_path="/path/to/your/company/ca-bundle.pem"
)
```

This tells the underlying `urllib` library to use your specified file for verifying the server's certificate.

### Other Potential Solutions

1. **Update System Certificates**:
   * On macOS: `brew install ca-certificates`
   * On Ubuntu/Debian: `sudo apt-get install ca-certificates`
   * On CentOS/RHEL: `sudo yum install ca-certificates`

2. **Environment Variable**:
   Set the `REQUESTS_CA_BUNDLE` or `CURL_CA_BUNDLE` environment variable:
   ```bash theme={null}
   export REQUESTS_CA_BUNDLE=/path/to/custom/ca-bundle.crt
   ```

3. **Corporate Proxy/VPN**:
   * Export your proxy's root certificate and add it to your system's trust store
   * Or use the custom CA bundle approach with your proxy's certificate
   * Ensure your VPN is properly configured to handle HTTPS traffic
