Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,14 @@ CI supports Python 3.11–3.14; root CI also spans Linux, macOS, and Windows.

- Handler/decorator/OpenAI/ADK telemetry uses the internal logged-step path and converts completed steps to immutable
OTel spans. The internal trace envelope is never exported as a span.
- The first explicit OTLP `start_trace()` freezes name, metadata, tags, and all three dataset fields privately.
Carry the declaration only on the SDK-owned root. The first operation under a declared envelope is the OTel root.
Preserve ordinary span dataset inheritance and keep actual and redacted I/O on operation spans.
- Public trace-envelope I/O is deprecated for OTLP. Hook-backed loggers retain envelope I/O. Internal integrations use
unmarked `_start_trace_envelope()` bookkeeping. Low-level `add_trace()` remains unmarked. Public `created_at`,
`duration_ns`, and `external_id` are deprecated and ignored.
- Warn and return `None` when an upstream or completed root leaves no open SDK-owned root. Reject duplicate
declarations on an open SDK trace. Automatic integrations and decorators can declare while their SDK root is open.
- `start_splunk_ao_span()` is SDK-native OTel. `add_splunk_ao_span_processor()` and A2A instrument caller-owned OTel.
`configure_distributed_tracing()` is the combined automatic HTTP setup: it creates or accepts an application-owned
provider, registers Splunk AO export once per provider, configures supported upstream instrumentors, and returns the
Expand Down
26 changes: 26 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,32 @@ internal trace/step model. Stable OTel context is associated with actual operati
OTel spans; the `LoggedTrace` envelope remains an internal lifecycle container and must not become a wire span.
An explicit display name is carried as `splunk_ao.span.name`. The converter keeps the existing GenAI `Span.name`.

The first explicit OTLP `start_trace()` freezes supplied name, metadata, tags, and dataset input, output, and metadata.
The snapshot contains `splunk_ao.trace.schema_version=1`, scalar text for dataset input and output, and JSON objects
with string values for both metadata maps. The logger stores the snapshot on the open SDK root or its internal
envelope. For a declared envelope, the first operation is the OTel root and later operations use that root as their
OTel parent. Conversion adds the snapshot only to the root `ReadableSpan`. Go ingestion applies it when building
the trace record.

The backend derives trace timing and operation I/O from real spans. Explicit input and redacted input to
`start_trace()`, and explicit output and redacted output to `conclude()` when closing a manually started trace, are
deprecated on the OTLP path. Hook-backed loggers still accept envelope I/O. Operation I/O, including redacted content,
uses the span's existing attributes. Dataset fields specified when opening an envelope continue to be inherited as
ordinary `splunk_ao.dataset.*` span attributes.

`add_retriever_span()` converts supplied results to documents for `gen_ai.retrieval.documents`. It leaves
`redacted_output` unset when omitted or `None`, so conversion omits `splunk_ao.redacted_output`. An explicit
empty list exports as JSON `[]`.

Internal integrations and decorators use unmarked `_start_trace_envelope()` bookkeeping. The low-level `add_trace()`
and single-LLM convenience path remain unmarked. Hook-backed loggers retain the existing envelope lifecycle and
payload. Deprecated public `start_trace()` timing and external-ID arguments are ignored. Private integration timing
and actual operation timing remain supported.

The open SDK root or envelope holds the declaration for duplicate detection. A call without an open SDK-owned root
logs a warning when an OTel trace is already active. Existing integrations and downstream operations continue to
inherit the upstream trace ID and sampling through normal OTel propagation.

Do not bypass this path when extending an existing handler. It centralizes lifecycle behavior, content conversion,
session handling, and compatibility hooks. Conversion changes must cover workflow, agent, LLM, tool, retriever, and
Agent Control kinds that they affect.
Expand Down
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- OTLP `start_trace()` declares optional name, metadata, tags, and dataset context on the SDK-owned root. It
returns a local envelope when starting a trace. On an existing trace it returns `None`, and warns if the SDK
has no open root to declare on. A duplicate declaration on an open SDK trace warns and raises `ValueError`.

### Deprecated

- On the OTLP path, passing `input` or `redacted_input` to `start_trace()`, or passing `output` or `redacted_output`
to `conclude()` when closing a manually started trace, emits `DeprecationWarning`. Supply these values on operation
spans. Hook-backed loggers continue to accept them on the envelope.
- Public `start_trace(created_at=..., duration_ns=..., external_id=...)` accepts but ignores these values and emits
`DeprecationWarning`, including for hook-backed callers. Use metadata for business identifiers.

### Fixed

- Workflow and agent decorators preserve mapped metadata and tags on their operation spans, including continuations.
- `add_retriever_span()` omits the redacted output attribute when `redacted_output` is omitted or `None`.
Explicit redacted results, including an empty list, are still exported.

## [0.8.1]

### Added
Expand Down
46 changes: 44 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,11 @@ def retrieve_documents(query: str) -> list[str]:
retrieve_documents(query="history")
```

When logging a retriever manually with `add_retriever_span()`, pass
`redacted_output` to include a redacted document list alongside the retrieved
documents. Omitting it or passing `None` leaves the redacted output unset.
An explicit empty list records an empty redacted result.

Create a tool span:

```python
Expand Down Expand Up @@ -265,7 +270,7 @@ from splunk_ao.logger import SplunkAOLogger

logger = SplunkAOLogger(project="gen-ai-project", agent_stream="production")
try:
logger.start_trace("Say this is a test")
logger.start_trace(name="Test conversation")
logger.add_llm_span(
input="Say this is a test",
output="Hello, this is a test",
Expand All @@ -275,7 +280,7 @@ try:
total_tokens=13,
duration_ns=1000,
)
logger.conclude(output="Hello, this is a test", duration_ns=1000)
logger.conclude()
finally:
logger.terminate()
```
Expand All @@ -286,6 +291,43 @@ for normal scheduled export. `terminate()` drains completed spans and shuts
down resources owned by `SplunkAOLogger`; it does not turn unfinished manual
spans into completed spans.

On the OTLP path, `start_trace()` declares optional `name`, `metadata`, `tags`,
`dataset_input`, `dataset_output`, and `dataset_metadata` for the current OTel
trace. The first explicit call freezes supplied values, including explicit
empty values, as version 1 `splunk_ao.trace.*` attributes. Backend trace-field
projection requires compatible Go OTel ingestion.

With no active trace, `start_trace()` opens a local envelope and the first
operation becomes the OTel root. Call `conclude()` to close that envelope.
When the SDK already owns an open root, `start_trace()` sets its fields and
returns `None`. The code that opened the root still owns its lifecycle.

When the active trace has no open SDK-owned root, `start_trace()` logs a
warning and returns `None`. Use `add_workflow_span()` or `add_agent_span()`
to join the existing trace and `conclude()` to finish the local span. Only the
SDK root exports the declaration.

Supply actual input, output, and any redacted versions on operation spans.
The backend derives the trace's operation I/O from its real spans. For OTLP,
`start_trace(input=..., redacted_input=...)` and passing `output` or
`redacted_output` to `conclude()` when closing a manually started trace are
deprecated. Loggers using an `ingestion_hook` still open and return an
envelope that accepts those I/O arguments.
Dataset context supplied when opening an envelope also uses the ordinary
span dataset attributes inherited by operations.

Declare trace fields once while the SDK root is open. A call with every field
omitted still creates a declaration. A duplicate on that open trace logs a
warning and raises `ValueError`. This also applies when `@log` or an integration
opened the SDK root.

The `start_trace()` arguments `created_at`, `duration_ns`, and `external_id`
are deprecated and ignored, including with an `ingestion_hook`. Actual operation
timing APIs are unchanged. The backend uses the OTel trace ID for correlation;
put business identifiers in metadata instead. No artificial span, sampling
override, or separate network call is added. Without an exported real operation,
the declaration is not delivered.

#### Using Agent Observability context with Agent Control

If you use Agent Control hosted by Splunk, initialize Agent Control with the
Expand Down
4 changes: 4 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
| [healthcare-assistant](agent/healthcare-assistant/README.md) | LangGraph + Streamlit | Full-stack chat app with RAG, text-to-SQL, hallucination demo, and Splunk AO tracing |
| [banking-agent](logging-samples/agent-streams/README.md) | OpenAI | Tool-using banking agent with Agent Stream routing and a shared session |

## Logging examples

- [Span names, metadata, and trace declarations](logging-samples/span-names/README.md)

## Preconditions

Install `uv`, we use inline dependency inside scripts.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,36 @@
Log intentional hallucinations to Splunk Agent Observability for demos.
Examples are defined in config.yaml under `demo_hallucinations`.
"""

import logging
import os
from typing import Any, List, Optional, Union
from typing import Any

from splunk_ao import SplunkAOLogger
from langchain_core.messages import AIMessage, HumanMessage

from splunk_ao import SplunkAOLogger

logger = logging.getLogger(__name__)


def log_hallucination(
project_name: str,
agent_stream: str,
question: str,
context_docs: List[str],
context_docs: list[str],
hallucinated_answer: str,
model: str = "gpt-4o",
session_name: str = "Hallucination Demo",
external_session_id: Optional[str] = None,
existing_logger: Optional[Union[SplunkAOLogger, Any]] = None,
external_session_id: str | None = None,
existing_logger: SplunkAOLogger | Any | None = None,
) -> bool:
"""
Log a hallucination trace to Splunk AO for demonstration purposes.

Creates a trace with a retriever span (real context) and an LLM span (wrong answer).
"""
try:
logger.info(
"Logging hallucination to project: %s, agent stream: %s",
project_name,
agent_stream,
)
logger.info("Logging hallucination to project: %s, agent stream: %s", project_name, agent_stream)

if existing_logger:
logger.info("Using existing Splunk AO session for hallucination demo")
Expand All @@ -50,25 +48,13 @@ def log_hallucination(
if external_session_id:
splunk_ao_logger.set_session(external_session_id)

splunk_ao_logger.start_trace(
input=question,
name="Hallucination Demo",
)
splunk_ao_logger.start_trace(name="Hallucination Demo")

# Wrap spans in a workflow so the console shows "Hallucination Demo" as the
# root name — splunk-ao OTel converter derives span names from type+model for
# LLM spans, ignoring name=, so a workflow span is needed as the visible root.
splunk_ao_logger.add_workflow_span(
input=question,
name="Hallucination Demo",
)
# The workflow holds the overall question and answer.
splunk_ao_logger.add_workflow_span(input=question, name="Hallucination Demo")

splunk_ao_logger.add_retriever_span(
input=question,
output=context_docs,
name="RAG Retrieval",
duration_ns=int(1.3e8),
status_code=200,
input=question, output=context_docs, name="RAG Retrieval", duration_ns=int(1.3e8), status_code=200
)

context_text = "\n\n".join(context_docs)
Expand All @@ -94,17 +80,8 @@ def log_hallucination(
)

# Conclude the workflow span, then the trace
splunk_ao_logger.conclude(
output=hallucinated_answer,
duration_ns=int(2.5e8),
status_code=200,
)

splunk_ao_logger.conclude(
output=hallucinated_answer,
duration_ns=int(2.5e8),
status_code=200,
)
splunk_ao_logger.conclude(output=hallucinated_answer, duration_ns=int(2.5e8), status_code=200)
splunk_ao_logger.conclude()

logger.info("Successfully logged hallucination to project: %s", project_name)
return True
Expand All @@ -117,8 +94,8 @@ def log_hallucination(
def log_demo_hallucination(
config: dict,
hallucination_index: int = 0,
existing_logger: Optional[Union[SplunkAOLogger, Any]] = None,
session_id: Optional[str] = None,
existing_logger: SplunkAOLogger | Any | None = None,
session_id: str | None = None,
) -> bool:
"""Log a demo hallucination from config.yaml to Splunk AO."""
project_name = os.getenv("SPLUNK_AO_PROJECT", "healthcare-assistant")
Expand Down Expand Up @@ -160,12 +137,9 @@ def log_demo_hallucination(
)


def add_hallucination_interaction_to_chat(
config: dict,
hallucination_index: int = 0,
) -> None:
def add_hallucination_interaction_to_chat(config: dict, hallucination_index: int = 0) -> None:
"""Append the demo hallucination Q&A pair to the Streamlit chat history."""
import streamlit as st
import streamlit as st # noqa: PLC0415 - only the chat UI needs Streamlit

hallucinations = config.get("demo_hallucinations", [])
if not hallucinations:
Expand All @@ -184,9 +158,5 @@ def add_hallucination_interaction_to_chat(
if "messages" not in st.session_state:
st.session_state.messages = []

st.session_state.messages.append(
{"message": HumanMessage(content=question), "agent": "user"}
)
st.session_state.messages.append(
{"message": AIMessage(content=answer), "agent": "assistant"}
)
st.session_state.messages.append({"message": HumanMessage(content=question), "agent": "user"})
st.session_state.messages.append({"message": AIMessage(content=answer), "agent": "assistant"})
6 changes: 3 additions & 3 deletions examples/agent/startup-simulator-3000/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ cat .env

```bash
# Change the port in app.py or kill the existing process
# In app.py, change: app.run(debug=True, host='0.0.0.0', port=2021)
# to: app.run(debug=True, host='0.0.0.0', port=2022)
# In app.py, change: app.run(port=2021)
# to: app.run(port=2022)
```

**4. Splunk AO logging not working**
Expand Down Expand Up @@ -286,4 +286,4 @@ If you run into issues:

**Happy Startup Pitching! 🚀**

*Built with ❤️ and silliness for those exploring the world of AI*
*Built with ❤️ and silliness for those exploring the world of AI*
Loading
Loading