Skip to content
OpenAI logo

GPT-4.1 mini

Text GenerationOpenAI

Fast, affordable version of GPT-4.1 with a million-token context window.

Model Info
Context Window1,047,576 tokens
Terms and Licenselink
More informationlink
Zero data retentionYes
Request formatsResponses, Chat Completions
PricingView pricing in the Cloudflare dashboard

Usage

TypeScript
const response = await env.AI.run(
'openai/gpt-4.1-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 how energy behaves in physical systems:

1. **First Law of Thermodynamics (Law of Energy Conservation):**  
   Energy cannot be created or destroyed; it can only be transferred or transformed from one form to another. In other words, the total energy of an isolated system remains constant. 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. **Second Law of Thermodynamics:**  
   The total entropy of an isolated system can never decrease over time; it either increases or remains constant in ideal cases. Entropy is a measure of disorder or randomness. This law implies that natural processes tend to move toward a state of greater disorder, and it explains the direction of heat transfer (from hot to cold).  

3. **Third Law of Thermodynamics:**  
   As the temperature of a system approaches absolute zero (0 Kelvin), the entropy of a perfect crystal approaches a constant minimum, which can be taken as zero. This means it is impossible to reach absolute zero temperature through any finite series of processes.

If you need, I can also explain the Zeroth Law, which is foundational and often included when discussing thermodynamics.

Examples

With System Message — Using a system message to set context
TypeScript
const response = await env.AI.run(
'openai/gpt-4.1-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. Here's a simple example:

```python
import json

# Open the JSON file
with open('data.json', 'r') as file:
    # Load the content of the file into a Python dictionary
    data = json.load(file)

# Now you can use `data` like a regular Python dictionary
print(data)
```

### Explanation:
- `open('data.json', 'r')` opens the file in read mode.
- `json.load(file)` reads the JSON content from the file and converts it into a Python dictionary (or list, depending on the JSON structure).

Make sure your JSON file is properly formatted. If you want to handle errors, you can add a try-except block as well.

Let me know if you need help with that!
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'openai/gpt-4.1-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)
Great! Here are some popular and scenic stops along the drive from San Francisco to Los Angeles:

1. **Half Moon Bay** – Just south of San Francisco, it’s a charming coastal town with beautiful beaches and great spots for breakfast or coffee.
2. **Santa Cruz** – Known for its classic boardwalk, beach vibes, and surfing culture.
3. **Monterey** – Famous for the Monterey Bay Aquarium, Cannery Row, and stunning coastal views.
4. **Carmel-by-the-Sea** – A picturesque town with art galleries, boutique shops, and beautiful beaches.
5. **Big Sur** – One of the most scenic stretches of the California coast with dramatic cliffs, waterfalls (like McWay Falls), and state parks.
6. **San Simeon** – Home to Hearst Castle, a historic mansion worth touring.
7. **Pismo Beach** – Great for a beach break, known for its dunes and laid-back atmosphere.
8. **Santa Barbara** – Often called the “American Riviera” for its Mediterranean climate, with beaches, shopping, and wine tasting.

Would you like recommendations for dining, accommodations, or activities at any of these stops?
Creative Writing — Longer completion for creative output
TypeScript
const response = await env.AI.run(
'openai/gpt-4.1-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 Elena Marsh crouched beside the shattered window, the cold wind tugging at her coat. Amid the splintered glass and upturned furniture, something caught her eye—a single, iridescent feather resting delicately on the floor. It shimmered with colors she couldn’t place, almost otherworldly. She reached down, careful not to disturb the scene further, and traced the feather’s fragile quill between her fingers. This wasn’t just a clue. It was a message. And Elena had a feeling it was about to rewrite everything she thought she knew about the case.
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'openai/gpt-4.1-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. A recursive function typically has two main parts:

1. **Base Case:** The condition under which the function stops calling itself. This prevents infinite recursion.
2. **Recursive Case:** The part where the function calls itself with a smaller or simpler input, gradually approaching the base case.

### Simple Example: Factorial of a Number

The factorial of a number \( n \) (written as \( n! \)) is the product of all positive integers less than or equal to \( n \). It can be defined recursively as:

- \( 0! = 1 \) (Base case)
- \( n! = n \times (n-1)! \) (Recursive case)

Here's how you can implement factorial recursively in Python:

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

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

### Explanation:

- When `factorial(5)` is called, it returns \( 5 \times factorial(4) \).
- `factorial(4)` returns \( 4 \times factorial(3) \), and so on.
- Eventually, `factorial(0)` returns 1, stopping the recursion.
- The results are then combined back up to give the final answer.

This shows how recursion breaks down a problem into smaller identical problems until reaching the simplest one.
Web Search — Letting the model use OpenAI's built-in web search tool to answer with current information
TypeScript
const response = await env.AI.run(
'openai/gpt-4.1-mini',
{
input: 'What were the top news stories about Cloudflare this week? Summarise in three bullets.',
max_output_tokens: 4096,
tools: [{ type: 'web_search_preview' }],
},
)
console.log(response)
Here are the top news stories about Cloudflare from June 15 to June 22, 2026:

- **Cloudflare Launches Partner Program for SASE and AI Security Deployment**: On June 17, 2026, Cloudflare introduced the Cloudflare One Design Partner Designation, a channel program providing select global partners with technical resources and financial support to deploy its Secure Access Service Edge (SASE) platform. The initial partners include Arctiq, Consortium, CMT, Presidio, and The Missing Link. Additionally, Cloudflare unveiled the Cloudflare One Stack, a library of AI tools designed to assist security teams in evaluating, deploying, and managing the Cloudflare One platform. ([streetinsider.com](https://www.streetinsider.com/Corporate%2BNews/Cloudflare%2Blaunches%2Bpartner%2Bprogram%2Bfor%2BSASE%2Band%2BAI%2Bsecurity%2Bdeployment/26657730.html?utm_source=openai))

- **Cloudflare Expands AI Security with Ping Identity Partnership at the Edge**: On June 17, 2026, Cloudflare announced a partnership with Ping Identity to enhance AI security by extending enterprise-scale identity enforcement to the edge. This collaboration focuses on real-time authorization, monitoring, and policy enforcement for AI agents running on Cloudflare’s global network, expanding Zero Trust controls to AI-powered edge workloads outside traditional cloud environments. ([simplywall.st](https://simplywall.st/stocks/us/software/nyse-net/cloudflare/news/cloudflare-net-expands-ai-security-with-ping-identity-partne?utm_source=openai))

- **Cloudflare Network Disruption Triggers Widespread Internet Outages**: On June 22, 2026, a significant global network disruption at Cloudflare caused widespread outages for millions of internet users, affecting major platforms like X, Reddit, and Zoom. The incident began around 10 a.m. EST, with users reporting persistent API authorization errors and dashboard issues. Cloudflare identified the technical issue and implemented a fix across the network. ([harianbasis.co](https://www.harianbasis.co/en/cloudflare-network-disruption-internet-outage?utm_source=openai)) 

Parameters

Schema variant
instructions
string
temperature
numberminimum: 0maximum: 2
max_output_tokens
numberexclusiveMinimum: 0
top_p
numberminimum: 0maximum: 1
stream
boolean
tool_choice

API Schemas (Raw)

Input
Output