Skip to content
OpenAI logo

GPT-4o mini

Text GenerationOpenAI

GPT-4o Mini is the lightweight, low-cost variant of GPT-4o, well suited to high-volume tasks with multimodal inputs.

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-mini',
{ 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 physical systems. Here’s a brief overview of each:

1. **Zeroth Law of Thermodynamics**: Though it was formulated after the first three laws, it's often referred to as the "zeroth" law. It states that if two systems are each in thermal equilibrium with a third system, then they are in thermal equilibrium with each other. This law forms the basis for the concept of temperature.

2. **First Law of Thermodynamics (Law of Energy Conservation)**: This law states that energy cannot be created or destroyed, only transformed from one form to another. In a closed system, the change in internal energy is equal to the heat added to the system minus the work done by the system. Mathematically, it's often expressed as:
   \[
   \Delta U = Q - W
   \]
   where \( \Delta U \) is the change in internal energy, \( Q \) is the heat added to the system, and \( W \) is the work done by the system.

3. **Second Law of Thermodynamics**: This law introduces the concept of entropy, stating that the total entropy of an isolated system can never decrease over time. It also implies that processes occur in a direction that increases the overall entropy of the universe. This law explains why some energy transformations are not 100% efficient and why heat flows spontaneously from hot to cold bodies.

4. **Third Law of Thermodynamics**: This law states that as the temperature of a system approaches absolute zero, the entropy of a perfect crystal approaches zero. It helps define the absolute temperature scale and indicates that it is impossible to reach absolute zero in a finite number of steps.

These laws are foundational to the study of physics and chemistry, affecting various fields, including engineering, biology, and materials science.

Examples

With System Message — Using a system message to set context
TypeScript
const response = await env.AI.run(
'openai/gpt-4o-mini',
{
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 can use the built-in `json` module, which provides methods for parsing JSON data. Here’s a step-by-step guide on how to do this:

1. **Import the `json` module**: This module allows you to work with JSON data easily.
2. **Open the JSON file**: Use Python's built-in `open()` function to access the file.
3. **Load the JSON data**: Use the `json.load()` function to parse the JSON data in the file.

Here is a simple example:

### Example: Reading a JSON file

Assuming you have a JSON file named `data.json` with the following content:

```json
{
    "name": "John",
    "age": 30,
    "city": "New York"
}
```

Here is how you can read this JSON file in Python:

```python
import json

# Open the JSON file for reading
with open('data.json', 'r') as file:
    # Load the JSON data from the file
    data = json.load(file)

# Now you can access the data
print(data)  # This will print the contents of the JSON file as a dictionary
print(data['name'])  # Outputs: John
print(data['age'])   # Outputs: 30
print(data['city'])  # Outputs: New York
```

### Explanation:
- The `with open('data.json', 'r') as file:` statement opens the file in read mode and ensures it will be properly closed after its suite finishes, even if an error is raised.
- The `json.load(file)` function reads the JSON data and converts it into a Python dictionary.
- You can then access the data using the dictionary syntax.

### Additional Notes:
- If you have a JSON string instead of a file, you can use `json.loads()` instead.
- Handle exceptions using `try-except` blocks if you want to manage errors, such as when a file does not exist or contains invalid JSON.

This method is simple and efficient for reading JSON data in Python.
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'openai/gpt-4o-mini',
{
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)
Here are some great stops you can consider on your road trip from San Francisco to Los Angeles, highlighting both scenic spots and interesting attractions:

### 1. **Half Moon Bay**
   - **Distance from San Francisco:** ~30 minutes
   - **Highlights:** Beautiful beaches, coastal cliffs, and the charming downtown area. Consider stopping at a beach or enjoying a meal at one of the waterfront restaurants.

### 2. **Santa Cruz**
   - **Distance from San Francisco:** ~1.5 hours
   - **Highlights:** Visit the Santa Cruz Beach Boardwalk, explore the redwood forests in Henry Cowell Redwoods State Park, or take a stroll along the coastline.

### 3. **Monterey**
   - **Distance from Santa Cruz:** ~45 minutes
   - **Highlights:** Monterey Bay Aquarium, Cannery Row, and beautiful coastal views. A must-see is the 17-Mile Drive through Pebble Beach.

### 4. **Carmel-by-the-Sea**
   - **Distance from Monterey:** ~15 minutes
   - **Highlights:** A picturesque town known for its art galleries, boutique shops, and stunning beach. Don't miss the chance to explore Carmel Mission Basilica.

### 5. **Big Sur**
   - **Distance from Carmel:** ~30 minutes
   - **Highlights:** Drive along the rugged coastline on Highway 1, stopping at famous viewpoints like Bixby Creek Bridge, McWay Falls, and Pfeiffer Beach. This stretch is a highlight of the trip.

### 6. **San Luis Obispo**
   - **Distance from Big Sur:** ~2 hours
   - **Highlights:** A quaint town with a vibrant downtown area, Mission San Luis Obispo de Tolosa, and the famous Bubblegum Alley. If you have time, check out nearby Hearst Castle in San Simeon.

### 7. **Pismo Beach**
   - **Distance from San Luis Obispo:** ~15 minutes
   - **Highlights:** A classic Californian beach town. Enjoy the pier, beautiful beaches, and local restaurants. If you're a fan of clam chowder, it's a great place to stop for some.

### 8. **Santa Barbara**
   - **Distance from Pismo Beach:** ~1 hour
   - **Highlights:** Gorgeous Mediterranean-style architecture, beautiful beaches, and wine country nearby. Visit State Street, the Santa Barbara Mission, and the Santa Barbara Botanic Garden.

### 9. **Malibu**
   - **Distance from Santa Barbara:** ~1.5 hours
   - **Highlights:** Scenic coastal views, beautiful beaches like Zuma Beach, and the Malibu Pier. If time allows, stop at the Getty Villa for art and architecture.

### 10. **Los Angeles**
   - **Distance from Malibu:** ~30 minutes
   - **Final Destination:** Depending on your interests, explore Hollywood, Santa Monica, or any of the numerous attractions the city has to offer.

### Tips:
- **Timing:** Start your trip early to maximize your time at each stop.
- **Scenic Routes:** The Pacific Coast Highway (Highway 1) is the most scenic route, but parts may be subject to closure due to weather or landslides, so check ahead.
- **Food:** There are many great eateries along the coast; don’t hesitate to stop for local seafood and cafés.
- **Overnight Stay:** If you want to break it into two days, consider staying in Monterey or Santa Barbara for a more relaxed pace.

Hope this helps you plan an amazing road trip! Let me know if you need more information or specific recommendations.
Creative Writing — Longer completion for creative output
TypeScript
const response = await env.AI.run(
'openai/gpt-4o-mini',
{
max_completion_tokens: 8192,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
},
)
console.log(response)
Detective Iris Kline stood in the dimly lit study of the late Vincent Hawthorne, an eccentric author known for his best-selling thrillers and reclusive nature. The smell of old books and the faint hint of cigar smoke lingered in the air, wrapping around her like a shroud as she scanned the cluttered room for anything that might shed light on the enigmatic man's death. The police had ruled it a heart attack, but Iris wasn’t convinced. A writer whose life revolved around crafting intricate plots wouldn't simply drop dead without a shred of foreshadowing.

She crouched beside a mahogany desk strewn with yellowed manuscripts and coffee-stained pages, her fingers brushing against the surface. That’s when she spotted it—a glint of silver poking out from beneath a loose floorboard. Curious, she pried it open, her nails scraping against the wood until she could retrieve the object: a small, intricately designed key. 

Flipping it over in her palm, she noticed a curious engraving on its barrel—a compass rose, with eight tiny arrows radiating from the center. It was both beautiful and unsettling, like something straight out of one of Hawthorne's novels. But it was the cryptic inscription beneath it that gave her pause, a single word: “NAVIGATOR.” 

Iris felt the weight of the key shift in her hand, a sense of urgency rising within her. Whatever this key unlocked, it was clear it held secrets far beyond the reclusive author’s final chapter. She slid the key into her pocket, the quiet thrill of an unraveling mystery beginning to take root in her mind. What could Vincent Hawthorne have been hiding? And where would this unusual clue lead her next?
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'openai/gpt-4o-mini',
{
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 typically involves a base case that stops the recursion and a recursive case that breaks the problem down into smaller subproblems.

### Example: Factorial

A classic example of recursion is calculating the factorial of a number, denoted as `n!`. The factorial of a non-negative integer `n` is the product of all positive integers less than or equal to `n`. The recursive definition is:

- **Base Case**: `0! = 1` (the factorial of 0 is 1)
- **Recursive Case**: `n! = n * (n - 1)!` for `n > 0`

Here’s a simple implementation of this concept in Python:

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

# Example usage
result = factorial(5)  # This will compute 5 * 4 * 3 * 2 * 1
print(result)  # Output: 120
```

### Explanation:

1. **When `factorial(5)` is called**:
   - It checks if `n` is 0 (which it isn't).
   - It computes `5 * factorial(4)`.

2. **Next, `factorial(4)` is called**:
   - Again, it checks if `n` is 0 (which it isn't).
   - It computes `4 * factorial(3)`.

3. This process continues until `factorial(0)` is reached, which hits the base case and returns 1.

4. The function then unwinds:
   - `factorial(1)` returns `1 * 1 = 1`
   - `factorial(2)` returns `2 * 1 = 2`
   - `factorial(3)` returns `3 * 2 = 6`
   - `factorial(4)` returns `4 * 6 = 24`
   - `factorial(5)` returns `5 * 24 = 120`

Thus, the factorial of 5 is computed to be 120, demonstrating how recursion can break down a complex problem into simpler subproblems.

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