> ## 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.

# Log Your First Trace

> Learn how to log your first trace with Galileo

## Create a Galileo Account

First create your Galileo account using the link below.

> [card] [Sign up for free](https://app.galileo.ai/sign-up)

## Add your first trace

This guide works with Python or TypeScript, using OpenAI, Azure OpenAI service, Anthropic, or Gemini LLMs.

**1. Install dependencies**

Install the **Galileo SDK** with OpenAI support, and the dotenv package using the following command in your terminal:

```bash Python theme={null}
pip install "galileo[openai]" python-dotenv
```

```bash TypeScript theme={null}
npm install galileo tsx dotenv
```

**2. Set up your environment variables**

Create an `.env` file in your project folder, and set:

* Your [Galileo API key](https://app.galileo.ai/settings/api-keys)
* Your [OpenAI API Key](https://platform.openai.com/settings/organization/api-keys).

```ini .env theme={null}
GALILEO_API_KEY="your-galileo-api-key"
OPENAI_API_KEY="your-openai-api-key"
# Provide the console url below if you are not using app.galileo.ai
# GALILEO_CONSOLE_URL="your-galileo-console-url"
```

**3. Create your application code**

Create a file called `app.py` (Python) or `app.ts` (TypeScript) and add the following code:

```python Python theme={null}
from galileo import galileo_context
from galileo.openai import openai
from galileo.config import GalileoPythonConfig
from dotenv import load_dotenv

# Load environment variables from the .env file
load_dotenv()

# Set the project and Log stream, these are created if they don't exist.
# You can also set these using the GALILEO_PROJECT and GALILEO_LOG_STREAM
# environment variables.
galileo_context.init(project="MyFirstEvaluation",
                     log_stream="MyFirstLogStream")

# Initialize the Galileo OpenAI client wrapper
client = openai.OpenAI()

# Define a system prompt with guidance
system_prompt = f"""
You are a helpful assistant that wants to provide a user as much
information as possible. Avoid saying I don't know.
"""

# Define a user prompt with a question
user_prompt = "Describe Galileo"

# Send a request to the LLM
response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt}
    ],
)

# Print the response
print(response.choices[0].message.content.strip())

# Show Galileo information after the response
config = GalileoPythonConfig.get()
logger = galileo_context.get_logger_instance()
project_url = f"{config.console_url}project/{logger.project_id}"
log_stream_url = f"{project_url}/log-streams/{logger.log_stream_id}"

print()
print("🚀 GALILEO LOG INFORMATION:")
print(f"🔗 Project   : {project_url}")
print(f"📝 Log Stream: {log_stream_url}")
```

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

// Load the environment variables
dotenv.config();

// Set the project and Log stream, these are created if they don't exist.
// You can also set these using the GALILEO_PROJECT and GALILEO_LOG_STREAM
// environment variables.
init({
    projectName: "MyFirstEvaluation",
    logStreamName: "MyFirstLogStream"
});

// Create an OpenAI wrapper
const openai = wrapOpenAI(new OpenAI());

// Define a system prompt with guidance
const systemPrompt = `
You are a helpful assistant that wants to provide a user as much
information as possible. Avoid saying I don't know.
`;

// Define a user prompt with a question
const userPrompt = "Describe Galileo";

(async () => {
    // Send a request to the LLM
    const response = await openai.chat.completions.create({
        model: "gpt-4o-mini",
        messages: [
            { role: "system", content: systemPrompt },
            { role: "user", content: userPrompt }
        ],
    });

    // Log the response
    console.log(response.choices[0].message.content);

    // Flush logs before exiting
    await flush({
        projectName: "MyFirstEvaluation",
        logStreamName: "MyFirstLogStream"
    });

    // Show Galileo information after the response
    const galileoLogger = getLogger();
    const galileoConsoleUrl = (process.env.GALILEO_CONSOLE_URL ??
                               "https://app.galileo.ai").replace(/\/+$/, "");
    const projectUrl = `${galileoConsoleUrl}/project/${galileoLogger.client.projectId}`;
    const logStreamUrl = `${projectUrl}/log-streams/${galileoLogger.client.logStreamId}`;

    console.log();
    console.log("🚀 GALILEO LOG INFORMATION:");
    console.log(`🔗 Project   : ${projectUrl}`);
    console.log(`📝 Log Stream: ${logStreamUrl}`);
})();
```

This will create a new project in Galileo called **MyFirstEvaluation**, with a Log stream called **MyFirstLogStream**. It will then log a trace using the call to the LLM.

> [!NOTE]
>
> This code defaults to using GPT-4o mini. If you want to use a different model, update the `model` in the call to `chat.completions.create`.

**4. Run your application**

Run your application using the following command in your terminal:

```bash Python theme={null}
python app.py
```

```bash TypeScript theme={null}
npx tsx app.ts
```

**5. View the results in your terminal**

You can see the model's output in your terminal:

```output Terminal wrap theme={null}
Galileo Galilei (1564-1642), an Italian polymath, is regarded as the "father of modern physics" and "modern observational astronomy." His work was central to the Scientific Revolution.

### Contributions:

1. **Astronomy:** Improved telescopes; discovered Jupiter’s moons (1610), phases of Venus, and observed celestial details supporting heliocentrism.
2. **Physics:** Demonstrated uniform acceleration, inertia, and falling-body principles; studied pendulums and harmonic motion.
3. **Mathematics:** Applied mathematics to physics, developing concepts of acceleration and projectile motion.
4. **Scientific Method:** Advocated observation and experimentation over abstract reasoning.
5. **Church Conflict:** His defense of heliocentrism led to trial (1633) and house arrest.
6. **Legacy:** Advanced physics, astronomy, and scientific inquiry; became a symbol of science versus authority.
```

The output describes Galileo Galilei, and is based on the training data used to train the LLM.

The output will also contain a link to your project and Log stream in Galileo.

```output Terminal wrap theme={null}
🚀 GALILEO LOG INFORMATION:
🔗 Project   : https://app.galileo.ai/project/...
📝 Log Stream: https://app.galileo.ai/project/.../log-streams/...
```

**6. See the trace in Galileo**

Open the Log stream for your project in the Galileo console using the URL output to your terminal. You will see the logged trace.

![The first trace in Galileo](https://mintcdn.com/v2galileo/04IoeOjygruoNb9a/snippets/content/get-started/quickstart/first-trace.webp?fit=max\&auto=format\&n=04IoeOjygruoNb9a\&q=85\&s=cafaa787f32578dd5bd889d5651b3d59)

Select the trace, then navigate to the **Messages** tab to see details of the trace.

![The first trace in Galileo](https://mintcdn.com/v2galileo/04IoeOjygruoNb9a/snippets/content/get-started/quickstart/first-trace-messages.webp?fit=max\&auto=format\&n=04IoeOjygruoNb9a\&q=85\&s=3f1c5be1b56857775e156331b745cc63)

**1. Install dependencies**

Install the **Galileo SDK** with OpenAI support, and the dotenv package using the following command in your terminal:

```bash Python theme={null}
pip install "galileo[openai]" python-dotenv
```

```bash TypeScript theme={null}
npm install galileo tsx dotenv
```

**2. Set up your environment variables**

Create an `.env` file in your project folder, and set:

* Your [Galileo API key](https://app.galileo.ai/settings/api-keys)
* Your Azure OpenAI Service API key
* Your Azure OpenAI Service endpoint

```ini .env theme={null}
GALILEO_API_KEY="your-galileo-api-key"
AZURE_OPENAI_API_KEY="your-azure-openai-api-key"
AZURE_OPENAI_ENDPOINT="your-azure-openai-api-key"
# Provide the console url below if you are not using app.galileo.ai
# GALILEO_CONSOLE_URL="your-galileo-console-url"
```

**3. Create your application code**

Create a file called `app.py` (Python) or `app.ts` (TypeScript) and add the following code:

```python Python theme={null}
from galileo import galileo_context
from galileo.openai import openai
from galileo.config import GalileoPythonConfig
from dotenv import load_dotenv

# Load environment variables from the .env file
load_dotenv()

# Set the project and Log stream, these are created if they don't exist.
# You can also set these using the GALILEO_PROJECT and GALILEO_LOG_STREAM
# environment variables.
galileo_context.init(project="MyFirstEvaluation",
                     log_stream="MyFirstLogStream")

# Initialize the Galileo Azure OpenAI client
client = openai.AzureOpenAI(api_version="2024-12-01-preview")

# Define a system prompt with guidance
system_prompt = f"""
You are a helpful assistant that wants to provide a user as much
information as possible. Avoid saying I don't know.
"""

# Define a user prompt with a question
user_prompt = "Describe Galileo"

# Send a request to the LLM
response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt}
    ],
)

# Print the response
print(response.choices[0].message.content.strip())

# Show Galileo information after the response
config = GalileoPythonConfig.get()
logger = galileo_context.get_logger_instance()
project_url = f"{config.console_url}project/{logger.project_id}"
log_stream_url = f"{project_url}/log-streams/{logger.log_stream_id}"

print()
print("🚀 GALILEO LOG INFORMATION:")
print(f"🔗 Project   : {project_url}")
print(f"📝 Log Stream: {log_stream_url}")
```

```typescript TypeScript theme={null}
import { AzureOpenAI } from "openai";
import { flush, getLogger, init, wrapOpenAI } from "galileo";
import dotenv from "dotenv";

// Load the environment variables
dotenv.config();

// Set the project and Log stream, these are created if they don't exist.
// You can also set these using the GALILEO_PROJECT and GALILEO_LOG_STREAM
// environment variables.
init({
    projectName: "MyFirstEvaluation",
    logStreamName: "MyFirstLogStream"
});

// Create an Azure OpenAI service wrapper
const openai = wrapOpenAI(new AzureOpenAI({ apiVersion: "2024-12-01-preview" }));

// Define a system prompt with guidance
const systemPrompt = `
You are a helpful assistant that wants to provide a user as much information
as possible. Avoid saying I don't know.
`;

// Define a user prompt with a question
const userPrompt = "Describe Galileo";

(async () => {
    // Send a request to the LLM
    const response = await openai.chat.completions.create({
        model: "gpt-4o-mini",
        messages: [
            { role: "system", content: systemPrompt },
            { role: "user", content: userPrompt }
        ],
    });

    // Log the response
    console.log(response.choices[0].message.content);

    // Flush logs before exiting
    await flush({
        projectName: "MyFirstEvaluation",
        logStreamName: "MyFirstLogStream"
    });

    // Show Galileo information after the response
    const galileoLogger = getLogger({
        projectName: "MyFirstEvaluation",
        logStreamName: "MyFirstLogStream"
    });
    const galileoConsoleUrl = (process.env.GALILEO_CONSOLE_URL ??
                               "https://app.galileo.ai").replace(/\/+$/, "");
    const projectUrl = `${galileoConsoleUrl}/project/${galileoLogger.client.projectId}`;
    const logStreamUrl = `${projectUrl}/log-streams/${galileoLogger.client.logStreamId}`;

    console.log();
    console.log("🚀 GALILEO LOG INFORMATION:");
    console.log(`🔗 Project   : ${projectUrl}`);
    console.log(`📝 Log Stream: ${logStreamUrl}`);
})();
```

This will create a new project in Galileo called **MyFirstEvaluation**, with a Log stream called **MyFirstLogStream**. It will then log a trace using the call to the LLM.

> [!NOTE]
>
> This code defaults to using GPT-4o mini. If you want to use a different model, update the `model` in the call to `chat.completions.create`.

**4. Run your application**

Run your application using the following command in your terminal:

```bash Python theme={null}
python app.py
```

```bash TypeScript theme={null}
npx tsx app.ts
```

**5. View the results in your terminal**

You can see the model's output in your terminal:

```output Terminal wrap theme={null}
Galileo Galilei (1564-1642), an Italian polymath, is regarded as the "father of modern physics" and "modern observational astronomy." His work was central to the Scientific Revolution.

### Contributions:

1. **Astronomy:** Improved telescopes; discovered Jupiter’s moons (1610), phases of Venus, and observed celestial details supporting heliocentrism.
2. **Physics:** Demonstrated uniform acceleration, inertia, and falling-body principles; studied pendulums and harmonic motion.
3. **Mathematics:** Applied mathematics to physics, developing concepts of acceleration and projectile motion.
4. **Scientific Method:** Advocated observation and experimentation over abstract reasoning.
5. **Church Conflict:** His defense of heliocentrism led to trial (1633) and house arrest.
6. **Legacy:** Advanced physics, astronomy, and scientific inquiry; became a symbol of science versus authority.
```

The output describes Galileo Galilei, and is based on the training data used to train the LLM.

The output will also contain a link to your project and Log stream in Galileo.

```output Terminal wrap theme={null}
🚀 GALILEO LOG INFORMATION:
🔗 Project   : https://app.galileo.ai/project/...
📝 Log Stream: https://app.galileo.ai/project/.../log-streams/...
```

**6. See the trace in Galileo**

Open the Log stream for your project in the Galileo console using the URL output to your terminal. You will see the logged trace.

![The first trace in Galileo](https://mintcdn.com/v2galileo/04IoeOjygruoNb9a/snippets/content/get-started/quickstart/first-trace.webp?fit=max\&auto=format\&n=04IoeOjygruoNb9a\&q=85\&s=cafaa787f32578dd5bd889d5651b3d59)

Select the trace, then navigate to the **Messages** tab to see details of the trace.

![The first trace in Galileo](https://mintcdn.com/v2galileo/04IoeOjygruoNb9a/snippets/content/get-started/quickstart/first-trace-messages.webp?fit=max\&auto=format\&n=04IoeOjygruoNb9a\&q=85\&s=3f1c5be1b56857775e156331b745cc63)

**1. Install dependencies**

Install the **Galileo SDK**, the Anthropic SDK, and the dotenv package using the following command in your terminal:

```bash Python theme={null}
pip install galileo python-dotenv anthropic
```

```bash TypeScript theme={null}
npm install galileo tsx dotenv @anthropic-ai/sdk
```

**2. Set up your environment variables**

Create an `.env` file in your project folder, and set:

* Your [Galileo API key](https://app.galileo.ai/settings/api-keys)
* Your [Anthropic API key](https://console.anthropic.com/settings/keys)

```ini .env theme={null}
GALILEO_API_KEY="your-galileo-api-key"
ANTHROPIC_API_KEY="your-anthropic-api-key"
# Provide the console url below if you are not using app.galileo.ai
# GALILEO_CONSOLE_URL="your-galileo-console-url"
```

**3. Create your application code**

Create a file called `app.py` (Python) or `app.ts` (TypeScript) and add the following code:

```python Python theme={null}
from datetime import datetime

from anthropic import Anthropic
from galileo import galileo_context
from galileo.config import GalileoPythonConfig
from dotenv import load_dotenv

# Load environment variables from the .env file
load_dotenv()

# Set the project and Log stream, these are created if they don't exist.
# You can also set these using the GALILEO_PROJECT and GALILEO_LOG_STREAM
# environment variables.
galileo_context.init(project="MyFirstEvaluation",
                     log_stream="MyFirstLogStream")

# Get the Galileo logger instance
logger = galileo_context.get_logger_instance()

# Start a Galileo session
logger.start_session()

# Initialize the Anthropic client
client = Anthropic()

# Define a system prompt with guidance
system_prompt = f"""
You are a helpful assistant that wants to provide a user as much
information as possible. Avoid saying I don't know.
"""

# Define a user prompt with a question
user_prompt = "Describe Galileo"

MODEL_NAME = "claude-sonnet-4-5"

# Start a trace
logger.start_trace(name="Conversation step", input=user_prompt)

# Define the messages to send
messages = [
    {"role": "user", "content": user_prompt}
]

# Capture the current time in nanoseconds for logging
start_time_ns = datetime.now().timestamp() * 1_000_000_000

# Send a request to the LLM
response = client.messages.create(
        max_tokens=1024,
        messages=messages,
        system=system_prompt,
        model=MODEL_NAME,
    )

# Log an LLM span using the response from Anthropic
logged_messages = [{"role": "system", "content": system_prompt}] + messages

logger.add_llm_span(
    input=logged_messages,
    output=response.content[0].text,
    model=MODEL_NAME,
    num_input_tokens=response.usage.input_tokens,
    num_output_tokens=response.usage.output_tokens,
    total_tokens=response.usage.input_tokens + response.usage.output_tokens,
    duration_ns=(datetime.now().timestamp() * 1_000_000_000) - start_time_ns,
)

# Conclude and flush the logger
logger.conclude(output=response.content[0].text)
logger.flush()

# Print the response
print(response.content[0].text)

# Show Galileo information after the response
config = GalileoPythonConfig.get()
project_url = f"{config.console_url}project/{logger.project_id}"
log_stream_url = f"{project_url}/log-streams/{logger.log_stream_id}"

print()
print("🚀 GALILEO LOG INFORMATION:")
print(f"🔗 Project   : {project_url}")
print(f"📝 Log Stream: {log_stream_url}")
```

```typescript TypeScript theme={null}
import Anthropic from '@anthropic-ai/sdk';
import { getLogger, init } from "galileo";
import dotenv from "dotenv";

// Load the environment variables
dotenv.config();

// Set the project and Log stream, these are created if they don't exist.
// You can also set these using the GALILEO_PROJECT and GALILEO_LOG_STREAM
// environment variables.
init({
    projectName: "MyFirstEvaluation",
    logStreamName: "MyFirstLogStream"
});

// Create an Anthropic client
const client = new Anthropic();

// Define a system prompt with guidance
const systemPrompt = `
You are a helpful assistant that wants to provide a user as much information
as possible. Avoid saying I don't know.
`;

// Define a user prompt with a question
const userPrompt = "Describe Galileo";

const modelName = "claude-sonnet-4-5";

// Get the Galileo logger instance
const galileoLogger = getLogger({
    projectName: "MyFirstEvaluation",
    logStreamName: "MyFirstLogStream"
});

(async () => {
    // Start a session
    await galileoLogger.startSession();

    // Start a trace
    galileoLogger.startTrace({ name: "Conversation step", input: userPrompt });

    // Define the messages to send
    const messages: Anthropic.Messages.MessageParam[] = [
        { "role": "user", "content": userPrompt }
    ];

    // Capture the current time in nanoseconds for logging
    function getNanoSecTime(): number {
        var hrTime = process.hrtime();
        return hrTime[0] * 1000000000 + hrTime[1];
    };

    const startTimeNs = getNanoSecTime();

    // Send a request to the LLM
    const response = await client.messages.create({
        max_tokens: 1024,
        messages: messages,
        system: systemPrompt,
        model: modelName,
    });

    // Log an LLM span using the response from Anthropic
    galileoLogger.addLlmSpan({
        input: [
            { role: "system", content: systemPrompt },
            { role: "user", content: userPrompt }
        ],
        output: (response.content[0] as Anthropic.TextBlock).text,
        model: modelName,
        numInputTokens: response.usage?.input_tokens,
        numOutputTokens: response.usage?.output_tokens,
        totalTokens: (response.usage?.input_tokens ?? 0) + 
                     (response.usage?.output_tokens ?? 0),
        durationNs: getNanoSecTime() - startTimeNs,
    });

    /// Conclude and flush the logger
    galileoLogger.conclude({
        output: (response.content[0] as Anthropic.TextBlock).text
    });
    await galileoLogger.flush();

    // Log the response
    console.log((response.content[0] as Anthropic.TextBlock).text);

    // Show Galileo information after the response
    const galileoConsoleUrl = (process.env.GALILEO_CONSOLE_URL ??
                               "https://app.galileo.ai").replace(/\/+$/, "");
    const projectUrl = `${galileoConsoleUrl}/project/${galileoLogger.client.projectId}`;
    const logStreamUrl = `${projectUrl}/log-streams/${galileoLogger.client.logStreamId}`;

    console.log();
    console.log("🚀 GALILEO LOG INFORMATION:");
    console.log(`🔗 Project   : ${projectUrl}`);
    console.log(`📝 Log Stream: ${logStreamUrl}`);
})();
```

This will create a new project in Galileo called **MyFirstEvaluation**, with a Log stream called **MyFirstLogStream**. It will then log a trace using the call to the LLM.

> [!NOTE]
>
> This code defaults to using Claude Sonnet 4.5. If you want to use a different model, update the `MODEL_NAME`.

**4. Run your application**

Run your application using the following command in your terminal:

```bash Python theme={null}
python app.py
```

```bash TypeScript theme={null}
npx tsx app.ts
```

**5. View the results in your terminal**

You can see the model's output in your terminal:

```output Terminal wrap theme={null}
Galileo Galilei (1564-1642), an Italian polymath, is regarded as the "father of modern physics" and "modern observational astronomy." His work was central to the Scientific Revolution.

### Contributions:

1. **Astronomy:** Improved telescopes; discovered Jupiter’s moons (1610), phases of Venus, and observed celestial details supporting heliocentrism.
2. **Physics:** Demonstrated uniform acceleration, inertia, and falling-body principles; studied pendulums and harmonic motion.
3. **Mathematics:** Applied mathematics to physics, developing concepts of acceleration and projectile motion.
4. **Scientific Method:** Advocated observation and experimentation over abstract reasoning.
5. **Church Conflict:** His defense of heliocentrism led to trial (1633) and house arrest.
6. **Legacy:** Advanced physics, astronomy, and scientific inquiry; became a symbol of science versus authority.
```

The output describes Galileo Galilei, and is based on the training data used to train the LLM.

The output will also contain a link to your project and Log stream in Galileo.

```output Terminal wrap theme={null}
🚀 GALILEO LOG INFORMATION:
🔗 Project   : https://app.galileo.ai/project/...
📝 Log Stream: https://app.galileo.ai/project/.../log-streams/...
```

**6. See the trace in Galileo**

Open the Log stream for your project in the Galileo console using the URL output to your terminal. You will see the logged trace.

![The first trace in Galileo](https://mintcdn.com/v2galileo/04IoeOjygruoNb9a/snippets/content/get-started/quickstart/first-trace.webp?fit=max\&auto=format\&n=04IoeOjygruoNb9a\&q=85\&s=cafaa787f32578dd5bd889d5651b3d59)

Select the trace, then navigate to the **Messages** tab to see details of the trace.

![The first trace in Galileo](https://mintcdn.com/v2galileo/04IoeOjygruoNb9a/snippets/content/get-started/quickstart/first-trace-messages.webp?fit=max\&auto=format\&n=04IoeOjygruoNb9a\&q=85\&s=3f1c5be1b56857775e156331b745cc63)

**1. Install dependencies**

Install the **Galileo SDK**, the Google GenAI SDK, and the dotenv package using the following command in your terminal:

```bash Python theme={null}
pip install galileo python-dotenv google-genai
```

```bash TypeScript theme={null}
npm install galileo tsx dotenv @google/genai
```

**2. Set up your environment variables**

Create an `.env` file in your project folder, and set:

* Your [Galileo API key](https://app.galileo.ai/settings/api-keys)
* Your [Gemini API key](https://aistudio.google.com/apikey)

```ini .env theme={null}
GALILEO_API_KEY="your-galileo-api-key"
GEMINI_API_KEY="your-gemini-api-key"
# Provide the console url below if you are not using app.galileo.ai
# GALILEO_CONSOLE_URL="your-galileo-console-url"
```

**3. Create your application code**

Create a file called `app.py` (Python) or `app.ts` (TypeScript) and add the following code:

```python Python theme={null}
from datetime import datetime

from google import genai
from google.genai import types

from galileo import galileo_context
from galileo.config import GalileoPythonConfig
from dotenv import load_dotenv

# Load environment variables from the .env file
load_dotenv(override=True)

# Set the project and Log stream, these are created if they don't exist.
# You can also set these using the GALILEO_PROJECT and GALILEO_LOG_STREAM
# environment variables.
galileo_context.init(project="MyFirstEvaluation",
                     log_stream="MyFirstLogStream")

# Get the Galileo logger instance
logger = galileo_context.get_logger_instance()

# Start a Galileo session
logger.start_session()

# Initialize the Gemini client
client = genai.Client()

# Define a system prompt with guidance
system_prompt = f"""
You are a helpful assistant that wants to provide a user as much
information as possible. Avoid saying I don't know.
"""

# Define a user prompt with a question
user_prompt = "Describe Galileo"

MODEL_NAME = "gemini-2.5-flash"

# Start a trace
logger.start_trace(name="Conversation step", input=user_prompt)

# Capture the current time in nanoseconds for logging
start_time_ns = datetime.now().timestamp() * 1_000_000_000

# Send a request to the LLM
response = client.models.generate_content(
    model=MODEL_NAME,
    config=types.GenerateContentConfig(
        system_instruction=system_prompt),
    contents=user_prompt
)

# Log an LLM span using the response from Gemini
logger.add_llm_span(
    input=[
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt}
    ],
    output=response.text,
    model=MODEL_NAME,
    num_input_tokens=response.usage_metadata.prompt_token_count,
    num_output_tokens=response.usage_metadata.candidates_token_count,
    total_tokens=response.usage_metadata.total_token_count,
    duration_ns=(datetime.now().timestamp() * 1_000_000_000) - start_time_ns,
)

# Conclude and flush the logger
logger.conclude(output=response.text)
logger.flush()

# Print the response
print(response.text)

# Show Galileo information after the response
config = GalileoPythonConfig.get()
project_url = f"{config.console_url}project/{logger.project_id}"
log_stream_url = f"{project_url}/log-streams/{logger.log_stream_id}"

print()
print("🚀 GALILEO LOG INFORMATION:")
print(f"🔗 Project   : {project_url}")
print(f"📝 Log Stream: {log_stream_url}")
```

```typescript TypeScript theme={null}
import { GoogleGenAI } from "@google/genai";
import { getLogger, init } from "galileo";
import dotenv from "dotenv";

// Load the environment variables
dotenv.config();

// Set the project and Log stream, these are created if they don't exist.
// You can also set these using the GALILEO_PROJECT and GALILEO_LOG_STREAM
// environment variables.
init({
    projectName: "MyFirstEvaluation",
    logStreamName: "MyFirstLogStream"
});

// Create a Gemini client
const client = new GoogleGenAI({});

// Define a system prompt with guidance
const systemPrompt = `
You are a helpful assistant that wants to provide a user as much information
as possible. Avoid saying I don't know.
`;

// Define a user prompt with a question
const userPrompt = "Describe Galileo";

const modelName = "gemini-2.5-flash";

// Get the Galileo logger instance
const galileoLogger = getLogger({
    projectName: "MyFirstEvaluation",
    logStreamName: "MyFirstLogStream"
});

(async () => {
    // Start a session
    await galileoLogger.startSession();

    // Start a trace
    galileoLogger.startTrace({ name: "Conversation step", input: userPrompt });

    // Capture the current time in nanoseconds for logging
    function getNanoSecTime(): number {
        var hrTime = process.hrtime();
        return hrTime[0] * 1000000000 + hrTime[1];
    };

    const startTimeNs = getNanoSecTime();

    // Send a request to the LLM
    const response = await client.models.generateContent({
        model: modelName,
        contents: userPrompt,
        config: {
            systemInstruction: systemPrompt,
        },
    });

    // Log an LLM span using the response from Gemini
    galileoLogger.addLlmSpan({
        input: [
            { role: "system", content: systemPrompt },
            { role: "user", content: userPrompt }
        ],
        output: response.text,
        model: modelName,
        numInputTokens: response.usageMetadata?.promptTokenCount ?? 0,
        numOutputTokens: response.usageMetadata?.candidatesTokenCount ?? 0,
        totalTokens: response.usageMetadata?.totalTokenCount ?? 0,
        durationNs: getNanoSecTime() - startTimeNs,
    });

    /// Conclude and flush the logger
    galileoLogger.conclude({ output: response.text });
    await galileoLogger.flush();

    // Log the response
    console.log(response.text);

    // Show Galileo information after the response
    const galileoConsoleUrl = (process.env.GALILEO_CONSOLE_URL ??
                               "https://app.galileo.ai").replace(/\/+$/, "");
    const projectUrl = `${galileoConsoleUrl}/project/${galileoLogger.client.projectId}`;
    const logStreamUrl = `${projectUrl}/log-streams/${galileoLogger.client.logStreamId}`;

    console.log();
    console.log("🚀 GALILEO LOG INFORMATION:");
    console.log(`🔗 Project   : ${projectUrl}`);
    console.log(`📝 Log Stream: ${logStreamUrl}`);
})();
```

This will create a new project in Galileo called **MyFirstEvaluation**, with a Log stream called **MyFirstLogStream**. It will then log a trace using the call to the LLM.

> [!NOTE]
>
> This code defaults to using Gemini 2.5 Flash. If you want to use a different model, update the `MODEL_NAME`.

**4. Run your application**

Run your application using the following command in your terminal:

```bash Python theme={null}
python app.py
```

```bash TypeScript theme={null}
npx tsx app.ts
```

**5. View the results in your terminal**

You can see the model's output in your terminal:

```output Terminal wrap theme={null}
Galileo Galilei (1564-1642), an Italian polymath, is regarded as the "father of modern physics" and "modern observational astronomy." His work was central to the Scientific Revolution.

### Contributions:

1. **Astronomy:** Improved telescopes; discovered Jupiter’s moons (1610), phases of Venus, and observed celestial details supporting heliocentrism.
2. **Physics:** Demonstrated uniform acceleration, inertia, and falling-body principles; studied pendulums and harmonic motion.
3. **Mathematics:** Applied mathematics to physics, developing concepts of acceleration and projectile motion.
4. **Scientific Method:** Advocated observation and experimentation over abstract reasoning.
5. **Church Conflict:** His defense of heliocentrism led to trial (1633) and house arrest.
6. **Legacy:** Advanced physics, astronomy, and scientific inquiry; became a symbol of science versus authority.
```

The output describes Galileo Galilei, and is based on the training data used to train the LLM.

The output will also contain a link to your project and Log stream in Galileo.

```output Terminal wrap theme={null}
🚀 GALILEO LOG INFORMATION:
🔗 Project   : https://app.galileo.ai/project/...
📝 Log Stream: https://app.galileo.ai/project/.../log-streams/...
```

**6. See the trace in Galileo**

Open the Log stream for your project in the Galileo console using the URL output to your terminal. You will see the logged trace.

![The first trace in Galileo](https://mintcdn.com/v2galileo/04IoeOjygruoNb9a/snippets/content/get-started/quickstart/first-trace.webp?fit=max\&auto=format\&n=04IoeOjygruoNb9a\&q=85\&s=cafaa787f32578dd5bd889d5651b3d59)

Select the trace, then navigate to the **Messages** tab to see details of the trace.

![The first trace in Galileo](https://mintcdn.com/v2galileo/04IoeOjygruoNb9a/snippets/content/get-started/quickstart/first-trace-messages.webp?fit=max\&auto=format\&n=04IoeOjygruoNb9a\&q=85\&s=3f1c5be1b56857775e156331b745cc63)

**1. Install dependencies**

Install the **Galileo SDK**, the AWS SDK, and the dotenv package using the following command in your terminal:

```bash Python theme={null}
pip install galileo python-dotenv boto3
```

```bash TypeScript theme={null}
npm install galileo dotenv tsx @aws-sdk/client-bedrock-runtime
```

**2. Set up your environment variables**

Create an `.env` file in your project folder, and set:

* Your [Galileo API key](https://app.galileo.ai/settings/api-keys)

```ini .env theme={null}
GALILEO_API_KEY="your-galileo-api-key"
# Provide the console url below if you are not using app.galileo.ai
# GALILEO_CONSOLE_URL="your-galileo-console-url"
```

**3. Set up AWS credentials**

Set up your AWS credentials to allow access to Bedrock. You can do this by [configuring the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html) or by setting the following environment variables:

```bash Terminal theme={null}
export AWS_ACCESS_KEY_ID=your-access-key-id
export AWS_SECRET_ACCESS_KEY=your-secret-access-key
export AWS_REGION=your-AWS_region
```

Alternatively, use an [Amazon Bedrock API key](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-generate.html).

```bash Terminal theme={null}
export AWS_BEARER_TOKEN_BEDROCK=your-api-key
```

**4. Create your application code**

Create a file called `app.py` (Python) or `app.ts` (TypeScript) and add the following code:

```python Python theme={null}
from datetime import datetime

import boto3
import json
from galileo import galileo_context
from galileo.config import GalileoPythonConfig
from dotenv import load_dotenv
import os

# Load environment variables from the .env file
load_dotenv()

# Set the project and Log stream, these are created if they don't exist.
# You can also set these using the GALILEO_PROJECT and GALILEO_LOG_STREAM
# environment variables.
galileo_context.init(project="MyFirstEvaluation",
                     log_stream="MyFirstLogStream")

# Get the Galileo logger instance
logger = galileo_context.get_logger_instance()

# Start a Galileo session
logger.start_session()

# Initialize the Amazon Bedrock Runtime client.
brt = boto3.client(
    service_name='bedrock-runtime',
    region_name=os.environ.get('AWS_DEFAULT_REGION', 'us-east-1')
)

# Define a system prompt with guidance
system_prompt = """
You are a helpful assistant that wants to provide a user as much
information as possible. Avoid saying I don't know.
"""

# Define a user prompt with a question
user_prompt = "Describe Galileo"

MODEL_NAME = "us.anthropic.claude-sonnet-4-5-20250929-v1:0"

# Start a trace
logger.start_trace(name="Conversation step", input=user_prompt)

# Capture the current time in nanoseconds for logging
start_time_ns = datetime.now().timestamp() * 1_000_000_000

# Format the request for AWS Bedrock
# following the Anthropic Claude API structure.
native_request = {
    "anthropic_version": "bedrock-2023-05-31",
    "max_tokens": 512,
    "temperature": 0.7,
    "system": system_prompt.strip(),
    "messages": [
        {
            "role": "user",
            "content": user_prompt
        }
    ]
}

# Convert the native request to JSON.
request = json.dumps(native_request)

# Send a request to the LLM with AWS Bedrock
try:
    # Invoke the model with the request.
    response = brt.invoke_model(modelId=MODEL_NAME, body=request)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{MODEL_NAME}'. Reason: {e}")
    exit(1)

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract the response text from Claude's format
response_text = model_response["content"][0]["text"]

# Log an LLM span using the response from Claude
logged_messages = [
    {"role": "system", "content": system_prompt}, 
    {"role": "user", "content": user_prompt}
]

logger.add_llm_span(
    input=logged_messages,
    output=response_text,
    model=MODEL_NAME,
    num_input_tokens=model_response["usage"]["input_tokens"],
    num_output_tokens=model_response["usage"]["output_tokens"],
    total_tokens=model_response["usage"]["input_tokens"] + model_response["usage"]["output_tokens"],
    duration_ns=(datetime.now().timestamp() * 1_000_000_000) - start_time_ns,
)

# Conclude and flush the logger
logger.conclude(output=response_text)
logger.flush()

# Print the response
print(f"\n🤖 Response:\n{response_text}\n")

# Show Galileo information after the response
config = GalileoPythonConfig.get()
project_url = f"{config.console_url}project/{logger.project_id}"
log_stream_url = f"{project_url}/log-streams/{logger.log_stream_id}"

print()
print("🚀 GALILEO LOG INFORMATION:")
print(f"🔗 Project   : {project_url}")
print(f"📝 Log Stream: {log_stream_url}")
```

```typescript TypeScript theme={null}
import Anthropic from '@anthropic-ai/sdk';
import { getLogger, init } from "galileo";
import dotenv from "dotenv";

// Load the environment variables
dotenv.config();

// Set the project and Log stream, these are created if they don't exist.
// You can also set these using the GALILEO_PROJECT and GALILEO_LOG_STREAM
// environment variables.
init({
    projectName: "MyFirstEvaluation",
    logStreamName: "MyFirstLogStream"
});

// Create an Anthropic client
const client = new Anthropic();

// Define a system prompt with guidance
const systemPrompt = `
You are a helpful assistant that wants to provide a user as much information
as possible. Avoid saying I don't know.
`;

// Define a user prompt with a question
const userPrompt = "Describe Galileo";

const modelName = "claude-sonnet-4-5";

// Get the Galileo logger instance
const galileoLogger = getLogger({
    projectName: "MyFirstEvaluation",
    logStreamName: "MyFirstLogStream"
});

(async () => {
    // Start a session
    await galileoLogger.startSession();

    // Start a trace
    galileoLogger.startTrace({ name: "Conversation step", input: userPrompt });

    // Define the messages to send
    const messages: Anthropic.Messages.MessageParam[] = [
        { "role": "user", "content": userPrompt }
    ];

    // Capture the current time in nanoseconds for logging
    function getNanoSecTime(): number {
        var hrTime = process.hrtime();
        return hrTime[0] * 1000000000 + hrTime[1];
    };

    const startTimeNs = getNanoSecTime();

    // Send a request to the LLM
    const response = await client.messages.create({
        max_tokens: 1024,
        messages: messages,
        system: systemPrompt,
        model: modelName,
    });

    // Log an LLM span using the response from Anthropic
    galileoLogger.addLlmSpan({
        input: [
            { role: "system", content: systemPrompt },
            { role: "user", content: userPrompt }
        ],
        output: (response.content[0] as Anthropic.TextBlock).text,
        model: modelName,
        numInputTokens: response.usage?.input_tokens,
        numOutputTokens: response.usage?.output_tokens,
        totalTokens: (response.usage?.input_tokens ?? 0) + 
                     (response.usage?.output_tokens ?? 0),
        durationNs: getNanoSecTime() - startTimeNs,
    });

    /// Conclude and flush the logger
    galileoLogger.conclude({
        output: (response.content[0] as Anthropic.TextBlock).text
    });
    await galileoLogger.flush();

    // Log the response
    console.log((response.content[0] as Anthropic.TextBlock).text);

    // Show Galileo information after the response
    const galileoConsoleUrl = (process.env.GALILEO_CONSOLE_URL ??
                               "https://app.galileo.ai").replace(/\/+$/, "");
    const projectUrl = `${galileoConsoleUrl}/project/${galileoLogger.client.projectId}`;
    const logStreamUrl = `${projectUrl}/log-streams/${galileoLogger.client.logStreamId}`;

    console.log();
    console.log("🚀 GALILEO LOG INFORMATION:");
    console.log(`🔗 Project   : ${projectUrl}`);
    console.log(`📝 Log Stream: ${logStreamUrl}`);
})();
```

This will create a new project in Galileo called **MyFirstEvaluation**, with a Log stream called **MyFirstLogStream**. It will then log a trace using the call to the LLM.

> [!NOTE]
>
> This code defaults to using Claude Sonnet 4.5. If you want to use a different model, update the `MODEL_NAME`. Reference the [supported foundation models for Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html).

**5. Run your application**

Run your application using the following command in your terminal:

```bash Python theme={null}
python app.py
```

```bash TypeScript theme={null}
npx tsx app.ts
```

**6. View the results in your terminal**

You can see the model's output in your terminal:

```output Terminal wrap theme={null}
Galileo Galilei (1564-1642), an Italian polymath, is regarded as the "father of modern physics" and "modern observational astronomy." His work was central to the Scientific Revolution.

### Contributions:

1. **Astronomy:** Improved telescopes; discovered Jupiter’s moons (1610), phases of Venus, and observed celestial details supporting heliocentrism.
2. **Physics:** Demonstrated uniform acceleration, inertia, and falling-body principles; studied pendulums and harmonic motion.
3. **Mathematics:** Applied mathematics to physics, developing concepts of acceleration and projectile motion.
4. **Scientific Method:** Advocated observation and experimentation over abstract reasoning.
5. **Church Conflict:** His defense of heliocentrism led to trial (1633) and house arrest.
6. **Legacy:** Advanced physics, astronomy, and scientific inquiry; became a symbol of science versus authority.
```

The output describes Galileo Galilei, and is based on the training data used to train the LLM.

The output will also contain a link to your project and Log stream in Galileo.

```output Terminal wrap theme={null}
🚀 GALILEO LOG INFORMATION:
🔗 Project   : https://app.galileo.ai/project/...
📝 Log Stream: https://app.galileo.ai/project/.../log-streams/...
```

**7. See the trace in Galileo**

Open the Log stream for your project in the Galileo console using the URL output to your terminal. You will see the logged trace.

![The first trace in Galileo](https://mintcdn.com/v2galileo/04IoeOjygruoNb9a/snippets/content/get-started/quickstart/first-trace.webp?fit=max\&auto=format\&n=04IoeOjygruoNb9a\&q=85\&s=cafaa787f32578dd5bd889d5651b3d59)

Select the trace, then navigate to the **Messages** tab to see details of the trace.

![The first trace in Galileo](https://mintcdn.com/v2galileo/04IoeOjygruoNb9a/snippets/content/get-started/quickstart/first-trace-messages.webp?fit=max\&auto=format\&n=04IoeOjygruoNb9a\&q=85\&s=3f1c5be1b56857775e156331b745cc63)

🎉 **Congratulations**, you have logged your first trace! Your [next step is to evaluate this trace using Galileo metrics](https://docs.galileo.ai/getting-started/evaluate-and-improve/evaluate-and-improve.md), and use this evaluation to improve the LLM prompts to get a better response.

## Troubleshooting

* **I need a Galileo API key**: Head to [app.galileo.ai](https://app.galileo.ai) and sign up. Then head to the [API keys](https://app.galileo.ai/settings/api-keys) page to get a new API key.
* **What's my project name and Log stream name?**: The project and Log stream names were set when you created a new project. If you haven't created a new project, head to Galileo and select the **New Project** button.

## Next steps

> [card] [Evaluate your first trace](https://docs.galileo.ai/getting-started/evaluate-and-improve/evaluate-and-improve.md)
>
> Learn how to evaluating metrics for your trace with Galileo, and improve your application.

> [card] [Sample projects](https://docs.galileo.ai/getting-started/sample-projects/sample-projects.md)
>
> Learn how to get started with the Galileo sample projects that are included in every new account.

> [card] [Integrate with third-party frameworks](https://docs.galileo.ai/sdk-api/third-party-integrations/overview.md)
>
> Learn about the Galileo integrations with third-party SDKs to automatically log your applications

### Cookbooks

> [card] [Cookbooks](https://docs.galileo.ai/cookbooks/overview.md)
>
> Learn how to perform common tasks with Galileo, work with third-party integrations, and use evaluations to solve AI problems

### SDK reference

> [card] [Python SDK Reference](https://docs.galileo.ai/sdk-api/python/sdk-reference.md)
>
> The Galileo Python SDK reference.

> [card] [TypeScript SDK Reference](https://docs.galileo.ai/sdk-api/typescript/sdk-reference.md)
>
> The Galileo TypeScript SDK reference.
