Skip to content
OpenAI logo

GPT-4o

Text GenerationOpenAI

GPT-4o is OpenAI’s multimodal flagship, accepting text and images and responding quickly across a wide range of tasks.

Model Info
Context Window128,000 tokens
Terms and Licenselink
More informationlink
Zero data retentionYes
PricingView pricing in the Cloudflare dashboard

Usage

TypeScript
const response = await env.AI.run(
'openai/gpt-4o',
{ messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
The three laws of thermodynamics are fundamental principles that describe the behavior of energy and matter in a system. They are:

1. **The First Law of Thermodynamics (Law of Energy Conservation):**
   This law states that energy cannot be created or destroyed in an isolated system. The total energy of a system and its surroundings is conserved. It can only change forms (e.g., from kinetic energy to potential energy, or from mechanical energy to thermal energy). Mathematically, it is often expressed as:
   \[
   \Delta U = Q - W
   \]
   where \(\Delta U\) is the change in internal energy of the system, \(Q\) is the heat added to the system, and \(W\) is the work done by the system.

2. **The Second Law of Thermodynamics:**
   This law states that the total entropy of a closed system can never decrease over time. It also posits that energy, while conserved, tends to disperse or spread out, leading to an increase in disorder or entropy. In more practical terms, it implies that heat cannot spontaneously flow from a colder body to a hotter one and that all natural processes are irreversible. It establishes the concept of entropy as a measure of the energy dispersal within a system.

3. **The Third Law of Thermodynamics:**
   According to this law, as the temperature of a system approaches absolute zero, the entropy of the system approaches a minimum value, often considered to be zero for a perfect crystalline structure. This means that it becomes increasingly difficult to remove more energy from a system as it nears absolute zero, and practically, reaching absolute zero is impossible.

These three laws describe the fundamental behavior of energy transformations and form the groundwork for understanding thermodynamic processes.

Examples

With System Message — Using a system message to set context
TypeScript
const response = await env.AI.run(
'openai/gpt-4o',
{
messages: [
{ content: 'You are a helpful coding assistant specializing in Python.', role: 'system' },
{ content: 'How do I read a JSON file in Python?', role: 'user' },
],
},
)
console.log(response)
To read a JSON file in Python, you typically use the built-in `json` module, which provides utilities for parsing JSON formatted data. Here’s a step-by-step guide on how to do it:

1. **Import the `json` module**: To work with JSON data, you need to import this module.

2. **Open the JSON file**: Use the built-in `open()` function to open the file in read mode.

3. **Parse the JSON data**: Use `json.load()` to parse the JSON data from the file into a Python data structure (usually a dictionary or a list).

Here is a simple example demonstrating these steps:

```python
import json

# Specify the path to your JSON file
file_path = 'data.json'

# Open the file and load the JSON data
with open(file_path, 'r') as file:
    data = json.load(file)

# Now `data` is a Python dictionary (or list, depending on the structure of your JSON file)
print(data)
```

### Key Points:

- **Error Handling**: You might want to add exception handling to handle potential errors, such as the file not being found or the JSON data being malformed. You can do this using a `try-except` block.
  
  ```python
  import json

  file_path = 'data.json'

  try:
      with open(file_path, 'r') as file:
          data = json.load(file)
  except FileNotFoundError:
      print(f"Error: The file {file_path} does not exist.")
  except json.JSONDecodeError:
      print("Error: The file contains invalid JSON.")
  else:
      print(data)
  ```

- **File Modes**: Ensure the file is opened in read mode (`'r'`). If the JSON data is coming from a different source (like an API), you would use `json.loads()` to parse a JSON string instead.

Using this method, you can easily read and work with JSON data in your Python projects.
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'openai/gpt-4o',
{
max_completion_tokens: 8192,
messages: [
{
content: 'I need help planning a road trip from San Francisco to Los Angeles.',
role: 'user',
},
{
content:
"I'd be happy to help! The drive is about 380 miles and takes roughly 5-6 hours. Would you like suggestions for scenic routes or interesting stops along the way?",
role: 'assistant',
},
{ content: 'Yes, what are some good places to stop?', role: 'user' },
],
},
)
console.log(response)
A road trip from San Francisco to Los Angeles offers many scenic and interesting stops. Here are some popular ones:

1. **Half Moon Bay**: Just south of San Francisco, this coastal town is great for a quick visit to the beach and offers stunning ocean views.

2. **Santa Cruz**: Known for its boardwalk and beaches, Santa Cruz also has charming downtown shops and eateries.

3. **Monterey**: Visit the famous Monterey Bay Aquarium or take a scenic drive along the 17-Mile Drive through Pebble Beach.

4. **Carmel-by-the-Sea**: This picturesque town is perfect for a stroll through art galleries, shops, and beautiful beaches.

5. **Big Sur**: Enjoy dramatic coastal views on Highway 1. Stops include Bixby Creek Bridge, McWay Falls, and Pfeiffer Beach.

6. **San Luis Obispo**: Known for its charming downtown and the quirky Bubblegum Alley. You can also visit nearby Pismo Beach or Avila Beach.

7. **Solvang**: A small Danish-style town that offers unique architecture, bakeries, and shops.

8. **Santa Barbara**: Known as the "American Riviera," this city offers beautiful beaches, a bustling downtown, and the iconic Santa Barbara Mission.

9. **Malibu**: Stop by for some of the most famous beaches like Zuma Beach or enjoy oceanfront dining.

These stops offer a mix of natural beauty, quaint towns, and interesting attractions. Be sure to check road conditions and make accommodations as needed, especially if traveling along the Pacific Coast Highway (Highway 1). Safe travels!
Creative Writing — Longer completion for creative output
TypeScript
const response = await env.AI.run(
'openai/gpt-4o',
{
max_completion_tokens: 8192,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
},
)
console.log(response)
Detective Elara Finch pushed open the creaky iron gate of the weathered mansion, her eyes narrowing against the gray drizzle that blanketed the estate. The air was thick with the earthy scent of rain and old secrets. She stepped cautiously, her boots sinking slightly into the sodden earth, as she approached the scene where the latest in a string of bizarre disappearances had occurred.

The house loomed ahead, its once-grand façade now a tapestry of ivy and neglect. As Elara entered through the front door, the dim light from the overcast sky barely penetrated the dust-choked windows. Her gloved hand traced the outlines of dilapidated furniture covered in yellowed sheets, ghostly sentinels bearing witness to the passage of time.

Her gaze swept the parlor before settling on an oddly pristine object that gleamed incongruously amidst the decay—a small, intricately carved music box, perched neatly on the mantelpiece. She approached, her curiosity piqued by its anachronistic presence. Gently lifting the lid, she was met with the delicate chime of a haunting melody.

Inside the box lay a perfectly folded piece of parchment, its edges fraying but the ink remarkably intact. As she unfolded it, Elara's eyes widened at the drawing: a curious map, sketched with meticulous detail, leading to a location unfamiliar to her but marked with an ominous "X." What caught her attention most, however, was the signature beneath—a simple yet unmistakable mark that had haunted her career for years: a raven outlined in black.

This symbol had been left at every one of the enigmatic disappearances plaguing the city, and now, finally, a tangible connection lay before her. As the music continued to play, its eerie notes echoing in the hushed room, Elara realized that this peculiar clue—this thread from a carefully woven tapestry of puzzles—might just unravel the mystery that had eluded her for so long.
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'openai/gpt-4o',
{
messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
stream: true,
stream_options: { include_usage: true },
},
)
console.log(response)
Recursion is a programming concept where a function calls itself in order to solve a problem. It breaks down a problem into smaller, more manageable sub-problems, each of which resembles the original problem. This approach is especially useful in tasks that can naturally be divided into similar subtasks, like calculating factorials or traversing data structures like trees.

A simple example of recursion is the calculation of the factorial of a number. The factorial of a non-negative integer \( n \), denoted as \( n! \), is the product of all positive integers less than or equal to \( n \). The factorial of 0 is defined as 1.

Here's how you can define this problem recursively:

- Base case: If \( n \) is 0, return 1.
- Recursive case: If \( n \) is greater than 0, return \( n \times \text{factorial}(n-1) \).

Here's a simple implementation in Python:

```python
def factorial(n):
    if n == 0:  # Base case
        return 1
    else:
        return n * factorial(n - 1)  # Recursive case

# Example usage:
print(factorial(5))  # Output: 120
```

In this example:
- The base case stops the recursion when \( n \) is 0.
- The recursive case reduces the problem by calling the `factorial` function with \( n-1 \), gradually approaching the base case. 
- Each call of the function adds a new layer to the call stack, and returning the result of each call unwinds the stack, culminating in the final result.

Parameters

frequency_penalty
numbermaximum: 2minimum: -2
max_completion_tokens
numberexclusiveMinimum: 0
max_tokens
numberexclusiveMinimum: 0
presence_penalty
numbermaximum: 2minimum: -2
response_format
stream
boolean
temperature
numbermaximum: 2minimum: 0
tool_choice
top_p
numbermaximum: 1minimum: 0

API Schemas (Raw)

Input
Output