Skip to content
OpenAI logo

GPT-4.1 nano

Text GenerationOpenAI

GPT-4.1 Nano is OpenAI’s smallest and cheapest GPT-4.1 variant, optimized for high-throughput, low-latency tasks.

Model Info
Context Window1,000,000 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-nano',
{ 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 temperature in physical systems:

1. **First Law of Thermodynamics (Law of Energy Conservation):**  
   Energy cannot be created or destroyed in an isolated system. The total energy remains constant, implying that the change in the internal energy of a system is equal to the heat added to the system minus the work done by the system.  
   Mathematically:  
   \[
   \Delta U = Q - W
   \]

2. **Second Law of Thermodynamics:**  
   The entropy of an isolated system always tends to increase over time, and natural processes tend to move towards a state of maximum entropy. This law introduces the concept of irreversibility and asserts that heat cannot spontaneously flow from a colder to a hotter body without external work.

3. **Third Law of Thermodynamics:**  
   As the temperature of a perfect crystal approaches absolute zero (0 Kelvin), the entropy of the system approaches a constant minimum, often taken as zero. This implies that absolute zero temperature is unattainable in a finite number of steps.

These laws form the foundation of thermodynamics and are essential in understanding energy systems, engines, refrigerators, and many other physical phenomena.

Examples

With System Message — Using a system message to set context
TypeScript
const response = await env.AI.run(
'openai/gpt-4.1-nano',
{
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 functions for parsing JSON data. Here's a simple step-by-step example:

1. Import the `json` module.
2. Open the JSON file using `open()`.
3. Use `json.load()` to parse the data from the file into a Python data structure (usually a dictionary or list).

Here's an example:

```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 you can work with 'data' as a Python dictionary or list
print(data)
```

### Notes:
- Make sure the JSON file exists at the specified location.
- If the JSON data is in string format rather than a file, you can use `json.loads()` instead.
- Always handle potential exceptions (like `FileNotFoundError` or `json.JSONDecodeError`) when working with files and JSON data.

Would you like an example with error handling or working with JSON data in a string?
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'openai/gpt-4.1-nano',
{
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 interesting stops along the San Francisco to Los Angeles route, mainly along the iconic Highway 1 and scenic coastal areas:

1. **Santa Cruz**  
   - Enjoy the beaches, surf culture, and the famous Santa Cruz Beach Boardwalk amusement park.

2. **Monterey & Carmel-by-the-Sea**  
   - Monterey: Visit the Monterey Bay Aquarium and Cannery Row.  
   - Carmel: Stroll through charming streets, galleries, and enjoy the stunning coastal views.

3. **Big Sur**  
   - One of the most breathtaking parts of California's coast.  
   - Stop at Pfeiffer Beach, Bixby Creek Bridge, McWay Falls, and Julia Pfeiffer Burns State Park.

4. **San Simeon**  
   - Tour Hearst Castle, a magnificent historic estate with stunning architecture and gardens.

5. **Cambria or Morro Bay**  
   - Enjoy small-town charm, local shops, and coastal scenery.

6. **Elephant Seal Rookery at Piedras Blancas**  
   - See seals along the coast (near San Simeon).

7. **Santa Barbara**  
   - Often called the "American Riviera," it's known for beautiful beaches, Spanish-style architecture, and lively downtown.

8. **Malibu**  
   - Famous for its beaches and celebrity homes. Consider a quick stop at Zuma Beach or Malibu Pier.

If you're looking for a more inland route, you can also take Interstate 5 and explore some of California’s inland attractions, but the coastal drive offers some of the most iconic scenic views.

Would you like a suggested itinerary or specific activity recommendations at any of these stops?
Creative Writing — Longer completion for creative output
TypeScript
const response = await env.AI.run(
'openai/gpt-4.1-nano',
{
max_completion_tokens: 8192,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
},
)
console.log(response)
Detective Mara Collins cautiously stepped into the dimly lit workshop, the scent of oil and old wood lingering in the air. Pieces of broken clock gears and scattered tools dotted the cluttered space, but it was the tiny, shimmering feather tucked behind a loose brick that caught her eye. It was unlike any bird feather she’d seen—irregularly shaped, iridescent, and strangely warm to the touch. As she examined it, a shiver ran down her spine, promising that this was no ordinary clue, but a signature left behind by someone desperately trying to be remembered.
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'openai/gpt-4.1-nano',
{
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 technique where a function calls itself to solve a problem. It’s especially useful when a problem can be broken down into smaller, similar subproblems. Each recursive call works on a smaller piece, and the process continues until a basic case is reached, which stops the recursion.

**Simple Example:** Calculating the factorial of a number

The factorial of a number \( n \) (written as \( n! \)) is the product of all positive integers up to \( n \).

For example:
\[ 5! = 5 \times 4 \times 3 \times 2 \times 1 = 120 \]

**Recursive approach:**

- The factorial of \( n \) is \( n \) multiplied by the factorial of \( n-1 \).
- Base case: factorial of 1 (or 0) is 1.

**Python code example:**

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

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

In this example:
- When `factorial(5)` is called, it computes \( 5 \times factorial(4) \).
- `factorial(4)` computes \( 4 \times factorial(3) \), and so on.
- When it reaches `factorial(1)`, it hits the base case and returns 1.
- The recursive calls then resolve, multiplying the numbers back up to give the final result.

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