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

# Splunk Agent Observability Context

> Manage trace context and control logging behavior with the Splunk Agent Observability Context Manager

The Splunk Agent Observability Context Manager provides a convenient way to control the logging behavior of your application. It allows you to:

1. Set the project and Agent Stream for all logs
2. Get the current logger
3. Flush traces

In Python, you can also:

1. Set the project and Agent Stream for a particular scope
2. Manage sessions
3. Get the current span and trace

In the Python SDK, this is available through the [`splunk_ao_context` object](/sdk-api/python/reference/decorator).

## Set the project and Agent Stream

By default, Splunk Agent Observability uses the `SPLUNK_AO_PROJECT` and `SPLUNK_AO_AGENT_STREAM` environment variables to determine which project and Agent Stream to log to. You can override this by initializing the Splunk Agent Observability context with a project and Agent Stream name.

<CodeGroup>
  ```python Python theme={null}
  from splunk_ao import splunk_ao_context

  splunk_ao_context.init(project="my-project",agent_stream="my-agent-stream")
  ```

  ```python Python (Beta) theme={null}
  from splunk_ao import AgentStream

  agent_stream = AgentStream.get(name="my-agent-stream", project_name="my-project")

  # Or create a new one
  # agent_stream = AgentStream(name="my-agent-stream", project_name="my-project").create()

  # Route traces to the specified Agent Stream
  with agent_stream.context():
      # Every trace logged inside this block goes to the Agent Stream above
      ...
  ```
</CodeGroup>

### Set the project and Agent Stream for a single scope in Python

You can set the project and Agent Stream for a scope using the Python [`splunk_ao_context`](/sdk-api/python/reference/decorator), object in a with statement. Every log inside this block, including nested calls, will use the specified project and Agent Stream.

<CodeGroup>
  ```python Python theme={null}
  from splunk_ao import splunk_ao_context

  # This will log to the specified project and Agent Stream
  with splunk_ao_context(project="my-project", agent_stream="my-agent-stream"):
      # All operations within this block will be logged to the same trace
      # in the specified project and Agent Stream
      result = your_function()
      print(result)
  ```

  ```python Python (Beta) theme={null}
  from splunk_ao import AgentStream

  # Get the Agent Stream
  agent_stream = AgentStream.get(name="my-agent-stream", project_name="my-project")

  def your_function():
      # Function implementation
      return "result"

  # This will log to the specified project and Agent Stream
  with agent_stream.context():
      # All operations within this block will be logged to the same trace
      # in the specified project and Agent Stream
      result = your_function()
      print(result)
  ```
</CodeGroup>

This also works with the `@log` decorator.

<CodeGroup>
  ```python Python theme={null}
  from splunk_ao import log, splunk_ao_context

  @log
  def make_nested_call():
      # Function implementation
      return "result"

  # This will log to the specified project and Agent Stream
  with splunk_ao_context(project="my-project", agent_stream="my-agent-stream"):
      content = make_nested_call()
      print(content)
  ```

  ```python Python (Beta) theme={null}
  from splunk_ao import log
  from splunk_ao import AgentStream

  @log
  def make_nested_call():
      # Function implementation
      return "result"

  # Get the Agent Stream
  agent_stream = AgentStream.get(name="my-agent-stream", project_name="my-project")

  # This will log to the specified project and Agent Stream
  with agent_stream.context():
      content = make_nested_call()
      print(content)
  ```
</CodeGroup>

Third-party integrations like the OpenAI wrapper also support this.

<CodeGroup>
  ```python Python theme={null}
  import os
  from splunk_ao import splunk_ao_context, openai

  # Initialize the Splunk Agent Observability wrapped OpenAI client
  client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

  # This will log to the specified project and Agent Stream
  with splunk_ao_context(project="my-project", agent_stream="my-agent-stream"):
      chat_completion = client.chat.completions.create(
          messages=[{"role": "user", "content": "Say this is a test"}],
          model="gpt-4o"
      )
      print(chat_completion.choices[0].message.content)
  ```

  ```python Python (Beta) theme={null}
  import os
  from splunk_ao import AgentStream
  from splunk_ao import openai

  # Get the Agent Stream
  agent_stream = AgentStream.get(name="my-agent-stream", project_name="my-project")

  # Initialize the Splunk Agent Observability wrapped OpenAI client
  client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

  # This will log to the specified Agent Stream
  with agent_stream.context():
      chat_completion = client.chat.completions.create(
          messages=[{"role": "user", "content": "Say this is a test"}],
          model="gpt-4o"
      )
      print(chat_completion.choices[0].message.content)
  ```
</CodeGroup>

### Nesting scopes

You can nest `splunk_ao_context` calls to temporarily override the project or Agent Stream:

<CodeGroup>
  ```python Python theme={null}
  from splunk_ao import splunk_ao_context

  with splunk_ao_context(project="my-project", agent_stream="my-agent-stream"):
      # This will log to my-project/my-agent-stream
      operation_1()

      with splunk_ao_context(agent_stream="sub-stream"):
          # This will log to my-project/sub-stream
          operation_2()

      # Back to logging to my-project/my-agent-stream
      operation_3()
  ```
</CodeGroup>

## Get the current logger

The Splunk Agent Observability context management keeps track of loggers. You can get the current logger, which will create a new one if there isn't an existing logger.

<CodeGroup>
  ```python Python theme={null}
  from splunk_ao import splunk_ao_context

  # Get the current logger
  logger = splunk_ao_context.get_logger_instance()
  ```
</CodeGroup>

If you are using any of the decorators, wrappers, or third-party integrations then this allows you to get the logger created by those components. For example, if you are adding a call inside a method decorated by the Python `@log` decorator or created automatically by an experiment, then this will return that logger instance so you can manually add additional spans.

<CodeGroup>
  ```python Python theme={null}
  from splunk_ao import log, splunk_ao_context

  @log(span_type="llm")
  def logged_function(input_text):
      # Get the current logger
      logger = splunk_ao_context.get_logger_instance()

      # Add a span
      workflow_span = logger.add_workflow_span(
          input="My workflow"
      )
  ```
</CodeGroup>

## Flush logs

To keep your app performant, logs are not continually flushed. In some cases, you may want to flush traces explicitly:

<CodeGroup>
  ```python Python theme={null}
  import os
  from splunk_ao import splunk_ao_context, openai

  # Initialize the Splunk Agent Observability wrapped OpenAI client
  client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

  def call_openai():
      chat_completion = client.chat.completions.create(
          messages=[{"role": "user", "content": "Say this is a test"}],
          model="gpt-4o"
      )
      return chat_completion.choices[0].message.content

  # This will create a single span trace with the OpenAI call
  call_openai()

  # This will upload the trace to Splunk Agent Observability
  splunk_ao_context.flush()
  ```
</CodeGroup>

This approach is particularly useful for long-running applications where you need to control when traces are flushed to Splunk Agent Observability.

<Note>
  When using a Python Notebook (such as Jupyter, Google Colab, etc.), you should use the `splunk_ao_context` and make sure to call `splunk_ao_context.flush()` at the end of your notebook.
</Note>

## Manage sessions in Python

With the Python SDK, you can manage [sessions](/concepts/logging/sessions/sessions-overview) from the context level in addition to the logger level. All the session management functions are applied to the current logger if called from the context. If you want to apply these to a specific logger instance, call the same methods directly on that logger instance.

### Create a new session

To create a new session, use the [`start_session`](/sdk-api/python/reference/decorator#start-session) function.

<CodeGroup>
  ```python Python theme={null}
  from splunk_ao import splunk_ao_context

  # Start a new session
  splunk_ao_context.start_session(name="My session")
  ```
</CodeGroup>

When you start a session you can optionally give it a name. If you don't provide a name, one is created for you based off the traces in the session.

You can also provide an external ID to link a session in Splunk Agent Observability to an external identifier.

<CodeGroup>
  ```python Python theme={null}
  from splunk_ao import splunk_ao_context

  # Start a new session
  splunk_ao_context.start_session(external_id=conversation_id)
  ```
</CodeGroup>

### Continue an existing session

If you want to add a trace to an existing session, you can use the `set_session` function, passing the session ID. This is useful if you want to persist a session, for example saving a chatbot conversation with a user mid-conversation, then resuming the next time a user connects.

<CodeGroup>
  ```python Python theme={null}
  from splunk_ao import splunk_ao_context

  # Start an existing session to add new traces to it
  splunk_ao_context.set_session(session_id=conversation_session_id)
  ```
</CodeGroup>

You can also continue a conversation using an external ID using the `start_session` function.

<CodeGroup>
  ```python Python theme={null}
  from splunk_ao import splunk_ao_context

  # Start an existing session by its external ID to add new traces to it
  splunk_ao_context.start_session(external_id=conversation_id)
  ```
</CodeGroup>

### End a session

To stop logging to a session, you can clear the current session.

<CodeGroup>
  ```python Python theme={null}
  from splunk_ao import splunk_ao_context

  # Clear the current session
  splunk_ao_context.clear_session()
  ```
</CodeGroup>

## Next steps

### Basic logging components

<CardGroup cols={2}>
  <Card title="Splunk Agent Observability logger" icon="code" horizontal href="/sdk-api/logging/splunk-ao-logger">
    Log with full control over sessions, traces, and spans using the Splunk Agent Observability logger.
  </Card>

  <Card title="Log decorator" icon="code" horizontal href="/sdk-api/logging/log-decorator/log-decorator">
    Quickly add logging to your code with the log decorator and wrapper.
  </Card>
</CardGroup>

### Integrations with third-party SDKs

<CardGroup cols={2}>
  <Card title="OpenAI wrapper" icon="code" horizontal href="/sdk-api/third-party-integrations/openai/openai">
    Automatically log calls to the OpenAI SDK with a wrapper.
  </Card>

  <Card title="OpenAI Agents trace processor" icon="code" horizontal href="/sdk-api/third-party-integrations/openai-agents/openai-agents">
    Automatically log all the steps in your OpenAI Agent SDK apps using the Splunk Agent Observability trace processor.
  </Card>

  <Card title="LangChain callback" icon="code" horizontal href="/sdk-api/third-party-integrations/langchain/langchain">
    Automatically log all the steps in your LangChain or LangGraph application with the Splunk Agent Observability callback.
  </Card>
</CardGroup>
