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

# Galileo Context

> Manage trace context and control logging behavior with the Galileo Context Manager

{/*<!-- markdownlint-enable MD044 -->*/}

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

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

In Python, you can also:

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

In the Python SDK, this is available through the [`galileo_context` object](/sdk-api/python/reference/decorator), in TypeScript this is available as a set of distinct [top-level functions](/sdk-api/typescript/reference/README/functions/).

## Set the project and Log stream

By default, Galileo uses the `GALILEO_PROJECT` and `GALILEO_LOG_STREAM` environment variables to determine which project and Log stream to log to. You can override this by initializing the Galileo context with a project and Log stream name.

<CodeGroup>
  ```python Python theme={null}
  from galileo import galileo_context

  galileo_context.init(project="my-project",log_stream="my-log-stream")
  ```

  ```python Python (Beta) theme={null}
  from galileo import LogStream

  log_stream = LogStream.get(name="my-log-stream", project_name="my-project")

  # Or create a new one
  # log_stream = LogStream(name="my-log-stream", project_name="my-project").create()

  # Route traces to the specified Log stream
  with log_stream.context():
      # Every trace logged inside this block goes to the Log stream above
      ...
  ```

  ```typescript TypeScript theme={null}
  import { init } from "galileo";

  init({
      projectName: "my-project",
      logstream: "my-log-stream",
  });
  ```
</CodeGroup>

### Set the project and Log stream for a single scope in Python

You can set the project and Log stream for a scope using the Python [`galileo_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 Log stream.

<CodeGroup>
  ```python Python theme={null}
  from galileo import galileo_context

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

  ```python Python (Beta) theme={null}
  from galileo import LogStream

  # Get the log stream
  log_stream = LogStream.get(name="my-log-stream", project_name="my-project")

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

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

This also works with the `@log` decorator.

<CodeGroup>
  ```python Python theme={null}
  from galileo import log, galileo_context

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

  # This will log to the specified project and Log stream
  with galileo_context(project="my-project", log_stream="my-log-stream"):
      content = make_nested_call()
      print(content)
  ```

  ```python Python (Beta) theme={null}
  from galileo import log
  from galileo import LogStream

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

  # Get the log stream
  log_stream = LogStream.get(name="my-log-stream", project_name="my-project")

  # This will log to the specified project and Log stream
  with log_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 galileo import galileo_context, openai

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

  # This will log to the specified project and Log stream
  with galileo_context(project="my-project", log_stream="my-log-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 galileo import LogStream
  from galileo import openai

  # Get the log stream
  log_stream = LogStream.get(name="my-log-stream", project_name="my-project")

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

  # This will log to the specified Log stream
  with log_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 `galileo_context` calls to temporarily override the project or Log stream:

<CodeGroup>
  ```python Python theme={null}
  from galileo import galileo_context

  with galileo_context(project="my-project", log_stream="my-log-stream"):
      # This will log to my-project/my-log-stream
      operation_1()

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

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

## Get the current logger

The Galileo 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 galileo import galileo_context

  # Get the current logger
  logger = galileo_context.get_logger_instance()
  ```

  ```typescript TypeScript theme={null}
  import { getLogger } from "galileo";

  // Get the current logger
  const galileoLogger = getLogger();
  ```
</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, wrapped in the TypeScript `log` wrapper, 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 galileo import log, galileo_context

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

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

  ```typescript TypeScript theme={null}
  import { getLogger, log } from "galileo";

  const wrappedFunc = log({}, async (input: any) => {
      // Get the current logger
      const galileoLogger = getLogger();

      // Add a span
      const workflowSpan = galileoLogger.addWorkflowSpan({
          input: "Process user request",
      });
  });
  ```
</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 galileo import galileo_context, openai

  # Initialize the Galileo 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 Galileo
  galileo_context.flush()
  ```

  ```typescript TypeScript theme={null}
  import { OpenAI } from "openai";
  import { wrapOpenAI, flush } from "galileo";

  const openai = wrapOpenAI(new OpenAI({ apiKey: process.env.OPENAI_API_KEY }));

  async function callOpenAI(prompt: string) {
      const response = await openai.chat.completions.create({
          model: "gpt-4.1-mini",
          messages: [{ role: "user", content: prompt }],
      });
      return response.choices[0].message.content;
  }

  const response = await callOpenAI("Tell me about the Roman Empire");

  // This will upload the trace to Galileo
  await flush();
  ```
</CodeGroup>

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

<Note>
  When using a Python Notebook (such as Jupyter, Google Colab, etc.), you should use the `galileo_context` and make sure to call `galileo_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.

In the TypeScript SDK, these functions are only available on a [GalileoLogger instance](/sdk-api/logging/galileo-logger#manage-sessions).

### 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 galileo import galileo_context

  # Start a new session
  galileo_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 Galileo to an external identifier.

<CodeGroup>
  ```python Python theme={null}
  from galileo import galileo_context

  # Start a new session
  galileo_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 galileo import galileo_context

  # Start an existing session to add new traces to it
  galileo_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 galileo import galileo_context

  # Start an existing session by its external ID to add new traces to it
  galileo_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 galileo import galileo_context

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

## Next steps

### Basic logging components

<CardGroup cols={2}>
  <Card title="Galileo logger" icon="code" horizontal href="/sdk-api/logging/galileo-logger">
    Log with full control over sessions, traces, and spans using the Galileo 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 Galileo 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 Galileo callback.
  </Card>
</CardGroup>
