---
description: Run AI models on Cloudflare's global network using Workers AI, AI Gateway, and other integrated AI products.
title: AI
image: https://developers.cloudflare.com/ai/og.png?v=6924eb1785caad15
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/ai/llms.txt  
> Use this file to discover all available pages before exploring further.

# AI

Last updated Sep 30, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

Run AI models on Cloudflare's global network.

Available on all plans

Cloudflare AI provides a unified platform for running AI models, whether hosted on Cloudflare infrastructure (Workers AI) or proxied through AI Gateway to external providers.

## Get started

[Models](https://developers.cloudflare.com/ai/models/)

Explore all AI models available through Cloudflare, including hosted models on Workers AI and external providers through AI Gateway.

Browse models

## Related products

[Workers AI](https://developers.cloudflare.com/workers-ai/)

Run machine learning models, powered by serverless GPUs, on Cloudflare's global network.

[AI Gateway](https://developers.cloudflare.com/ai-gateway/)

Observe and control your AI applications with caching, rate limiting, request retries, model fallback, and more.

[Vectorize](https://developers.cloudflare.com/vectorize/)

Build full-stack AI applications with Vectorize, Cloudflare's vector database.

[Agents](https://developers.cloudflare.com/agents/)

Build AI-powered agents to perform tasks, persist state, and interact with external services.

[AI Search](https://developers.cloudflare.com/ai-search/)

Create fully managed RAG pipelines for your AI applications.

[AI Crawl Control](https://developers.cloudflare.com/ai-crawl-control/)

Analyze and control third-party AI crawlers on your website.

[Browser Rendering](https://developers.cloudflare.com/browser-run/)

Control and interact with headless browser instances for AI data extraction.

[Agent Lee](https://developers.cloudflare.com/agent-lee/)

An AI-powered assistant that helps you navigate, configure, and manage Cloudflare.

[Dynamic Workers](https://developers.cloudflare.com/dynamic-workers/)

Spin up isolated Workers on demand to execute code.

[Sandboxes](https://developers.cloudflare.com/sandbox/)

Run untrusted or generated code in isolated Workers or Linux virtual machines.

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/ai/#page","headline":"AI","description":"Run AI models on Cloudflare's global network using Workers AI, AI Gateway, and other integrated AI products.","url":"https://developers.cloudflare.com/ai/","inLanguage":"en","image":"https://developers.cloudflare.com/ai/og.png?v=6924eb1785caad15","dateModified":"2026-09-30","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["AI"]}
```

---

---
description: Browse AI models available through Cloudflare, including hosted models on Workers AI and external providers via AI Gateway.
title: Models
image: https://developers.cloudflare.com/ai/models/og.png?v=bb7974aa265b08c2
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/ai/llms.txt  
> Use this file to discover all available pages before exploring further.

# Models

Last updated Aug 12, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

Task TypesCapabilitiesProvidersAuthorsNewest first

We found 241 modelsClear filters

## Compare models

Compare up to three models.

Close

Clear comparison

No models found

Try a different search term, or broaden your search by removing filters.

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>hh1-i2v</h3>

AlibabaImage-to-Video Alibaba's HappyHorse 1.0 image-to-video model. Animates a reference image with an optional text prompt. Supports 720P and 1080P output with durations from 3 to 15 seconds.](https://developers.cloudflare.com/ai/models/alibaba/hh1-i2v/)

- Third-party
- +1

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>hh1-t2v</h3>

AlibabaText-to-Video Alibaba's HappyHorse 1.0 text-to-video model. Generates videos from a text prompt with configurable resolution, aspect ratio, and duration (3-15s).](https://developers.cloudflare.com/ai/models/alibaba/hh1-t2v/)

- Third-party
- +1

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>hh1.1-i2v</h3>

AlibabaImage-to-Video Alibaba's HappyHorse 1.1 image-to-video model. Animates a reference image with an optional text prompt, with smoother motion, natural skin textures, and improved close-up quality over 1.0. Supports 720P and 1080P output with durations from 3 to 15 seconds.](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-i2v/)

- Third-party

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>hh1.1-r2v</h3>

AlibabaImage-to-Video Alibaba's HappyHorse 1.1 reference-to-video model. Takes 1-9 reference images (characters and scenes) and a prompt that choreographs them into a single video, keeping each subject's identity consistent. Supports 720P and 1080P output with durations from 3 to 15 seconds.](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-r2v/)

- Third-party

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>hh1.1-t2v</h3>

AlibabaText-to-Video Alibaba's HappyHorse 1.1 text-to-video model. Generates videos from a text prompt with stronger dynamic expressiveness, better visual quality, and improved instruction following over 1.0. Configurable resolution, aspect ratio, and duration (3-15s).](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-t2v/)

- Third-party

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>qwen-image-3.0-pro</h3>

AlibabaText-to-Image Alibaba's Qwen Image 3.0 Pro generates images from text prompts with a focus on complex layout generation, small-text precision, and multilingual font rendering. Supports up to 6 image variants per call, negative prompts, seed control, and optional prompt rewriting.](https://developers.cloudflare.com/ai/models/alibaba/qwen-image-3.0-pro/)

- Third-party

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>qwen3-max</h3>

AlibabaText Generation Alibaba's Qwen 3 Max is a large language model with strong coding, reasoning, and multilingual capabilities, served via DashScope's OpenAI-compatible endpoint.](https://developers.cloudflare.com/ai/models/alibaba/qwen3-max/)

- Third-party
- +1

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>qwen3.5-397b-a17b</h3>

AlibabaText Generation Alibaba's Qwen 3.5 is a 397B-parameter mixture-of-experts model with 17B active parameters, offering strong reasoning capabilities with efficient inference.](https://developers.cloudflare.com/ai/models/alibaba/qwen3.5-397b-a17b/)

- Third-party
- +1

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>qwen3.7-max</h3>

AlibabaText Generation Alibaba's Qwen 3.7 Max is the largest and most capable model in the Qwen3.7 series, a next-generation flagship built for the agent-centric era with deep strengths in programming, office and productivity tasks, and long-term autonomous execution, served via DashScope's OpenAI-compatible endpoint.](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-max/)

- Third-party

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>qwen3.7-plus</h3>

AlibabaText Generation Alibaba's Qwen 3.7 Plus is the cost-effective member of the Qwen3.7 series, pairing strong text capabilities with image and video understanding and full-stack agent-level intelligence for coding, tool use, and GUI-based automation, served via DashScope's OpenAI-compatible endpoint.](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-plus/)

- Third-party

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>qwen3.8-max</h3>

AlibabaText Generation Alibaba's Qwen 3.8 Max is a 2.4-trillion-parameter MoE flagship built for professional-grade coding and long-horizon autonomous work, capable of delivering complete, production-grade projects spanning 10+ days across legal, financial, design, and other specialized domains. Native visual understanding of images and extended video runs through the full plan-execute-verify cycle, served via DashScope's OpenAI-compatible endpoint.](https://developers.cloudflare.com/ai/models/alibaba/qwen3.8-max/)

- Third-party

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>wan-2.6-image</h3>

AlibabaText-to-Image Alibaba's Wan 2.6 text-to-image model generating images from text prompts with optional negative prompts and customizable dimensions.](https://developers.cloudflare.com/ai/models/alibaba/wan-2.6-image/)

- Third-party
- +1

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>wan-2.7-i2v</h3>

AlibabaImage-to-Video Alibaba's Wan 2.7 image-to-video model that generates videos from a reference image with optional text prompts. Supports 720P and 1080P output with durations from 2 to 15 seconds.](https://developers.cloudflare.com/ai/models/alibaba/wan-2.7-i2v/)

- Third-party
- +1

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>wan-3.0</h3>

AlibabaText-to-Video Alibaba's Wan 3.0 text-to-video model. Generates cinematic videos from text prompts with adaptive aspect ratio, 480P, 720P, or 1080P resolution, and configurable duration.](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0/)

- Third-party

Compare

[![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)<h3>wan-3.0-prime</h3>

AlibabaText-to-Video Alibaba's Wan 3.0 Prime text-to-video model. Generates cinematic videos from text prompts with adaptive aspect ratio, 480P, 720P, or 1080P resolution, and configurable duration.](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0-prime/)

- Third-party

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-fable-5</h3>

AnthropicText Generation Claude Fable 5 is Anthropic's most capable widely released model, built for the most demanding reasoning and long-horizon agentic work. Adaptive thinking is always on, and the model supports a 1M token context window with up to 128k output tokens per request.](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5/)

- Third-party

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-fable-5.1</h3>

AnthropicText Generation Claude Fable 5.1 is Anthropic's next model in the Fable family, with improvements in agentic coding, long-running agentic workflows, knowledge work, front-end and visual code generation, and finance and analysis tasks. It supports adaptive thinking and a 1M token context window.](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5.1/)

- Third-party

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-haiku-4.5</h3>

AnthropicText Generation Claude Haiku 4.5 delivers similar levels of coding performance at one-third the cost and more than twice the speed of larger models.](https://developers.cloudflare.com/ai/models/anthropic/claude-haiku-4.5/)

- Third-party
- +1

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-opus-4.5</h3>

AnthropicText Generation Claude Opus 4.5 brings further reasoning, coding, and agentic improvements over Opus 4.1, with stronger tool use and tighter instruction following.](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.5/)

- Third-party
- +1

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-opus-4.6</h3>

AnthropicText Generation Claude Opus 4.6 is Anthropic's flagship language model built for complex, multi-step work in coding, financial analysis, and legal reasoning. It uses extended thinking to work through complex problems carefully and features a one million token context window.](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.6/)

- Third-party
- +1

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-opus-4.7</h3>

AnthropicText Generation Claude Opus 4.7 is Anthropic's most capable generally available model, with a step-change improvement in agentic coding over Claude Opus 4.6. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing.](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.7/)

- Third-party
- +1

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-opus-4.8</h3>

AnthropicText Generation Claude Opus 4.8 is Anthropic's most capable generally available model, with a step-change improvement in agentic coding over Claude Opus 4.7. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing.](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.8/)

- Third-party
- +1

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-opus-5</h3>

AnthropicText Generation Claude Opus 5 is Anthropic's model for complex agentic coding and enterprise work, delivering intelligence close to Claude Fable 5 at half the price. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing. Unlike Fable 5, Opus 5 has no data retention requirements for general access.](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5/)

- Third-party

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-opus-5.5</h3>

AnthropicText Generation Claude Opus 5.5 is Anthropic's model for long-running agentic coding and knowledge work. It combines a one million token context window with adaptive thinking that is always on, a 128K token maximum output, and a medium default effort level.](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5.5/)

- Third-party

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-sonnet-4.5</h3>

AnthropicText Generation Claude Sonnet 4.5 is the best coding model to date, with significant improvements across the entire development lifecycle.](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.5/)

- Third-party
- +1

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-sonnet-4.6</h3>

AnthropicText Generation Claude Sonnet 4.6 is Anthropic's latest balanced model offering strong coding, reasoning, and agentic capabilities with improved instruction following.](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.6/)

- Third-party
- +1

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-sonnet-5</h3>

AnthropicText Generation Claude Sonnet 5 is Anthropic's most agentic Sonnet model yet, built for coding, tool use, reasoning, and long-horizon professional work at lower cost than Opus-class models.](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5/)

- Third-party

Compare

[![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)<h3>claude-sonnet-5.5</h3>

AnthropicText Generation Claude Sonnet 5.5 offers the best combination of speed and intelligence, with adaptive thinking for coding, tool use, reasoning, and long-horizon work.](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5.5/)

- Third-party

Compare

[![AssemblyAI logo](https://developers.cloudflare.com/_astro/assemblyai.DKrad3Z3.svg)<h3>universal-3-pro</h3>

AssemblyAIAutomatic Speech Recognition AssemblyAI's Universal 3 Pro speech recognition model for high-accuracy transcription.](https://developers.cloudflare.com/ai/models/assemblyai/universal-3-pro/)

- Third-party
- +1

Compare

[![AssemblyAI logo](https://developers.cloudflare.com/_astro/assemblyai.DKrad3Z3.svg)<h3>universal-3.5-pro</h3>

AssemblyAIAutomatic Speech Recognition AssemblyAI's Universal-3.5 Pro speech recognition model for fast, high-accuracy transcription.](https://developers.cloudflare.com/ai/models/assemblyai/universal-3.5-pro/)

- Third-party

Compare

[![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)<h3>flux-1-kontext-max</h3>

Black Forest LabsText-to-Image FLUX.1 Kontext \[max\] is Black Forest Labs' highest-quality Kontext model for text-to-image generation and context-aware image editing.](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-max/)

- Third-party

Compare

[![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)<h3>flux-1-kontext-pro</h3>

Black Forest LabsText-to-Image FLUX.1 Kontext \[pro\] creates and edits images from text prompts with strong character and style consistency.](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-pro/)

- Third-party

Compare

[![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)<h3>flux-2-flex</h3>

Black Forest LabsText-to-Image FLUX.2 \[flex\] is Black Forest Labs' fine-grained control variant of FLUX.2 — exposes tunable inference steps, guidance, and prompt upsampling for typography-heavy and production workflows.](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-flex/)

- Third-party

Compare

[![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)<h3>flux-2-max</h3>

Black Forest LabsText-to-Image FLUX.2 \[max\] is Black Forest Labs' highest-quality image model — top editing consistency, strongest prompt following, and grounding search for visualizations of real-time information.](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-max/)

- Third-party

Compare

[![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)<h3>flux-2-pro-preview</h3>

Black Forest LabsText-to-Image FLUX.2 \[pro\] Preview is Black Forest Labs' recommended default for production image generation and editing — tracks the latest \[pro\] weights with strong multi-reference support.](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-pro-preview/)

- Third-party

Compare

[![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)<h3>flux-3-video</h3>

Black Forest LabsText-to-Video FLUX 3 Video is Black Forest Labs' video generation model. It generates video from a text prompt (t2v), animates one or more reference images (i2v), or continues an existing clip (v2v), with synchronized audio, up to fhd resolution, and 5-20 second durations.](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-3-video/)

- Third-party

Compare

[![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)<h3>flux-video-upscale</h3>

Black Forest Labsvideo-to-video FLUX Video Upscale increases video resolution with a precise mode for source-faithful results and a creative mode for stronger detail enhancement. It accepts clips up to 20 seconds and preserves audio.](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-video-upscale/)

- Third-party

Compare

[b<h3>fibo-edit-1.5</h3>

briaImage-to-Image FIBO Edit changes one to four input images from a natural-language or structured JSON (VGL) instruction. Add a black-and-white mask to edit only part of a single image, or refer to several images as "image 1", "image 2", and so on to combine them or transfer a style.](https://developers.cloudflare.com/ai/models/bria/fibo-edit-1.5/)

- Third-party

Compare

[b<h3>fibo-generate-1.5</h3>

briaText-to-Image FIBO Generate creates images from a text prompt, a reference image, or both. Each result includes the seed and the structured JSON (VGL) prompt used to render it; send them back to recreate the image exactly or to refine it with a new prompt. Outputs are 1MP or 4MP in nine aspect ratios.](https://developers.cloudflare.com/ai/models/bria/fibo-generate-1.5/)

- Third-party

Compare

[b<h3>remove-background</h3>

briaImage-to-Image Bria's RMBG 2.0 model removes the background from an image and returns a PNG cutout with a transparent background. Partial transparency from the input's alpha channel is kept by default.](https://developers.cloudflare.com/ai/models/bria/remove-background/)

- Third-party

Compare

[b<h3>v-rmbg-3.0</h3>

briavideo-to-video Bria's video background removal replaces the background of a clip up to 60 seconds long with a solid color or with transparency. Transparent output needs the mov\_proresks (ProRes) preset. Frame rate and audio are preserved, and the output resolution matches the input unless auto\_zoom crops to the subject.](https://developers.cloudflare.com/ai/models/bria/v-rmbg-3.0/)

- Third-party

Compare

[![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)<h3>seedance-2.0</h3>

ByteDanceText-to-Video ByteDance's next-generation video model with a unified multimodal architecture. Generates high-quality video with synchronized audio from text, images, video clips, and audio inputs. Supports multimodal references (up to 9 images, 3 videos, 3 audio files), native audio generation, video editing, video extension, intelligent duration, and adaptive aspect ratio.](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0/)

- Third-party

Compare

[![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)<h3>seedance-2.0-fast</h3>

ByteDanceText-to-Video Faster variant of ByteDance's Seedance 2.0 video model. Trades some quality for speed while sharing the same multimodal architecture. Supports text-to-video, image-to-video, native audio generation, multimodal references (images, videos, audio), video editing, and video extension.](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-fast/)

- Third-party

Compare

[![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)<h3>seedance-2.0-mini</h3>

ByteDanceText-to-Video ByteDance's compact, cost-efficient video generation model from the Seedance 2.0 family. Supports text-to-video, image-to-video, reference video, and reference audio for background music. Ideal for high-volume workloads where speed and cost matter.](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-mini/)

- Third-party

Compare

[![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)<h3>seedance-2.5</h3>

ByteDanceText-to-Video ByteDance's next-generation video model with a unified multimodal reference-to-video architecture. Generates video from text, up to 30 reference images, 10 reference videos, and 10 reference audio clips — including audio-only input with no image or video required. Supports first/last-frame image-to-video, video editing, video extension, intelligent duration (including automatic selection), and adaptive aspect ratio.](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/)

- Third-party

Compare

[![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)<h3>seedream-4.0</h3>

ByteDanceText-to-Image Seedream 4.0 is ByteDance's image creation model that combines text-to-image generation and image editing into a single architecture, offering fast, high-resolution output up to 4K.](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.0/)

- Third-party

Compare

[![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)<h3>seedream-4.5</h3>

ByteDanceText-to-Image Seedream 4.5 builds on 4.0 with multi-reference image support, batch generation, and sequential image generation.](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.5/)

- Third-party

Compare

[![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)<h3>seedream-5-lite</h3>

ByteDanceText-to-Image Seedream 5 Lite is a lighter, faster version of the Seedream 5 family with multi-reference and batch generation support.](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-lite/)

- Third-party

Compare

[![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)<h3>seedream-5-pro</h3>

ByteDanceText-to-Image Seedream 5 Pro is ByteDance's high-quality image generation and editing model with text prompts, up to 10 reference images, and 1K, 2K, or explicit pixel-size output controls.](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/)

- Third-party

Compare

[d<h3>deepseek-v4-pro</h3>

deepseekText Generation DeepSeek V4 Pro is a high-capability reasoning model from DeepSeek, served via Fireworks infrastructure for production-grade inference.](https://developers.cloudflare.com/ai/models/deepseek/deepseek-v4-pro/)

- Third-party

Compare

[![ElevenLabs logo](https://developers.cloudflare.com/_astro/elevenlabs.0RXw7U95.svg)<h3>eleven-flash-v2-5</h3>

ElevenLabsText-to-Speech ElevenLabs' low-latency Flash v2.5 text-to-speech model for fast multilingual speech generation.](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-flash-v2-5/)

- Third-party

Compare

[![ElevenLabs logo](https://developers.cloudflare.com/_astro/elevenlabs.0RXw7U95.svg)<h3>eleven-multilingual-v2</h3>

ElevenLabsText-to-Speech ElevenLabs' multilingual text-to-speech model for generating natural speech across many languages with ElevenLabs voices.](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-multilingual-v2/)

- Third-party

Compare

[![ElevenLabs logo](https://developers.cloudflare.com/_astro/elevenlabs.0RXw7U95.svg)<h3>eleven-turbo-v2-5</h3>

ElevenLabsText-to-Speech ElevenLabs' Turbo v2.5 text-to-speech model balancing high-quality voice generation with low latency across 32 languages.](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-turbo-v2-5/)

- Third-party

Compare

[![ElevenLabs logo](https://developers.cloudflare.com/_astro/elevenlabs.0RXw7U95.svg)<h3>eleven-v3</h3>

ElevenLabsText-to-Speech ElevenLabs' latest text-to-speech model for highly expressive, natural speech generation with advanced voice control.](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-v3/)

- Third-party

Compare

[![ElevenLabs logo](https://developers.cloudflare.com/_astro/elevenlabs.0RXw7U95.svg)<h3>music-v2</h3>

ElevenLabsMusic Generation ElevenLabs Music v2 composes songs and instrumental tracks from a prompt or detailed composition plan.](https://developers.cloudflare.com/ai/models/elevenlabs/music-v2/)

- Third-party

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-2.5-flash</h3>

GoogleText Generation Google's fast multimodal Gemini 2.5 model with strong reasoning and a 1M token context window.](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-2.5-flash-lite</h3>

GoogleText Generation Google's lightest and most cost-efficient Gemini 2.5 model for high-throughput tasks.](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash-lite/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-2.5-pro</h3>

GoogleText Generation Google's most capable Gemini 2.5 model with strong reasoning, thinking support, and a 1M token context window.](https://developers.cloudflare.com/ai/models/google/gemini-2.5-pro/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-3-flash</h3>

GoogleText Generation Gemini 3 Flash is Google's fast multimodal model with frontier intelligence, superior search, and grounding capabilities.](https://developers.cloudflare.com/ai/models/google/gemini-3-flash/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-3.1-flash-lite</h3>

GoogleText Generation Google's lightest and most cost-efficient Gemini model for high-throughput tasks.](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-lite/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-3.1-flash-tts</h3>

GoogleText-to-Speech](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-tts/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-3.1-pro</h3>

GoogleText Generation Google's most intelligent Gemini model with improved reasoning, a medium thinking level, and a 1M token context window.](https://developers.cloudflare.com/ai/models/google/gemini-3.1-pro/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-3.5-flash</h3>

GoogleText Generation Gemini 3.5 Flash is Google's fast multimodal model with frontier intelligence, superior search, and grounding capabilities.](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash/)

- Third-party

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-3.5-flash-lite</h3>

GoogleText Generation Gemini 3.5 Flash-Lite is a low-latency, cost-effective multimodal model optimized for high-throughput, low-cost execution for subagent tasks and document parsing.](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash-lite/)

- Third-party

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-3.6-flash</h3>

GoogleText Generation Gemini 3.6 Flash provides sustained frontier-level intelligence optimized for real-world tasks at a higher speed and lower cost, excelling at code generation, agentic execution, and spatial reasoning.](https://developers.cloudflare.com/ai/models/google/gemini-3.6-flash/)

- Third-party

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-3.7-flash</h3>

GoogleText Generation Gemini 3.7 Flash is a highly capable, natively multimodal reasoning model optimized for agentic workflows and real-world tasks.](https://developers.cloudflare.com/ai/models/google/gemini-3.7-flash/)

- Third-party

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-3.8-flash</h3>

GoogleText Generation Our most intelligent Flash model, engineered for long-horizon software engineering, autonomous agents, and complex enterprise workflows.](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash/)

- Third-party

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-3.8-flash-lite-tts</h3>

GoogleText-to-Speech Gemini 3.8 Flash-Lite TTS is a fast, cost-efficient text-to-speech model optimized for high-throughput production workloads.](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-lite-tts/)

- Third-party

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-3.8-flash-tts</h3>

GoogleText-to-Speech Gemini 3.8 Flash TTS is Google's flagship text-to-speech model for expressive, natural speech generation.](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-tts/)

- Third-party

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-omni-1.1-flash</h3>

GoogleText-to-Video High-performance multimodal video generation and editing model with conversational controls and generated audio.](https://developers.cloudflare.com/ai/models/google/gemini-omni-1.1-flash/)

- Third-party

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemini-omni-flash</h3>

GoogleText-to-Video Preview high-performance multimodal video generation and editing model with conversational controls and generated audio.](https://developers.cloudflare.com/ai/models/google/gemini-omni-flash/)

- Third-party

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>nano-banana</h3>

GoogleText-to-Image Google's fast image generation model producing high-quality images from text prompts.](https://developers.cloudflare.com/ai/models/google/nano-banana/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>nano-banana-2</h3>

GoogleText-to-Image Google's second-generation image generation model with improved quality and speed.](https://developers.cloudflare.com/ai/models/google/nano-banana-2/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>nano-banana-2-lite</h3>

GoogleText-to-Image Google's fastest Gemini image generation model for rapid image creation and iteration.](https://developers.cloudflare.com/ai/models/google/nano-banana-2-lite/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>nano-banana-pro</h3>

GoogleText-to-Image Google's higher-quality image generation model with improved detail and prompt adherence.](https://developers.cloudflare.com/ai/models/google/nano-banana-pro/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>veo-3.1</h3>

GoogleText-to-Video Google's latest video generation model with improved quality, motion, and audio generation.](https://developers.cloudflare.com/ai/models/google/veo-3.1/)

- Third-party
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>veo-3.1-fast</h3>

GoogleText-to-Video A faster version of Veo 3.1 optimized for lower latency while maintaining high-quality video and audio output.](https://developers.cloudflare.com/ai/models/google/veo-3.1-fast/)

- Third-party
- +1

Compare

[![Inworld logo](https://developers.cloudflare.com/_astro/inworld.BDwMAXI2.svg)<h3>tts-1.5-max</h3>

InworldText-to-Speech Highest-quality text-to-speech with under 200ms latency, emotion control, and 15-language support.](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-max/)

- Third-party
- +1

Compare

[![Inworld logo](https://developers.cloudflare.com/_astro/inworld.BDwMAXI2.svg)<h3>tts-1.5-mini</h3>

InworldText-to-Speech Ultra-fast, cost-efficient text-to-speech with approximately 120ms latency and 15-language support.](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-mini/)

- Third-party
- +1

Compare

[![Inworld logo](https://developers.cloudflare.com/_astro/inworld.BDwMAXI2.svg)<h3>tts-2</h3>

InworldText-to-Speech Inworld's most powerful and expressive text-to-speech model. Builds on TTS 1.5 with rich expressive speech, real-time latency, natural language steering (e.g. \[whisper\], \[say excitedly\]), and stronger multilingual support across 15 production languages plus 90+ experimental languages.](https://developers.cloudflare.com/ai/models/inworld/tts-2/)

- Third-party
- +1

Compare

[k<h3>krea-2-large</h3>

kreaText-to-Image More than 2x the size of Medium, with softer post-training. Outputs are rawer, more textured, and more flexible — at its best, Large produces results Medium can't match. Strongest on photorealism, raw looks (motion blur, grain, low dynamic range), and expressive and artistic styles.](https://developers.cloudflare.com/ai/models/krea/krea-2-large/)

- Third-party

Compare

[k<h3>krea-2-medium</h3>

kreaText-to-Image Smaller, faster, more cost-efficient. Extensive post-training makes outputs especially stable and consistent across generations. Strongest on illustration, anime, painting, and other expressive or artistic styles.](https://developers.cloudflare.com/ai/models/krea/krea-2-medium/)

- Third-party

Compare

[k<h3>krea-2-medium-turbo</h3>

kreaText-to-Image The fastest Krea 2 model, built for low-cost iteration on expressive illustrations, style-driven concepts, and rapid visual exploration. Keeps the Krea 2 style system and expressive visual range but uses a distilled sampling schedule so you can move through ideas much faster. Especially useful for expressive illustration, graphic styles, typography experiments, and quick campaign or concept directions.](https://developers.cloudflare.com/ai/models/krea/krea-2-medium-turbo/)

- Third-party

Compare

[l<h3>ltx-2-5-fast</h3>

lightricksText-to-Video Lightricks LTX-2.5 Fast is a fast video generation model for text-to-video and image-to-video workflows, with synchronized audio, configurable duration, resolution, and frame rate.](https://developers.cloudflare.com/ai/models/lightricks/ltx-2-5-fast/)

- Third-party

Compare

[![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)<h3>h3</h3>

MiniMaxText-to-Video A multimodal video generation model supporting text-to-video, first and last frame image-to-video, and reference-to-video generation with 768P and 2K output.](https://developers.cloudflare.com/ai/models/minimax/h3/)

- Third-party

Compare

[![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)<h3>h3-max</h3>

MiniMaxText-to-Video A fast multimodal video generation model supporting text-to-video and image-to-video generation at 480P and 768P.](https://developers.cloudflare.com/ai/models/minimax/h3-max/)

- Third-party

Compare

[![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)<h3>hailuo-2.3</h3>

MiniMaxText-to-Video A high-fidelity video generation model optimized for realistic human motion, cinematic VFX, expressive characters, and strong prompt and style adherence across text-to-video and image-to-video workflows.](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3/)

- Third-party
- +1

Compare

[![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)<h3>hailuo-2.3-fast</h3>

MiniMaxText-to-Video A lower-latency version of Hailuo 2.3 that preserves core motion quality, visual consistency, and stylization while enabling faster iteration.](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3-fast/)

- Third-party
- +1

Compare

[![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)<h3>m2.7</h3>

MiniMaxText Generation MiniMax's M2.7 language model with multilingual capabilities.](https://developers.cloudflare.com/ai/models/minimax/m2.7/)

- Third-party
- +1

Compare

[![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)<h3>m3</h3>

MiniMaxText Generation MiniMax's M3 language model with frontier coding and agentic capabilities, a 1M token context window, and multilingual support.](https://developers.cloudflare.com/ai/models/minimax/m3/)

- Third-party
- +1

Compare

[![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)<h3>music-2.6</h3>

MiniMaxMusic Generation MiniMax's music generation model that creates full-length songs with vocals from text prompts and lyrics, or instrumental tracks. Supports BPM/key control and auto-generated lyrics.](https://developers.cloudflare.com/ai/models/minimax/music-2.6/)

- Third-party
- +1

Compare

[![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)<h3>speech-2.8-hd</h3>

MiniMaxText-to-Speech MiniMax Speech 2.8 HD focuses on studio-grade audio generation with emotion control, multilingual support (40+ languages), and voice cloning.](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-hd/)

- Third-party
- +1

Compare

[![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)<h3>speech-2.8-turbo</h3>

MiniMaxText-to-Speech MiniMax Speech 2.8 Turbo turns text into natural, expressive speech with voice cloning, emotion control, and 40+ language support at faster speeds.](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-turbo/)

- Third-party
- +1

Compare

[![Moonshot AI logo](https://developers.cloudflare.com/_astro/moonshotai.DjWMkXUS.svg)<h3>kimi-k3</h3>

Moonshot AIText Generation Kimi K3 is Moonshot's flagship 2.8 trillion-parameter model, built on Kimi Delta Attention (a hybrid linear attention mechanism) with Attention Residuals. It offers native visual understanding, always-on reasoning, and a 1M-token context window for long-horizon coding, knowledge work, and deep reasoning tasks.](https://developers.cloudflare.com/ai/models/moonshotai/kimi-k3/)

- Third-party

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-4.1</h3>

OpenAIText Generation OpenAI's flagship GPT model for complex tasks with a million-token context window.](https://developers.cloudflare.com/ai/models/openai/gpt-4.1/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-4.1-mini</h3>

OpenAIText Generation Fast, affordable version of GPT-4.1 with a million-token context window.](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-mini/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-4.1-nano</h3>

OpenAIText Generation GPT-4.1 Nano is OpenAI’s smallest and cheapest GPT-4.1 variant, optimized for high-throughput, low-latency tasks.](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-nano/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-4o</h3>

OpenAIText Generation GPT-4o is OpenAI’s multimodal flagship, accepting text and images and responding quickly across a wide range of tasks.](https://developers.cloudflare.com/ai/models/openai/gpt-4o/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-4o-mini</h3>

OpenAIText Generation GPT-4o Mini is the lightweight, low-cost variant of GPT-4o, well suited to high-volume tasks with multimodal inputs.](https://developers.cloudflare.com/ai/models/openai/gpt-4o-mini/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-4o-transcribe</h3>

OpenAIAutomatic Speech Recognition A speech-to-text model that uses GPT-4o to transcribe audio with improved word error rate and better language recognition compared to original Whisper models.](https://developers.cloudflare.com/ai/models/openai/gpt-4o-transcribe/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5</h3>

OpenAIText Generation OpenAI's model excelling at coding, writing, and reasoning.](https://developers.cloudflare.com/ai/models/openai/gpt-5/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5-mini</h3>

OpenAIText Generation GPT-5 Mini is the lightweight, low-cost variant of GPT-5, well suited to high-volume coding and reasoning tasks.](https://developers.cloudflare.com/ai/models/openai/gpt-5-mini/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5-nano</h3>

OpenAIText Generation GPT-5 Nano is OpenAI’s smallest GPT-5 variant, optimized for low latency and cheap, high-throughput tasks.](https://developers.cloudflare.com/ai/models/openai/gpt-5-nano/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5.1</h3>

OpenAIText Generation GPT-5.1 is OpenAI’s incremental improvement over GPT-5, with stronger coding, reasoning, and writing.](https://developers.cloudflare.com/ai/models/openai/gpt-5.1/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5.4</h3>

OpenAIText Generation GPT-5.4 is OpenAI's flagship model with strong coding, reasoning, and multimodal capabilities.](https://developers.cloudflare.com/ai/models/openai/gpt-5.4/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5.4-mini</h3>

OpenAIText Generation GPT-5.4 mini is a smaller, faster, and more cost-efficient version of GPT-5.4 for lightweight tasks.](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-mini/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5.4-nano</h3>

OpenAIText Generation GPT-5.4 nano is OpenAI's smallest and fastest model, optimized for edge and low-latency use cases.](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-nano/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5.4-pro</h3>

OpenAIText Generation GPT-5.4 pro uses OpenAI's Responses API with built-in tools, improved reasoning, and stateful context management.](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-pro/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5.5</h3>

OpenAIText Generation GPT-5.5 is OpenAI's flagship model with strong coding, reasoning, and multimodal capabilities.](https://developers.cloudflare.com/ai/models/openai/gpt-5.5/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5.5-pro</h3>

OpenAIText Generation GPT-5.5 pro uses OpenAI's Responses API with built-in tools, improved reasoning, and stateful context management.](https://developers.cloudflare.com/ai/models/openai/gpt-5.5-pro/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5.6-luna</h3>

OpenAIText Generation GPT-5.6 Luna is an OpenAI GPT-5.6 model optimized for cost-sensitive workloads, using the Responses API for efficient text generation.](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-luna/)

- Third-party

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5.6-sol</h3>

OpenAIText Generation GPT-5.6 Sol is OpenAI's frontier GPT-5.6 model for complex professional work, using the Responses API for reasoning and stateful context management.](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-sol/)

- Third-party

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-5.6-terra</h3>

OpenAIText Generation GPT-5.6 Terra is an OpenAI GPT-5.6 model that balances intelligence and cost, using the Responses API for reasoning and stateful context management.](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-terra/)

- Third-party

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-6-astra</h3>

OpenAIText Generation GPT-6 Astra is OpenAI's most capable model, built for complex reasoning, coding, computer use, research, and document creation.](https://developers.cloudflare.com/ai/models/openai/gpt-6-astra/)

- Third-party

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-6-luna</h3>

OpenAIText Generation GPT-6 Luna is OpenAI's most efficient GPT-6 model, built for focused, high-volume tasks.](https://developers.cloudflare.com/ai/models/openai/gpt-6-luna/)

- Third-party

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-6-sol</h3>

OpenAIText Generation GPT-6 Sol is OpenAI's mid-tier GPT-6 model, built to power complex coding and agentic workflows.](https://developers.cloudflare.com/ai/models/openai/gpt-6-sol/)

- Third-party

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-6.1-sol</h3>

OpenAIText Generation GPT-6.1 Sol is OpenAI's newest Sol model, delivering near-Astra performance at a lower cost for complex coding, computer use, and professional work.](https://developers.cloudflare.com/ai/models/openai/gpt-6.1-sol/)

- Third-party

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-image-1.5</h3>

OpenAIText-to-Image OpenAI's image generation model that creates and edits images from text prompts, supporting multiple quality levels and output sizes.](https://developers.cloudflare.com/ai/models/openai/gpt-image-1.5/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-image-2</h3>

OpenAIText-to-Image OpenAI's next-generation image model that creates and edits images from text prompts, with support for multiple quality levels, sizes, and output formats. Note: transparent backgrounds are not supported — use openai/gpt-image-1.5 for transparent PNGs.](https://developers.cloudflare.com/ai/models/openai/gpt-image-2/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-image-2.5-flare</h3>

OpenAIText-to-Image OpenAI's fastest high-quality everyday image generation model. It accepts text and image inputs and produces images with low, medium, high, xhigh, max, and auto quality settings.](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-flare/)

- Third-party

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-image-2.5-sunburst</h3>

OpenAIText-to-Image OpenAI's most capable image generation and editing model. It accepts text and image inputs and produces images with low, medium, high, xhigh, max, and auto quality settings.](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-sunburst/)

- Third-party

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>o3</h3>

OpenAIText Generation o3 is OpenAI’s general-purpose reasoning model, balancing strong analytical performance with reasonable latency and cost.](https://developers.cloudflare.com/ai/models/openai/o3/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>o3-mini</h3>

OpenAIText Generation o3-mini is the lightweight, low-cost reasoning variant of o3, well suited to quick analytical tasks at scale.](https://developers.cloudflare.com/ai/models/openai/o3-mini/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>o4-mini</h3>

OpenAIText Generation OpenAI's fast, lightweight reasoning model optimized for multi-step problem solving at lower cost.](https://developers.cloudflare.com/ai/models/openai/o4-mini/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>tts-1</h3>

OpenAIText-to-Speech OpenAI's text-to-speech model optimized for real-time use with low latency.](https://developers.cloudflare.com/ai/models/openai/tts-1/)

- Third-party
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>tts-1-hd</h3>

OpenAIText-to-Speech OpenAI's high-definition text-to-speech model producing higher quality audio output.](https://developers.cloudflare.com/ai/models/openai/tts-1-hd/)

- Third-party
- +1

Compare

[![PixVerse logo](https://developers.cloudflare.com/_astro/pixverse.DSyGEAYR.svg)<h3>v5.6</h3>

PixVerseText-to-Video Pixverse v5.6 is a video generation model supporting text-to-video and image-to-video with audio generation, customizable aspect ratios, and up to 1080p output.](https://developers.cloudflare.com/ai/models/pixverse/v5.6/)

- Third-party
- +1

Compare

[![PixVerse logo](https://developers.cloudflare.com/_astro/pixverse.DSyGEAYR.svg)<h3>v6</h3>

PixVerseText-to-Video Pixverse v6 is the latest Pixverse video model with support for up to 15-second videos, customizable duration from 1 to 15 seconds, and audio generation.](https://developers.cloudflare.com/ai/models/pixverse/v6/)

- Third-party
- +1

Compare

[![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)<h3>p-image</h3>

Pruna AIText-to-Image Pruna's P-Image is an ultra-fast text-to-image model with automatic prompt enhancement and 2-stage refinement, combining exceptional speed with high-quality output and flexible aspect ratios.](https://developers.cloudflare.com/ai/models/pruna/p-image/)

- Third-party

Compare

[![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)<h3>p-image-edit</h3>

Pruna AIImage-to-Image Pruna's P-Image-Edit edits and composes 1-5 reference images with text instructions. It supports complex compositions, style transfers, and targeted edits with flexible output aspect ratios.](https://developers.cloudflare.com/ai/models/pruna/p-image-edit/)

- Third-party

Compare

[![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)<h3>p-image-try-on</h3>

Pruna AIImage-to-Image Pruna's P-Image Try-On virtually fits one or more garments onto a person's photo. Provide a photo of a person plus garment reference images and the model realistically dresses the person in the provided garments.](https://developers.cloudflare.com/ai/models/pruna/p-image-try-on/)

- Third-party

Compare

[![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)<h3>p-image-upscale</h3>

Pruna AIImage-to-Image Pruna's P-Image-Upscale increases image resolution using AI, targeting 1-128 megapixels with optional detail and realism enhancement for sharper, cleaner results.](https://developers.cloudflare.com/ai/models/pruna/p-image-upscale/)

- Third-party

Compare

[![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)<h3>p-video</h3>

Pruna AIText-to-Video Pruna's P-Video is a premium video generation model supporting text-to-video, image-to-video, and audio-conditioned generation up to 1080p at 24 or 48 fps, with configurable duration up to 20 seconds.](https://developers.cloudflare.com/ai/models/pruna/p-video/)

- Third-party

Compare

[![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)<h3>p-video-animate</h3>

Pruna AIImage-to-Video Pruna's P-Video-Animate takes a source video and a subject reference image, then animates the referenced subject using the motion and audio from the source video.](https://developers.cloudflare.com/ai/models/pruna/p-video-animate/)

- Third-party

Compare

[![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)<h3>p-video-avatar</h3>

Pruna AIImage-to-Video Pruna's P-Video-Avatar generates talking-head videos from a single portrait image driven by a text script or audio file, with multiple voices, languages, and output resolutions.](https://developers.cloudflare.com/ai/models/pruna/p-video-avatar/)

- Third-party

Compare

[![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)<h3>p-video-replace</h3>

Pruna AIImage-to-Video Pruna's P-Video-Replace takes a source video and one or more identity reference images, then places the referenced person or people into the video while preserving the source motion and audio.](https://developers.cloudflare.com/ai/models/pruna/p-video-replace/)

- Third-party

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv3</h3>

RecraftText-to-Image Recraft V3 is the previous-generation text-to-image model from Recraft, well-suited to design-quality compositions, brand-aware imagery, and accurate text rendering.](https://developers.cloudflare.com/ai/models/recraft/recraftv3/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4</h3>

RecraftText-to-Image Recraft V4 generates art-directed images with strong composition, accurate text rendering, and design taste built in. Fast and cost-efficient at standard resolution.](https://developers.cloudflare.com/ai/models/recraft/recraftv4/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4-1</h3>

RecraftText-to-Image Recraft V4.1 generates art-directed images tuned for high aesthetics, with strong composition, accurate text rendering, and refined design taste. Fast and cost-efficient at standard resolution.](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4-1-pro</h3>

RecraftText-to-Image Recraft V4.1 Pro generates high-resolution, art-directed images at 2048px+ tuned for high aesthetics, with strong composition, text rendering, and refined design taste. Built for print and production work.](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4-1-pro-vector</h3>

RecraftText-to-Image Generate detailed, high-resolution SVG vector graphics from text prompts with high aesthetic quality, fine geometry, scalable to any size for print and design work.](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro-vector/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4-1-utility</h3>

RecraftText-to-Image Recraft V4.1 Utility is a general-purpose text-to-image model balancing quality and flexibility for a wide range of everyday use cases at standard resolution.](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4-1-utility-pro</h3>

RecraftText-to-Image Recraft V4.1 Utility Pro is a general-purpose text-to-image model producing high-resolution 2048px+ output for a wide range of production and print use cases.](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4-1-utility-pro-vector</h3>

RecraftText-to-Image Generate detailed, high-resolution SVG vector graphics from text prompts with a general-purpose model, scalable to any size for print and large-scale design work.](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro-vector/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4-1-utility-vector</h3>

RecraftText-to-Image Generate production-ready SVG vector graphics from text prompts with a general-purpose model suited for a wide range of design and illustration tasks.](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-vector/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4-1-vector</h3>

RecraftText-to-Image Generate production-ready SVG vector graphics from text prompts with high aesthetic quality, clean geometry, structured layers, and editable paths.](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-vector/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4-pro</h3>

RecraftText-to-Image Recraft V4 Pro generates high-resolution, art-directed images at 2048px+ with strong composition, text rendering, and design taste. Built for print and production work.](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4-pro-vector</h3>

RecraftText-to-Image Generate detailed, production-ready SVG vector graphics from text prompts with fine geometry, scalable to any size for print and design work.](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro-vector/)

- Third-party
- +1

Compare

[![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)<h3>recraftv4-vector</h3>

RecraftText-to-Image Generate production-ready SVG vector graphics from text prompts with clean geometry, structured layers, and editable paths.](https://developers.cloudflare.com/ai/models/recraft/recraftv4-vector/)

- Third-party
- +1

Compare

[![RunwayML logo](https://developers.cloudflare.com/_astro/runway.Cq8Cjov4.svg)<h3>aleph-2</h3>

RunwayMLText-to-Video RunwayML's video editing model. Edit one frame to update your whole video, make changes across multiple shots, and work with up to 30 seconds of video. Supports keyframe-guided editing for precise control over specific moments in the clip.](https://developers.cloudflare.com/ai/models/runwayml/aleph-2/)

- Third-party

Compare

[![RunwayML logo](https://developers.cloudflare.com/_astro/runway.Cq8Cjov4.svg)<h3>gen-4.5</h3>

RunwayMLText-to-Video RunwayML's video generation model supporting both text-to-video and image-to-video with customizable duration, aspect ratio, and content moderation controls.](https://developers.cloudflare.com/ai/models/runwayml/gen-4.5/)

- Third-party

Compare

[t<h3>inkling</h3>

thinkingmachinesText Generation Inkling is Thinking Machines' open-weights hybrid reasoning model, built on a mixture-of-experts architecture. It reasons by default, exposing its chain-of-thought as leading thinking content blocks, with reasoning effort tunable via a Tinker-specific output\_config.effort parameter. Available through Tinker's beta Anthropic Messages-compatible endpoint alongside tool use, streaming, and multi-turn conversations. Currently intended for low-traffic testing and internal use rather than high-throughput production deployments; prompt caching, citations, and audio input are not supported through this endpoint.](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling/)

- Third-party

Compare

[t<h3>inkling-256k</h3>

thinkingmachinesText Generation The 256K-context variant of Inkling, Thinking Machines' open-weights hybrid reasoning MoE model. Same hybrid reasoning, tool-use, and streaming support as the base model, with an extended context window for longer conversations and documents. Currently intended for low-traffic testing and internal use rather than high-throughput production deployments.](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling-256k/)

- Third-party

Compare

[t<h3>jev</h3>

typesafeText Generation Jev is TypeSafe's structured evaluation model. It evaluates one state against typed Noul, Choice, and Score questions and returns calibrated answers with probabilities and confidence.](https://developers.cloudflare.com/ai/models/typesafe/jev/)

- Third-party
- +1

Compare

[u<h3>pareto</h3>

unbiasedText Generation Pareto is Unbiased's blended AI model. It engages multiple language models in parallel for each request, synthesizes one answer, and supports text and vision inputs through a single API response.](https://developers.cloudflare.com/ai/models/unbiased/pareto/)

- Third-party
- +1

Compare

[![Vidu logo](https://developers.cloudflare.com/_astro/vidu.CcN5bM2x.svg)<h3>q3-pro</h3>

ViduText-to-Video Vidu Q3 Pro is a high-quality video generation model supporting text-to-video, image-to-video, and start/end-frame-to-video workflows with audio and up to 16-second clips.](https://developers.cloudflare.com/ai/models/vidu/q3-pro/)

- Third-party
- +1

Compare

[![Vidu logo](https://developers.cloudflare.com/_astro/vidu.CcN5bM2x.svg)<h3>q3-turbo</h3>

ViduText-to-Video Vidu Q3 Turbo is a faster version of Vidu Q3 optimized for lower latency video generation while maintaining audio support and up to 16-second clips.](https://developers.cloudflare.com/ai/models/vidu/q3-turbo/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-4.20-0309-non-reasoning</h3>

xAIText Generation xAI's Grok 4.20 non-reasoning model. Skips the thinking trace for fast, single-pass responses while keeping the same training as the reasoning variant.](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-non-reasoning/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-4.20-0309-reasoning</h3>

xAIText Generation xAI's Grok 4.20 reasoning model. Uses extended thinking to work through complex problems, returning a reasoning trace alongside the final answer.](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-reasoning/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-4.20-multi-agent-0309</h3>

xAIText Generation xAI's Grok 4.20 multi-agent model with a 2M-token context window. Multiple agents collaborate in parallel to perform deep research tasks, with function calling, structured outputs, and reasoning capabilities.](https://developers.cloudflare.com/ai/models/xai/grok-4.20-multi-agent-0309/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-4.3</h3>

xAIText Generation xAI's Grok 4.3 model with a 1M-token context window and strong agentic tool calling with minimal hallucinations. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (none, low, medium, high).](https://developers.cloudflare.com/ai/models/xai/grok-4.3/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-4.5</h3>

xAIText Generation xAI's Grok 4.5, a frontier model built for coding, agentic tasks, and knowledge work. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (low, medium, high).](https://developers.cloudflare.com/ai/models/xai/grok-4.5/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-4.6</h3>

xAIText Generation xAI's Grok 4.6, a flagship reasoning model for coding, agentic tasks, and visual work. Accepts text and image inputs, and supports function calling and structured outputs.](https://developers.cloudflare.com/ai/models/xai/grok-4.6/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-4.7</h3>

xAIText Generation xAI's Grok 4.7, a frontier reasoning model for coding, agentic tasks, and knowledge work. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (low, medium, high, xhigh).](https://developers.cloudflare.com/ai/models/xai/grok-4.7/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-imagine-image</h3>

xAIText-to-Image xAI's Grok Imagine image model. Generates and edits images from text and reference-image inputs with configurable aspect ratio and resolution.](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-imagine-image-2.0</h3>

xAIText-to-Image xAI's Grok Imagine Image 2.0 is a precise image generation and editing model for creative work, with strong instruction following, typography, layout, and reference-image preservation.](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-2.0/)

- Third-party

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-imagine-image-quality</h3>

xAIText-to-Image xAI's higher-fidelity text-to-image model optimized for sharper details, more accurate compositions, and stronger text rendering. Supports image editing via reference images and masks. Trades speed for quality compared to grok-imagine-image. Default output at 2k resolution.](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-quality/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-imagine-video</h3>

xAIText-to-Video xAI's video generation model. Generates, edits, and extends videos from text and image inputs with native synchronized audio including dialogue, sound effects, and music. Supports multiple creative modes (normal, fun, custom).](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-imagine-video-1.5-preview</h3>

xAIImage-to-Video xAI's next-generation video generation model. Generates, edits, and extends videos from text and image inputs. Supports multiple aspect ratios and resolutions with improved quality over the previous generation.](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video-1.5-preview/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-stt</h3>

xAIAutomatic Speech Recognition xAI's Grok speech-to-text model. Transcribes audio files into text across 25 languages with word-level timestamps, multichannel transcription, speaker diarization, and key-term biasing.](https://developers.cloudflare.com/ai/models/xai/grok-stt/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-tts</h3>

xAIText-to-Speech xAI's Grok text-to-speech model. Generates high-fidelity spoken audio in 5 expressive voices (eve, ara, rex, sal, leo) with 20+ supported languages. Supports inline speech tags for laughter, whispers, and pauses.](https://developers.cloudflare.com/ai/models/xai/grok-tts/)

- Third-party
- +1

Compare

[![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)<h3>grok-voice</h3>

xAIwebsocket xAI's real-time voice conversation model with low-latency audio input and output streaming.](https://developers.cloudflare.com/ai/models/xai/grok-voice/)

- Third-party
- +1

Compare

[s<h3>apertus-v1.5-8b</h3>

swiss-aiText Generation Apertus 1.5 is an 8B parameter language model designed to advance the state of multilingual, multimodal, fully open, and transparent AI. The models support a wide range of languages, handle contexts of up to 262,144 tokens, and it uses only fully open training data whilst delivering performance comparable to other models of similar size. For access, please fill out this form: https://forms.gle/kgvmkr6ucHN3xNuH6](https://developers.cloudflare.com/ai/models/@cf/swiss-ai/apertus-v1.5-8b/)

- Cloudflare-hosted
- +2

Compare

[![Deepgram logo](https://developers.cloudflare.com/_astro/deepgram.BYzW8KfF.svg)<h3>aura-1</h3>

DeepgramText-to-Speech Aura is a context-aware text-to-speech (TTS) model that applies natural pacing, expressiveness, and fillers based on the context of the provided text. The quality of your text input directly impacts the naturalness of the audio output.](https://developers.cloudflare.com/ai/models/@cf/deepgram/aura-1/)

- Cloudflare-hosted
- +3

Compare

[![Deepgram logo](https://developers.cloudflare.com/_astro/deepgram.BYzW8KfF.svg)<h3>aura-2-en</h3>

DeepgramText-to-Speech Aura-2 is a context-aware text-to-speech (TTS) model that applies natural pacing, expressiveness, and fillers based on the context of the provided text. The quality of your text input directly impacts the naturalness of the audio output.](https://developers.cloudflare.com/ai/models/@cf/deepgram/aura-2-en/)

- Cloudflare-hosted
- +3

Compare

[![Deepgram logo](https://developers.cloudflare.com/_astro/deepgram.BYzW8KfF.svg)<h3>aura-2-es</h3>

DeepgramText-to-Speech Aura-2 is a context-aware text-to-speech (TTS) model that applies natural pacing, expressiveness, and fillers based on the context of the provided text. The quality of your text input directly impacts the naturalness of the audio output.](https://developers.cloudflare.com/ai/models/@cf/deepgram/aura-2-es/)

- Cloudflare-hosted
- +3

Compare

[![BAAI logo](https://developers.cloudflare.com/_astro/baai.BooZR_xF.svg)<h3>bge-base-en-v1.5</h3>

BAAIText Embeddings BAAI general embedding (Base) model that transforms any given text into a 768-dimensional vector](https://developers.cloudflare.com/ai/models/@cf/baai/bge-base-en-v1.5/)

- Cloudflare-hosted
- +1

Compare

[![BAAI logo](https://developers.cloudflare.com/_astro/baai.BooZR_xF.svg)<h3>bge-large-en-v1.5</h3>

BAAIText Embeddings BAAI general embedding (Large) model that transforms any given text into a 1024-dimensional vector](https://developers.cloudflare.com/ai/models/@cf/baai/bge-large-en-v1.5/)

- Cloudflare-hosted
- +1

Compare

[![BAAI logo](https://developers.cloudflare.com/_astro/baai.BooZR_xF.svg)<h3>bge-m3</h3>

BAAIText Embeddings Multi-Functionality, Multi-Linguality, and Multi-Granularity embeddings model.](https://developers.cloudflare.com/ai/models/@cf/baai/bge-m3/)

- Cloudflare-hosted

Compare

[![BAAI logo](https://developers.cloudflare.com/_astro/baai.BooZR_xF.svg)<h3>bge-reranker-base</h3>

BAAIText Classification Different from embedding model, reranker uses question and document as input and directly output similarity instead of embedding. You can get a relevance score by inputting query and passage to the reranker. And the score can be mapped to a float value in \[0,1\] by sigmoid function.](https://developers.cloudflare.com/ai/models/@cf/baai/bge-reranker-base/)

- Cloudflare-hosted

Compare

[![BAAI logo](https://developers.cloudflare.com/_astro/baai.BooZR_xF.svg)<h3>bge-small-en-v1.5</h3>

BAAIText Embeddings BAAI general embedding (Small) model that transforms any given text into a 384-dimensional vector](https://developers.cloudflare.com/ai/models/@cf/baai/bge-small-en-v1.5/)

- Cloudflare-hosted
- +1

Compare

[Pinned![Cloudflare logo](https://developers.cloudflare.com/_astro/cloudflare.DP8rkHys.svg)<h3>clef</h3>

CloudflareText Generation Clef is a 27B multimodal decision model that turns a state and a schema of typed questions into decisions. It reads the state as text, JSON, images, or video, and returns a probability for every allowed option of every question.](https://developers.cloudflare.com/ai/models/@cf/cloudflare/clef/)

- Cloudflare-hosted
- +1

Compare

[Pinned![Cloudflare logo](https://developers.cloudflare.com/_astro/cloudflare.DP8rkHys.svg)<h3>clef-flash</h3>

CloudflareText Generation Clef-flash is a fast 9B multimodal decision model that turns a state and a schema of typed questions into decisions. It reads the state as text, JSON, images, or video, and returns a probability for every allowed option of every question.](https://developers.cloudflare.com/ai/models/@cf/cloudflare/clef-flash/)

- Cloudflare-hosted
- +1

Compare

[![DeepSeek logo](https://developers.cloudflare.com/_astro/deepseek.CkzAgvN6.svg)<h3>deepseek-r1-distill-qwen-32b</h3>

DeepSeekText Generation DeepSeek-R1-Distill-Qwen-32B is a model distilled from DeepSeek-R1 based on Qwen2.5. It outperforms OpenAI-o1-mini across various benchmarks, achieving new state-of-the-art results for dense models.](https://developers.cloudflare.com/ai/models/@cf/deepseek-ai/deepseek-r1-distill-qwen-32b/)

- Cloudflare-hosted
- +1

Compare

[![DeepSeek logo](https://developers.cloudflare.com/_astro/deepseek.CkzAgvN6.svg)<h3>deepseek-v4-flash-0731</h3>

DeepSeekText Generation DeepSeek-V4-Flash-0731 is the official release of DeepSeek-V4-Flash, superseding the preview version, with substantially enhanced agentic capabilities.](https://developers.cloudflare.com/ai/models/@cf/deepseek-ai/deepseek-v4-flash-0731/)

- Cloudflare-hosted
- +3

Compare

[![DeepSeek logo](https://developers.cloudflare.com/_astro/deepseek.CkzAgvN6.svg)<h3>deepseek-v4-pro-0813</h3>

DeepSeekText Generation DeepSeek V4 Pro is a high-capability reasoning model from DeepSeek with a one million token context window, built for long-horizon agentic workflows and complex, multi-step problem-solving](https://developers.cloudflare.com/ai/models/@cf/deepseek-ai/deepseek-v4-pro-0813/)

- Cloudflare-hosted
- +2

Compare

[![HuggingFace logo](https://developers.cloudflare.com/_astro/huggingface.DMS-v5TA.svg)<h3>distilbert-sst-2-int8</h3>

HuggingFaceText Classification Distilled BERT model that was finetuned on SST-2 for sentiment classification](https://developers.cloudflare.com/ai/models/@cf/huggingface/distilbert-sst-2-int8/)

- Cloudflare-hosted

Compare

[l<h3>dreamshaper-8-lcm</h3>

lykonText-to-Image Stable Diffusion model that has been fine-tuned to be better at photorealism without sacrificing range.](https://developers.cloudflare.com/ai/models/@cf/lykon/dreamshaper-8-lcm/)

- Cloudflare-hosted

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>embeddinggemma-300m</h3>

BetaGoogleText Embeddings EmbeddingGemma is a 300M parameter, state-of-the-art for its size, open embedding model from Google, built from Gemma 3 (with T5Gemma initialization) and the same research and technology used to create Gemini models. EmbeddingGemma produces vector representations of text, making it well-suited for search and retrieval tasks, including classification, clustering, and semantic similarity search. This model was trained with data in 100+ spoken languages.](https://developers.cloudflare.com/ai/models/@cf/google/embeddinggemma-300m/)

- Cloudflare-hosted

Compare

[u<h3>eurollm-9b-it</h3>

utter-projectText Generation EuroLLM-9B is a 9B parameter model trained on 4 trillion tokens divided across the considered languages and several data sources: Web data, parallel data (en-xx and xx-en), and high-quality datasets. For access, please fill out this form: https://forms.gle/kgvmkr6ucHN3xNuH6](https://developers.cloudflare.com/ai/models/@cf/utter-project/eurollm-9b-it/)

- Cloudflare-hosted
- +1

Compare

[![Deepgram logo](https://developers.cloudflare.com/_astro/deepgram.BYzW8KfF.svg)<h3>flux</h3>

DeepgramAutomatic Speech Recognition Flux is the first conversational speech recognition model built specifically for voice agents.](https://developers.cloudflare.com/ai/models/@cf/deepgram/flux/)

- Cloudflare-hosted
- +2

Compare

[![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)<h3>flux-1-schnell</h3>

Black Forest LabsText-to-Image FLUX.1 \[schnell\] is a 12 billion parameter rectified flow transformer capable of generating images from text descriptions.](https://developers.cloudflare.com/ai/models/@cf/black-forest-labs/flux-1-schnell/)

- Cloudflare-hosted

Compare

[![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)<h3>flux-2-dev</h3>

Black Forest LabsText-to-Image FLUX.2 \[dev\] is an image model from Black Forest Labs where you can generate highly realistic and detailed images, with multi-reference support.](https://developers.cloudflare.com/ai/models/@cf/black-forest-labs/flux-2-dev/)

- Cloudflare-hosted
- +1

Compare

[![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)<h3>flux-2-klein-4b</h3>

Black Forest LabsText-to-Image FLUX.2 \[klein\] is an ultra-fast, distilled image model. It unifies image generation and editing in a single model, delivering state-of-the-art quality enabling interactive workflows, real-time previews, and latency-critical applications.](https://developers.cloudflare.com/ai/models/@cf/black-forest-labs/flux-2-klein-4b/)

- Cloudflare-hosted
- +1

Compare

[![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)<h3>flux-2-klein-9b</h3>

Black Forest LabsText-to-Image FLUX.2 \[klein\] 9B is a 9 billion parameter model that can generate images from text descriptions and supports multi-reference editing capabilities.](https://developers.cloudflare.com/ai/models/@cf/black-forest-labs/flux-2-klein-9b/)

- Cloudflare-hosted
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemma-2b-it-lora</h3>

BetaGoogleText Generation This is a Gemma-2B base model that Cloudflare dedicates for inference with LoRA adapters. Gemma is a family of lightweight, state-of-the-art open models from Google, built from the same research and technology used to create the Gemini models.](https://developers.cloudflare.com/ai/models/@cf/google/gemma-2b-it-lora/)

- Cloudflare-hosted
- +1

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemma-4-26b-a4b-it</h3>

GoogleText Generation Gemma 4 is Google's most intelligent family of open models, built from Gemini 3 research to maximize intelligence-per-parameter.](https://developers.cloudflare.com/ai/models/@cf/google/gemma-4-26b-a4b-it/)

- Cloudflare-hosted
- +4

Compare

[![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)<h3>gemma-7b-it-lora</h3>

BetaGoogleText Generation This is a Gemma-7B base model that Cloudflare dedicates for inference with LoRA adapters. Gemma is a family of lightweight, state-of-the-art open models from Google, built from the same research and technology used to create the Gemini models.](https://developers.cloudflare.com/ai/models/@cf/google/gemma-7b-it-lora/)

- Cloudflare-hosted
- +1

Compare

[a<h3>gemma-sea-lion-v4-27b-it</h3>

aisingaporeText Generation SEA-LION stands for Southeast Asian Languages In One Network, which is a collection of Large Language Models (LLMs) which have been pretrained and instruct-tuned for the Southeast Asia (SEA) region.](https://developers.cloudflare.com/ai/models/@cf/aisingapore/gemma-sea-lion-v4-27b-it/)

- Cloudflare-hosted

Compare

[![Zhipu AI logo](https://developers.cloudflare.com/_astro/zai.Dj2vcayE.svg)<h3>glm-4.7-flash</h3>

Zhipu AIText Generation GLM-4.7-Flash is a fast and efficient multilingual text generation model with a 131,072 token context window. Optimized for dialogue, instruction-following, and multi-turn tool calling across 100+ languages.](https://developers.cloudflare.com/ai/models/@cf/zai-org/glm-4.7-flash/)

- Cloudflare-hosted
- +2

Compare

[![Zhipu AI logo](https://developers.cloudflare.com/_astro/zai.Dj2vcayE.svg)<h3>glm-5.2</h3>

Zhipu AIText Generation Z.ai's flagship agentic coding model](https://developers.cloudflare.com/ai/models/@cf/zai-org/glm-5.2/)

- Cloudflare-hosted
- +2

Compare

[![Zhipu AI logo](https://developers.cloudflare.com/_astro/zai.Dj2vcayE.svg)<h3>glm-5.3</h3>

Zhipu AIText Generation GLM-5.3 is Z.ai's flagship agentic coding model, pairing a 1M-token context window with reasoning, function calling, and structured outputs to power multi-step, tool-driven development workflows.](https://developers.cloudflare.com/ai/models/@cf/zai-org/glm-5.3/)

- Cloudflare-hosted
- +2

Compare

[![Zhipu AI logo](https://developers.cloudflare.com/_astro/zai.Dj2vcayE.svg)<h3>glm-5.3-flash</h3>

Zhipu AIText Generation The first natively multimodal model in the GLM-5 series. With 320B total parameters and just 18B active parameters, it outperforms GLM-5.2 across benchmarks and real-world workloads at one-tenth the price, while approaching Claude Opus 4.8 on coding and agentic benchmarks.](https://developers.cloudflare.com/ai/models/@cf/zai-org/glm-5.3-flash/)

- Cloudflare-hosted
- +3

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-oss-120b</h3>

OpenAIText Generation OpenAI’s open-weight models designed for powerful reasoning, agentic tasks, and versatile developer use cases – gpt-oss-120b is for production, general purpose, high reasoning use-cases.](https://developers.cloudflare.com/ai/models/@cf/openai/gpt-oss-120b/)

- Cloudflare-hosted
- +3

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>gpt-oss-20b</h3>

OpenAIText Generation OpenAI’s open-weight models designed for powerful reasoning, agentic tasks, and versatile developer use cases – gpt-oss-20b is for lower latency, and local or specialized use-cases.](https://developers.cloudflare.com/ai/models/@cf/openai/gpt-oss-20b/)

- Cloudflare-hosted
- +3

Compare

[![IBM logo](https://developers.cloudflare.com/_astro/ibm.CYdLt4EI.svg)<h3>granite-4.0-h-micro</h3>

IBMText Generation Granite 4.0 instruct models deliver strong performance across benchmarks, achieving industry-leading results in key agentic tasks like instruction following and function calling. These efficiencies make the models well-suited for a wide range of use cases like retrieval-augmented generation (RAG), multi-agent workflows, and edge deployments.](https://developers.cloudflare.com/ai/models/@cf/ibm-granite/granite-4.0-h-micro/)

- Cloudflare-hosted
- +1

Compare

[a<h3>indictrans2-en-indic-1B</h3>

ai4bharatTranslation IndicTrans2 is the first open-source transformer-based multilingual NMT model that supports high-quality translations across all the 22 scheduled Indic languages](https://developers.cloudflare.com/ai/models/@cf/ai4bharat/indictrans2-en-indic-1B/)

- Cloudflare-hosted

Compare

[![Moonshot AI logo](https://developers.cloudflare.com/_astro/moonshotai.DjWMkXUS.svg)<h3>kimi-k2.6</h3>

Moonshot AIText Generation Kimi K2.6 is a frontier-scale open-source 1T parameter model with a 262.1k context window, multi-turn tool calling, vision inputs, and structured outputs for agentic workloads.](https://developers.cloudflare.com/ai/models/@cf/moonshotai/kimi-k2.6/)

- Cloudflare-hosted
- +4

Compare

[![Moonshot AI logo](https://developers.cloudflare.com/_astro/moonshotai.DjWMkXUS.svg)<h3>kimi-k2.7-code</h3>

Moonshot AIText Generation Kimi K2.7 is a frontier-scale open-source 1T parameter model with a 262.1k context window, multi-turn tool calling, vision inputs, and structured outputs for agentic workloads.](https://developers.cloudflare.com/ai/models/@cf/moonshotai/kimi-k2.7-code/)

- Cloudflare-hosted
- +3

Compare

[![Meta logo](https://developers.cloudflare.com/_astro/meta.CTzB_ysm.svg)<h3>llama-2-7b-chat-hf-lora</h3>

BetaMetaText Generation This is a Llama2 base model that Cloudflare dedicated for inference with LoRA adapters. Llama 2 is a collection of pretrained and fine-tuned generative text models ranging in scale from 7 billion to 70 billion parameters. This is the repository for the 7B fine-tuned model, optimized for dialogue use cases and converted for the Hugging Face Transformers format.](https://developers.cloudflare.com/ai/models/@cf/meta-llama/llama-2-7b-chat-hf-lora/)

- Cloudflare-hosted
- +1

Compare

[![Meta logo](https://developers.cloudflare.com/_astro/meta.CTzB_ysm.svg)<h3>llama-3.1-8b-instruct-fp8</h3>

MetaText Generation Llama 3.1 8B quantized to FP8 precision](https://developers.cloudflare.com/ai/models/@cf/meta/llama-3.1-8b-instruct-fp8/)

- Cloudflare-hosted

Compare

[![Meta logo](https://developers.cloudflare.com/_astro/meta.CTzB_ysm.svg)<h3>llama-3.2-11b-vision-instruct</h3>

MetaText Generation The Llama 3.2-Vision instruction-tuned models are optimized for visual recognition, image reasoning, captioning, and answering general questions about an image.](https://developers.cloudflare.com/ai/models/@cf/meta/llama-3.2-11b-vision-instruct/)

- Cloudflare-hosted
- +2

Compare

[![Meta logo](https://developers.cloudflare.com/_astro/meta.CTzB_ysm.svg)<h3>llama-3.2-1b-instruct</h3>

MetaText Generation The Llama 3.2 instruction-tuned text only models are optimized for multilingual dialogue use cases, including agentic retrieval and summarization tasks.](https://developers.cloudflare.com/ai/models/@cf/meta/llama-3.2-1b-instruct/)

- Cloudflare-hosted

Compare

[![Meta logo](https://developers.cloudflare.com/_astro/meta.CTzB_ysm.svg)<h3>llama-3.2-3b-instruct</h3>

MetaText Generation The Llama 3.2 instruction-tuned text only models are optimized for multilingual dialogue use cases, including agentic retrieval and summarization tasks.](https://developers.cloudflare.com/ai/models/@cf/meta/llama-3.2-3b-instruct/)

- Cloudflare-hosted
- +1

Compare

[![Meta logo](https://developers.cloudflare.com/_astro/meta.CTzB_ysm.svg)<h3>llama-3.3-70b-instruct-fp8-fast</h3>

MetaText Generation Llama 3.3 70B quantized to fp8 precision, optimized to be faster.](https://developers.cloudflare.com/ai/models/@cf/meta/llama-3.3-70b-instruct-fp8-fast/)

- Cloudflare-hosted
- +2

Compare

[![Meta logo](https://developers.cloudflare.com/_astro/meta.CTzB_ysm.svg)<h3>llama-4-scout-17b-16e-instruct</h3>

MetaText Generation Meta's Llama 4 Scout is a 17 billion parameter model with 16 experts that is natively multimodal. These models leverage a mixture-of-experts architecture to offer industry-leading performance in text and image understanding.](https://developers.cloudflare.com/ai/models/@cf/meta/llama-4-scout-17b-16e-instruct/)

- Cloudflare-hosted
- +3

Compare

[![Meta logo](https://developers.cloudflare.com/_astro/meta.CTzB_ysm.svg)<h3>llama-guard-3-8b</h3>

MetaText Generation Llama Guard 3 is a Llama-3.1-8B pretrained model, fine-tuned for content safety classification. Similar to previous versions, it can be used to classify content in both LLM inputs (prompt classification) and in LLM responses (response classification). It acts as an LLM – it generates text in its output that indicates whether a given prompt or response is safe or unsafe, and if unsafe, it also lists the content categories violated.](https://developers.cloudflare.com/ai/models/@cf/meta/llama-guard-3-8b/)

- Cloudflare-hosted
- +1

Compare

[l<h3>llava-1.5-7b-hf</h3>

Betallava-hfImage-to-Text LLaVA is an open-source chatbot trained by fine-tuning LLaMA/Vicuna on GPT-generated multimodal instruction-following data. It is an auto-regressive language model, based on the transformer architecture.](https://developers.cloudflare.com/ai/models/@cf/llava-hf/llava-1.5-7b-hf/)

- Cloudflare-hosted

Compare

[![Leonardo logo](https://developers.cloudflare.com/_astro/leonardo.JZysY-g3.svg)<h3>lucid-origin</h3>

LeonardoText-to-Image Lucid Origin from Leonardo.AI is their most adaptable and prompt-responsive model to date. Whether you're generating images with sharp graphic design, stunning full-HD renders, or highly specific creative direction, it adheres closely to your prompts, renders text with accuracy, and supports a wide array of visual styles and aesthetics – from stylized concept art to crisp product mockups.](https://developers.cloudflare.com/ai/models/@cf/leonardo/lucid-origin/)

- Cloudflare-hosted
- +1

Compare

[![Meta logo](https://developers.cloudflare.com/_astro/meta.CTzB_ysm.svg)<h3>m2m100-1.2b</h3>

MetaTranslation Multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many multilingual translation](https://developers.cloudflare.com/ai/models/@cf/meta/m2m100-1.2b/)

- Cloudflare-hosted
- +1

Compare

[![MyShell logo](https://developers.cloudflare.com/_astro/myshell.6ROagMV2.svg)<h3>melotts</h3>

MyShellText-to-Speech MeloTTS is a high-quality multi-lingual text-to-speech library by MyShell.ai.](https://developers.cloudflare.com/ai/models/@cf/myshell-ai/melotts/)

- Cloudflare-hosted

Compare

[![MistralAI logo](https://developers.cloudflare.com/_astro/mistralai.Bn9UMUMu.svg)<h3>mistral-7b-instruct-v0.2-lora</h3>

MistralAIText Generation The Mistral-7B-Instruct-v0.2 Large Language Model (LLM) is an instruct fine-tuned version of the Mistral-7B-v0.2.](https://developers.cloudflare.com/ai/models/@cf/mistral/mistral-7b-instruct-v0.2-lora/)

- Cloudflare-hosted
- +1

Compare

[![MistralAI logo](https://developers.cloudflare.com/_astro/mistralai.Bn9UMUMu.svg)<h3>mistral-small-3.1-24b-instruct</h3>

MistralAIText Generation Building upon Mistral Small 3 (2501), Mistral Small 3.1 (2503) adds state-of-the-art vision understanding and enhances long context capabilities up to 128k tokens without compromising text performance. With 24 billion parameters, this model achieves top-tier capabilities in both text and vision tasks.](https://developers.cloudflare.com/ai/models/@cf/mistralai/mistral-small-3.1-24b-instruct/)

- Cloudflare-hosted
- +1

Compare

[m<h3>moondream3.1-9B-A2B</h3>

moondreamImage-to-Text Moondream 3 is a fast, efficient 9B mixture-of-experts vision language model (2B active parameters) that delivers frontier-level visual reasoning for tasks like object detection, pointing, OCR, and structured output.](https://developers.cloudflare.com/ai/models/@cf/moondream/moondream3.1-9B-A2B/)

- Cloudflare-hosted
- +1

Compare

[![NVIDIA logo](https://developers.cloudflare.com/_astro/nvidia.DI1bb8hH.svg)<h3>nemotron-3-120b-a12b</h3>

NVIDIAText Generation NVIDIA Nemotron 3 Super is a hybrid MoE model with leading accuracy for multi-agent applications and specialized agentic AI systems.](https://developers.cloudflare.com/ai/models/@cf/nvidia/nemotron-3-120b-a12b/)

- Cloudflare-hosted
- +2

Compare

[![Deepgram logo](https://developers.cloudflare.com/_astro/deepgram.BYzW8KfF.svg)<h3>nova-3</h3>

DeepgramAutomatic Speech Recognition Transcribe audio using Deepgram’s speech-to-text model](https://developers.cloudflare.com/ai/models/@cf/deepgram/nova-3/)

- Cloudflare-hosted
- +3

Compare

[![Leonardo logo](https://developers.cloudflare.com/_astro/leonardo.JZysY-g3.svg)<h3>phoenix-1.0</h3>

LeonardoText-to-Image Phoenix 1.0 is a model by Leonardo.Ai that generates images with exceptional prompt adherence and coherent text.](https://developers.cloudflare.com/ai/models/@cf/leonardo/phoenix-1.0/)

- Cloudflare-hosted
- +1

Compare

[p<h3>plamo-embedding-1b</h3>

pfnetText Embeddings PLaMo-Embedding-1B is a Japanese text embedding model developed by Preferred Networks, Inc. It can convert Japanese text input into numerical vectors and can be used for a wide range of applications, including information retrieval, text classification, and clustering.](https://developers.cloudflare.com/ai/models/@cf/pfnet/plamo-embedding-1b/)

- Cloudflare-hosted

Compare

[![Qwen logo](https://developers.cloudflare.com/_astro/qwen.ByCZjtXU.svg)<h3>qwen2.5-coder-32b-instruct</h3>

QwenText Generation Qwen2.5-Coder is the latest series of Code-Specific Qwen large language models (formerly known as CodeQwen). As of now, Qwen2.5-Coder has covered six mainstream model sizes, 0.5, 1.5, 3, 7, 14, 32 billion parameters, to meet the needs of different developers. Qwen2.5-Coder brings the following improvements upon CodeQwen1.5:](https://developers.cloudflare.com/ai/models/@cf/qwen/qwen2.5-coder-32b-instruct/)

- Cloudflare-hosted
- +1

Compare

[![Qwen logo](https://developers.cloudflare.com/_astro/qwen.ByCZjtXU.svg)<h3>qwen3-30b-a3b-fp8</h3>

QwenText Generation Qwen3 is the latest generation of large language models in Qwen series, offering a comprehensive suite of dense and mixture-of-experts (MoE) models. Built upon extensive training, Qwen3 delivers groundbreaking advancements in reasoning, instruction-following, agent capabilities, and multilingual support.](https://developers.cloudflare.com/ai/models/@cf/qwen/qwen3-30b-a3b-fp8/)

- Cloudflare-hosted
- +3

Compare

[![Qwen logo](https://developers.cloudflare.com/_astro/qwen.ByCZjtXU.svg)<h3>qwen3-embedding-0.6b</h3>

QwenText Embeddings The Qwen3 Embedding model series is the latest proprietary model of the Qwen family, specifically designed for text embedding and ranking tasks.](https://developers.cloudflare.com/ai/models/@cf/qwen/qwen3-embedding-0.6b/)

- Cloudflare-hosted

Compare

[![Qwen logo](https://developers.cloudflare.com/_astro/qwen.ByCZjtXU.svg)<h3>qwen3.8-27b</h3>

QwenText Generation Qwen 3.8 27B is a 27-billion-parameter instruction-tuned language model from Alibaba's Qwen family, designed for vision, efficient general-purpose text generation and agentic workloads.](https://developers.cloudflare.com/ai/models/@cf/qwen/qwen3.8-27b/)

- Cloudflare-hosted
- +4

Compare

[![Qwen logo](https://developers.cloudflare.com/_astro/qwen.ByCZjtXU.svg)<h3>qwq-32b</h3>

QwenText Generation QwQ is the reasoning model of the Qwen series. Compared with conventional instruction-tuned models, QwQ, which is capable of thinking and reasoning, can achieve significantly enhanced performance in downstream tasks, especially hard problems. QwQ-32B is the medium-sized reasoning model, which is capable of achieving competitive performance against state-of-the-art reasoning models, e.g., DeepSeek-R1, o1-mini.](https://developers.cloudflare.com/ai/models/@cf/qwen/qwq-32b/)

- Cloudflare-hosted
- +2

Compare

[![Microsoft logo](https://developers.cloudflare.com/_astro/microsoft.LujcDJ--.svg)<h3>resnet-50</h3>

MicrosoftImage Classification 50 layers deep image classification CNN trained on more than 1M images from ImageNet](https://developers.cloudflare.com/ai/models/@cf/microsoft/resnet-50/)

- Cloudflare-hosted

Compare

[![Pipecat logo](https://developers.cloudflare.com/_astro/pipecat.B-PNBdef.svg)<h3>smart-turn-v2</h3>

PipecatDumb Pipe An open source, community-driven, native audio turn detection model in 2nd version](https://developers.cloudflare.com/ai/models/@cf/pipecat-ai/smart-turn-v2/)

- Cloudflare-hosted
- +2

Compare

[![RunwayML logo](https://developers.cloudflare.com/_astro/runway.Cq8Cjov4.svg)<h3>stable-diffusion-v1-5-inpainting</h3>

BetaRunwayMLText-to-Image Stable Diffusion Inpainting is a latent text-to-image diffusion model capable of generating photo-realistic images given any text input, with the extra capability of inpainting the pictures by using a mask.](https://developers.cloudflare.com/ai/models/@cf/runwayml/stable-diffusion-v1-5-inpainting/)

- Cloudflare-hosted

Compare

[![Stability.ai logo](https://developers.cloudflare.com/_astro/stabilityai.VsBx3CKv.svg)<h3>stable-diffusion-xl-base-1.0</h3>

BetaStability.aiText-to-Image Diffusion-based text-to-image generative model by Stability AI. Generates and modify images based on text prompts.](https://developers.cloudflare.com/ai/models/@cf/stabilityai/stable-diffusion-xl-base-1.0/)

- Cloudflare-hosted

Compare

[![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)<h3>stable-diffusion-xl-lightning</h3>

BetaByteDanceText-to-Image SDXL-Lightning is a lightning-fast text-to-image generation model. It can generate high-quality 1024px images in a few steps.](https://developers.cloudflare.com/ai/models/@cf/bytedance/stable-diffusion-xl-lightning/)

- Cloudflare-hosted

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>whisper</h3>

OpenAIAutomatic Speech Recognition Whisper is a general-purpose speech recognition model. It is trained on a large dataset of diverse audio and is also a multitasking model that can perform multilingual speech recognition, speech translation, and language identification.](https://developers.cloudflare.com/ai/models/@cf/openai/whisper/)

- Cloudflare-hosted

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>whisper-large-v3-turbo</h3>

OpenAIAutomatic Speech Recognition Whisper is a pre-trained model for automatic speech recognition (ASR) and speech translation.](https://developers.cloudflare.com/ai/models/@cf/openai/whisper-large-v3-turbo/)

- Cloudflare-hosted
- +1

Compare

[![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)<h3>whisper-tiny-en</h3>

BetaOpenAIAutomatic Speech Recognition Whisper is a pre-trained model for automatic speech recognition (ASR) and speech translation. Trained on 680k hours of labelled data, Whisper models demonstrate a strong ability to generalize to many datasets and domains without the need for fine-tuning. This is the English-only version of the Whisper Tiny model which was trained on the task of speech recognition.](https://developers.cloudflare.com/ai/models/@cf/openai/whisper-tiny-en/)

- Cloudflare-hosted

Compare

Compare models

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/ai/models/#page","headline":"Models","description":"Browse AI models available through Cloudflare, including hosted models on Workers AI and external providers via AI Gateway.","url":"https://developers.cloudflare.com/ai/models/","inLanguage":"en","image":"https://developers.cloudflare.com/ai/models/og.png?v=bb7974aa265b08c2","dateModified":"2026-08-12","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's HappyHorse 1.0 image-to-video model. Animates a reference image with an optional text prompt. Supports 720P and 1080P output with durations from 3 to 15 seconds.
title: HappyHorse 1.0 I2V
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# HappyHorse 1.0 I2V

Image-to-Video • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/hh1-i2v/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/hh1-i2v`

- Third-party
- Zero data retention

Alibaba's HappyHorse 1.0 image-to-video model. Animates a reference image with an optional text prompt. Supports 720P and 1080P output with durations from 3 to 15 seconds.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://modelstudio.console.alibabacloud.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.28</li><li>@720p (per second)$0.14</li><li>@1080p (per second)$0.28</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/hh1-i2v',
  {
    image:
      'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png',
    prompt: 'A gentle camera push-in on the scene with soft ambient lighting',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/hh1-i2v",
  "input": {
    "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png",
    "prompt": "A gentle camera push-in on the scene with soft ambient lighting"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/alibaba__hh1-i2v/simple-image-to-video.mp4"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**High Resolution** — Generate at 1080P with a longer duration</summary>



```ts
const response = await env.AI.run(
  'alibaba/hh1-i2v',
  {
    image:
      'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png',
    prompt: 'Subject begins rapping confidently to the beat, head bobbing',
    duration: 10,
    resolution: '1080P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/hh1-i2v",
  "input": {
    "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png",
    "prompt": "Subject begins rapping confidently to the beat, head bobbing",
    "duration": 10,
    "resolution": "1080P"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/alibaba__hh1-i2v/high-resolution.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Reproducible Output** — Use a fixed seed for reproducibility</summary>



```ts
const response = await env.AI.run(
  'alibaba/hh1-i2v',
  {
    image:
      'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png',
    prompt: 'Camera orbits slowly around the subject under streetlamp light',
    duration: 8,
    resolution: '720P',
    seed: 42,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/hh1-i2v",
  "input": {
    "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png",
    "prompt": "Camera orbits slowly around the subject under streetlamp light",
    "duration": 8,
    "resolution": "720P",
    "seed": 42
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/alibaba__hh1-i2v/reproducible-output.mp4"
  },
  "state": "Completed"
}
```

</details>

## Parameters

image

`string`requiredformat: uri

prompt

`string`

negative\_prompt

`string`

resolution

`string`enum: 720P, 1080P

duration

`integer`minimum: 3maximum: 15

seed

`integer`minimum: 0maximum: 2147483647

watermark

`boolean`

video

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/hh1-i2v/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/hh1-i2v/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/hh1-i2v/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/hh1-i2v/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/hh1-i2v/#page","headline":"HappyHorse 1.0 I2V","description":"Alibaba's HappyHorse 1.0 image-to-video model. Animates a reference image with an optional text prompt. Supports 720P and 1080P output with durations from 3 to 15 seconds.","url":"https://developers.cloudflare.com/ai/models/alibaba/hh1-i2v/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's HappyHorse 1.0 text-to-video model. Generates videos from a text prompt with configurable resolution, aspect ratio, and duration (3-15s).
title: HappyHorse 1.0 T2V
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# HappyHorse 1.0 T2V

Text-to-Video • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/hh1-t2v/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/hh1-t2v`

- Third-party
- Zero data retention

Alibaba's HappyHorse 1.0 text-to-video model. Generates videos from a text prompt with configurable resolution, aspect ratio, and duration (3-15s).

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://modelstudio.console.alibabacloud.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.28</li><li>@720p (per second)$0.14</li><li>@1080p (per second)$0.28</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/hh1-t2v',
  { prompt: 'A little girl walking on the road' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/hh1-t2v",
  "input": {
    "prompt": "A little girl walking on the road"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/alibaba__hh1-t2v/simple-text-to-video.mp4"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Vertical 1080P** — Vertical 9:16 output at 1080P for social media</summary>



```ts
const response = await env.AI.run(
  'alibaba/hh1-t2v',
  {
    prompt: 'A dog running through a field of tall grass, slow motion, golden hour',
    duration: 6,
    ratio: '9:16',
    resolution: '1080P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/hh1-t2v",
  "input": {
    "prompt": "A dog running through a field of tall grass, slow motion, golden hour",
    "duration": 6,
    "ratio": "9:16",
    "resolution": "1080P"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/alibaba__hh1-t2v/vertical-1080p.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Reproducible Output** — Use a fixed seed for reproducibility</summary>



```ts
const response = await env.AI.run(
  'alibaba/hh1-t2v',
  {
    prompt: 'Clouds drifting across a mountain range, time-lapse style',
    duration: 5,
    ratio: '16:9',
    resolution: '720P',
    seed: 42,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/hh1-t2v",
  "input": {
    "prompt": "Clouds drifting across a mountain range, time-lapse style",
    "duration": 5,
    "ratio": "16:9",
    "resolution": "720P",
    "seed": 42
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/alibaba__hh1-t2v/reproducible-output.mp4"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`requiredminLength: 1maxLength: 2500

resolution

`string`enum: 720P, 1080P

ratio

`string`enum: 16:9, 9:16, 1:1, 4:3, 3:4

duration

`integer`minimum: 3maximum: 15

seed

`integer`minimum: 0maximum: 2147483647

watermark

`boolean`

video

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/hh1-t2v/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/hh1-t2v/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/hh1-t2v/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/hh1-t2v/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/hh1-t2v/#page","headline":"HappyHorse 1.0 T2V","description":"Alibaba's HappyHorse 1.0 text-to-video model. Generates videos from a text prompt with configurable resolution, aspect ratio, and duration (3-15s).","url":"https://developers.cloudflare.com/ai/models/alibaba/hh1-t2v/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's HappyHorse 1.1 image-to-video model. Animates a reference image with an optional text prompt, with smoother motion, natural skin textures, and improved close-up quality over 1.0. Supports 720P and 1080P output with durations from 3 to 15 seconds.
title: HappyHorse 1.1 I2V
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# HappyHorse 1.1 I2V

Image-to-Video • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-i2v/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/hh1.1-i2v`

- Third-party

Alibaba's HappyHorse 1.1 image-to-video model. Animates a reference image with an optional text prompt, with smoother motion, natural skin textures, and improved close-up quality over 1.0. Supports 720P and 1080P output with durations from 3 to 15 seconds.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://modelstudio.console.alibabacloud.com/) |
| Pricing | <ul><li>Default (per second)$0.18</li><li>@720p (per second)$0.14</li><li>@1080p (per second)$0.18</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/hh1.1-i2v',
  {
    image:
      'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png',
    prompt: 'A gentle camera push-in on the scene with soft ambient lighting',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/hh1.1-i2v",
  "input": {
    "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png",
    "prompt": "A gentle camera push-in on the scene with soft ambient lighting"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/alibaba/hh1.1-i2v/simple-image-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

image

`string`requiredformat: uri

prompt

`string`

negative\_prompt

`string`

resolution

`string`enum: 720P, 1080P

duration

`integer`minimum: 3maximum: 15

seed

`integer`minimum: 0maximum: 2147483647

watermark

`boolean`

video

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-i2v/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-i2v/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-i2v/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-i2v/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/hh1.1-i2v/#page","headline":"HappyHorse 1.1 I2V","description":"Alibaba's HappyHorse 1.1 image-to-video model. Animates a reference image with an optional text prompt, with smoother motion, natural skin textures, and improved close-up quality over 1.0. Supports 720P and 1080P output with durations from 3 to 15 seconds.","url":"https://developers.cloudflare.com/ai/models/alibaba/hh1.1-i2v/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's HappyHorse 1.1 reference-to-video model. Takes 1-9 reference images (characters and scenes) and a prompt that choreographs them into a single video, keeping each subject's identity consistent. Supports 720P and 1080P output with durations from 3 to 15 seconds.
title: HappyHorse 1.1 R2V
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# HappyHorse 1.1 R2V

Image-to-Video • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-r2v/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/hh1.1-r2v`

- Third-party

Alibaba's HappyHorse 1.1 reference-to-video model. Takes 1-9 reference images (characters and scenes) and a prompt that choreographs them into a single video, keeping each subject's identity consistent. Supports 720P and 1080P output with durations from 3 to 15 seconds.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://modelstudio.console.alibabacloud.com/) |
| Pricing | <ul><li>Default (per second)$0.18</li><li>@720p (per second)$0.14</li><li>@1080p (per second)$0.18</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/hh1.1-r2v',
  {
    prompt:
      'The person in image 1 walks through the futuristic city in image 2 and meets the person in image 3.',
    images: [
      'https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-5-lite/portrait-photo-0.jpeg',
      'https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-2/futuristic-city.png',
      'https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-2/high-resolution-portrait.jpg',
    ],
    duration: 8,
    ratio: '16:9',
    resolution: '1080P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/hh1.1-r2v",
  "input": {
    "prompt": "The person in image 1 walks through the futuristic city in image 2 and meets the person in image 3.",
    "images": [
      "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-5-lite/portrait-photo-0.jpeg",
      "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-2/futuristic-city.png",
      "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-2/high-resolution-portrait.jpg"
    ],
    "duration": 8,
    "ratio": "16:9",
    "resolution": "1080P"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/alibaba/hh1.1-r2v/multi-image-reference.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

prompt

`string`requiredminLength: 1maxLength: 2500

▶images\[]

`array`requiredminItems: 1maxItems: 9format: uri

resolution

`string`enum: 720P, 1080P

ratio

`string`enum: 16:9, 9:16, 3:4, 4:3, 1:1, 21:9, 9:21, 5:4, 4:5

duration

`integer`minimum: 3maximum: 15

seed

`integer`minimum: 0maximum: 2147483647

watermark

`boolean`

video

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-r2v/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-r2v/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-r2v/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-r2v/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/hh1.1-r2v/#page","headline":"HappyHorse 1.1 R2V","description":"Alibaba's HappyHorse 1.1 reference-to-video model. Takes 1-9 reference images (characters and scenes) and a prompt that choreographs them into a single video, keeping each subject's identity consistent. Supports 720P and 1080P output with durations from 3 to 15 seconds.","url":"https://developers.cloudflare.com/ai/models/alibaba/hh1.1-r2v/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's HappyHorse 1.1 text-to-video model. Generates videos from a text prompt with stronger dynamic expressiveness, better visual quality, and improved instruction following over 1.0. Configurable resolution, aspect ratio, and duration (3-15s).
title: HappyHorse 1.1 T2V
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# HappyHorse 1.1 T2V

Text-to-Video • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-t2v/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/hh1.1-t2v`

- Third-party

Alibaba's HappyHorse 1.1 text-to-video model. Generates videos from a text prompt with stronger dynamic expressiveness, better visual quality, and improved instruction following over 1.0. Configurable resolution, aspect ratio, and duration (3-15s).

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://modelstudio.console.alibabacloud.com/) |
| Pricing | <ul><li>Default (per second)$0.18</li><li>@720p (per second)$0.14</li><li>@1080p (per second)$0.18</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/hh1.1-t2v',
  { prompt: 'A little girl walking on the road' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/hh1.1-t2v",
  "input": {
    "prompt": "A little girl walking on the road"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/alibaba/hh1.1-t2v/simple-text-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

prompt

`string`requiredminLength: 1maxLength: 2500

resolution

`string`enum: 720P, 1080P

ratio

`string`enum: 16:9, 9:16, 1:1, 4:3, 3:4

duration

`integer`minimum: 3maximum: 15

seed

`integer`minimum: 0maximum: 2147483647

watermark

`boolean`

video

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-t2v/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-t2v/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-t2v/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/hh1.1-t2v/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/hh1.1-t2v/#page","headline":"HappyHorse 1.1 T2V","description":"Alibaba's HappyHorse 1.1 text-to-video model. Generates videos from a text prompt with stronger dynamic expressiveness, better visual quality, and improved instruction following over 1.0. Configurable resolution, aspect ratio, and duration (3-15s).","url":"https://developers.cloudflare.com/ai/models/alibaba/hh1.1-t2v/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's Qwen Image 3.0 Pro generates images from text prompts with a focus on complex layout generation, small-text precision, and multilingual font rendering. Supports up to 6 image variants per call, negative prompts, seed control, and optional prompt rewriting.
title: Qwen Image 3.0 Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# Qwen Image 3.0 Pro

Text-to-Image • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/qwen-image-3.0-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/qwen-image-3.0-pro`

- Third-party

Alibaba's Qwen Image 3.0 Pro generates images from text prompts with a focus on complex layout generation, small-text precision, and multilingual font rendering. Supports up to 6 image variants per call, negative prompts, seed control, and optional prompt rewriting.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://www.alibabacloud.com/en/solutions/generative-ai/qwen) |
| Pricing | <ul><li>Per image$0.04</li><li>output size 1k$0.04</li><li>output size 2k$0.07</li><li>Default (per second)$0.04</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/qwen-image-3.0-pro',
  { prompt: 'A golden retriever puppy playing in autumn leaves' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen-image-3.0-pro",
  "input": {
    "prompt": "A golden retriever puppy playing in autumn leaves"
  }
}'
```

![Simple Generation](https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/simple-generation.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/simple-generation.png"
    ]
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Multiple Variants** — Generate several image variants from a single call</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen-image-3.0-pro',
  { prompt: 'A minimalist logo for a coffee roastery, line art style, single color', n: 4 },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen-image-3.0-pro",
  "input": {
    "prompt": "A minimalist logo for a coffee roastery, line art style, single color",
    "n": 4
  }
}'
```

![Multiple Variants](https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/multiple-variants-0.png)![Multiple Variants](https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/multiple-variants-1.png)![Multiple Variants](https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/multiple-variants-2.png)![Multiple Variants](https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/multiple-variants-3.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/multiple-variants-0.png",
      "https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/multiple-variants-1.png",
      "https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/multiple-variants-2.png",
      "https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/multiple-variants-3.png"
    ]
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Negative Prompt** — Guide generation away from unwanted elements</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen-image-3.0-pro',
  {
    prompt: 'A detailed oil painting portrait of a Renaissance nobleman with intricate lace collar',
    negative_prompt: 'modern clothing, photograph, blurry, low quality',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen-image-3.0-pro",
  "input": {
    "prompt": "A detailed oil painting portrait of a Renaissance nobleman with intricate lace collar",
    "negative_prompt": "modern clothing, photograph, blurry, low quality"
  }
}'
```

![Negative Prompt](https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/negative-prompt.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://examples.aig.cloudflare.com/alibaba/qwen-image-3.0-pro/negative-prompt.png"
    ]
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`requireddefault: 1024x1024pattern: ^\\d+x\\d+$

negative\_prompt

`string`maxLength: 500

n

`integer`minimum: 1maximum: 6

seed

`integer`minimum: 0maximum: 2147483647

watermark

`boolean`

prompt\_extend

`boolean`

prompt\_extend\_mode

`string`enum: direct, agent

▶images\[]

`array`minItems: 1format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen-image-3.0-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen-image-3.0-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen-image-3.0-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen-image-3.0-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/qwen-image-3.0-pro/#page","headline":"Qwen Image 3.0 Pro","description":"Alibaba's Qwen Image 3.0 Pro generates images from text prompts with a focus on complex layout generation, small-text precision, and multilingual font rendering. Supports up to 6 image variants per call, negative prompts, seed control, and optional prompt rewriting.","url":"https://developers.cloudflare.com/ai/models/alibaba/qwen-image-3.0-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's Qwen 3 Max is a large language model with strong coding, reasoning, and multilingual capabilities, served via DashScope's OpenAI-compatible endpoint.
title: Qwen 3 Max
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# Qwen 3 Max

Text Generation • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/qwen3-max/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/qwen3-max`

- Third-party
- Zero data retention

Alibaba's Qwen 3 Max is a large language model with strong coding, reasoning, and multilingual capabilities, served via DashScope's OpenAI-compatible endpoint.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://www.alibabacloud.com/en/solutions/generative-ai/qwen) |
| Zero data retention | Yes |
| Request formats | Chat Completions, Responses |
| Pricing | <ul><li>Input (per 1M tokens)$1.20</li><li>Output (per 1M tokens)$6.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/qwen3-max',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3-max",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The three laws of thermodynamics are fundamental principles that describe the behavior of energy and entropy in physical systems:

1. **Zeroth Law of Thermodynamics**:  
   *If two systems are each in thermal equilibrium with a third system, then they are in thermal equilibrium with each other.*  
   This law establishes the concept of temperature and justifies the use of thermometers.

2. **First Law of Thermodynamics** (Law of Energy Conservation):  
   *Energy cannot be created or destroyed in an isolated system; it can only change forms.*  
   Mathematically, this 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.

3. **Second Law of Thermodynamics**:  
   *The total entropy of an isolated system can never decrease over time; it either increases or remains constant in ideal reversible processes.*  
   This law introduces the concept of irreversibility and explains why certain processes occur spontaneously in one direction (e.g., heat flows from hot to cold).

There is also a **Third Law of Thermodynamics**, which is sometimes included as the fourth in historical contexts but is now standardly recognized as the third:

4. **Third Law of Thermodynamics**:  
   *As the temperature of a system approaches absolute zero, the entropy of the system approaches a constant minimum value.*  
   In practical terms, it implies that absolute zero (0 K) cannot be reached in a finite number of steps.

So, while commonly referred to as “three laws,” modern physics includes **four**—with the Zeroth Law added later for logical completeness, even though it was formulated after the first three.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "The three laws of thermodynamics are fundamental principles that describe the behavior of energy and entropy in physical systems:\n\n1. **Zeroth Law of Thermodynamics**:  \n   *If two systems are each in thermal equilibrium with a third system, then they are in thermal equilibrium with each other.*  \n   This law establishes the concept of temperature and justifies the use of thermometers.\n\n2. **First Law of Thermodynamics** (Law of Energy Conservation):  \n   *Energy cannot be created or destroyed in an isolated system; it can only change forms.*  \n   Mathematically, this is often expressed as:  \n   \\[\n   \\Delta U = Q - W\n   \\]  \n   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.\n\n3. **Second Law of Thermodynamics**:  \n   *The total entropy of an isolated system can never decrease over time; it either increases or remains constant in ideal reversible processes.*  \n   This law introduces the concept of irreversibility and explains why certain processes occur spontaneously in one direction (e.g., heat flows from hot to cold).\n\nThere is also a **Third Law of Thermodynamics**, which is sometimes included as the fourth in historical contexts but is now standardly recognized as the third:\n\n4. **Third Law of Thermodynamics**:  \n   *As the temperature of a system approaches absolute zero, the entropy of the system approaches a constant minimum value.*  \n   In practical terms, it implies that absolute zero (0 K) cannot be reached in a finite number of steps.\n\nSo, while commonly referred to as “three laws,” modern physics includes **four**—with the Zeroth Law added later for logical completeness, even though it was formulated after the first three.",
        "role": "assistant"
      }
    }
  ],
  "created": 1776471062,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-1cc68967-fae9-9f2f-aa72-ec0674038c0a",
  "model": "qwen3-max",
  "object": "chat.completion",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 375,
    "prompt_tokens": 17,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "total_tokens": 392
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3-max',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3-max",
  "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"
    }
  ]
}'
```

````
To read a JSON file in Python, you can use the built-in `json` module. Here's the basic approach:

## Basic Example

```python
import json

# Read JSON file
with open('data.json', 'r') as file:
    data = json.load(file)

# Now you can work with your data
print(data)
```

## Step-by-step breakdown:

1. **Import the json module**: `import json`
2. **Open the file**: Use `open()` with mode `'r'` (read mode)
3. **Parse the JSON**: Use `json.load()` to parse the file content into Python objects
4. **Use context manager**: The `with` statement automatically closes the file when done

## Common Data Types After Loading

JSON data gets converted to these Python types:
- JSON object → Python dictionary (`dict`)
- JSON array → Python list (`list`)
- JSON string → Python string (`str`)
- JSON number → Python int or float
- JSON boolean → Python `True` or `False`
- JSON null → Python `None`

## Example with Error Handling

```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
    print("Data loaded successfully!")
    print(data)
except FileNotFoundError:
    print("File not found!")
except json.JSONDecodeError:
    print("Invalid JSON format!")
```

## Reading JSON from a String

If you have JSON as a string (not a file), use `json.loads()` instead:

```python
import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)
print(data)  # {'name': 'Alice', 'age': 30}
```

## Specifying Encoding (if needed)

For files with non-UTF-8 encoding:

```python
with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
```

The `json.load()` function handles UTF-8 by default, so you usually don't need to specify encoding unless you're dealing with a different character encoding.
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "To read a JSON file in Python, you can use the built-in `json` module. Here's the basic approach:\n\n## Basic Example\n\n```python\nimport json\n\n# Read JSON file\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\n# Now you can work with your data\nprint(data)\n```\n\n## Step-by-step breakdown:\n\n1. **Import the json module**: `import json`\n2. **Open the file**: Use `open()` with mode `'r'` (read mode)\n3. **Parse the JSON**: Use `json.load()` to parse the file content into Python objects\n4. **Use context manager**: The `with` statement automatically closes the file when done\n\n## Common Data Types After Loading\n\nJSON data gets converted to these Python types:\n- JSON object → Python dictionary (`dict`)\n- JSON array → Python list (`list`)\n- JSON string → Python string (`str`)\n- JSON number → Python int or float\n- JSON boolean → Python `True` or `False`\n- JSON null → Python `None`\n\n## Example with Error Handling\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r') as file:\n        data = json.load(file)\n    print(\"Data loaded successfully!\")\n    print(data)\nexcept FileNotFoundError:\n    print(\"File not found!\")\nexcept json.JSONDecodeError:\n    print(\"Invalid JSON format!\")\n```\n\n## Reading JSON from a String\n\nIf you have JSON as a string (not a file), use `json.loads()` instead:\n\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)\nprint(data)  # {'name': 'Alice', 'age': 30}\n```\n\n## Specifying Encoding (if needed)\n\nFor files with non-UTF-8 encoding:\n\n```python\nwith open('data.json', 'r', encoding='utf-8') as file:\n    data = json.load(file)\n```\n\nThe `json.load()` function handles UTF-8 by default, so you usually don't need to specify encoding unless you're dealing with a different character encoding.",
        "role": "assistant"
      }
    }
  ],
  "created": 1776471064,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-ba93d05e-b778-9fe4-97f6-a2b16726e379",
  "model": "qwen3-max",
  "object": "chat.completion",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 449,
    "prompt_tokens": 33,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "total_tokens": 482
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3-max',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3-max",
  "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"
    }
  ]
}'
```

```
Great! The classic route from San Francisco to Los Angeles along the California coast—especially **Highway 1 (Pacific Coast Highway)**—is one of the most scenic drives in the world. While it takes longer than the inland I-5 freeway (about 8–10 hours without stops), it’s absolutely worth it for the views and experiences. Here are some top places to stop, roughly ordered from north to south:

### 🌉 **Half Moon Bay**  
- Just 30 miles south of SF  
- Charming coastal town with beaches, tide pools, and great seafood  
- Stop at **Pillar Point Harbor** or walk the **Coastal Trail**

### 🏞️ **Santa Cruz**  
- Famous for its beach boardwalk (oldest in California!), surfing, and laid-back vibe  
- Visit the **Santa Cruz Beach Boardwalk** or explore **Natural Bridges State Beach**

### 🐬 **Monterey & Carmel-by-the-Sea**  
- **Monterey**: Don’t miss the world-class **Monterey Bay Aquarium** and Cannery Row  
- **Carmel**: Quaint village with art galleries, fairytale cottages, and **Carmel Beach**  
- Optional detour: **17-Mile Drive** through Pebble Beach (toll road with stunning ocean views)

### 🌲 **Big Sur**  
- The crown jewel of the PCH! Dramatic cliffs, redwoods, and ocean vistas  
- Must-stops:  
  - **Bixby Creek Bridge** (iconic photo spot)  
  - **McWay Falls** at Julia Pfeiffer Burns State Park (80-ft waterfall onto a beach!)  
  - **Nepenthe** restaurant for lunch with panoramic views  

> ⚠️ Note: Check road conditions before heading through Big Sur—landslides occasionally close Highway 1.

### 🍷 **San Simeon**  
- Home of **Hearst Castle**, the opulent estate of newspaper magnate William Randolph Hearst  
- Also great for spotting **elephant seals** at the **Piedras Blancas Rookery** just north of town

### 🏖️ **Cambria & Morro Bay**  
- **Cambria**: Cozy seaside village with unique shops and forest-meets-ocean scenery  
- **Morro Bay**: Known for **Morro Rock**, kayaking, and fresh oysters

### 🌴 **San Luis Obispo (SLO)**  
- A relaxed college town with a historic mission, farmers’ market (Thursday nights!), and great food  
- Nearby: **Bubblegum Alley** and **Madonna Inn** (quirky, Instagrammable hotel)

### 🏄 **Pismo Beach**  
- Classic Central Coast surf town with dunes and a long pier  
- Try clam chowder—it’s the “Clam Capital of the World”!

### 🌺 **Santa Barbara**  
- “The American Riviera” with Spanish architecture, palm-lined streets, and wine tasting  
- Stroll **Stearns Wharf**, visit the **Mission Santa Barbara**, or relax on **East Beach**

### 🏙️ **Final Stretch to Los Angeles**  
- From Santa Barbara, you can stay on Highway 1 through **Malibu** (stop at **El Matador Beach** or **Point Dume**)  
- Or hop on US-101 for a quicker arrival into LA

---

### Tips:
- **Allow 2–3 days** if you want to enjoy the stops without rushing  
- **Book lodging in advance**, especially in Big Sur, Carmel, or Santa Barbara  
- **Fill your gas tank**—some stretches (like Big Sur) have limited services  
- **Pack layers**—coastal weather changes fast, even in summer!

Would you like help planning an itinerary based on how many days you have?
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "Great! The classic route from San Francisco to Los Angeles along the California coast—especially **Highway 1 (Pacific Coast Highway)**—is one of the most scenic drives in the world. While it takes longer than the inland I-5 freeway (about 8–10 hours without stops), it’s absolutely worth it for the views and experiences. Here are some top places to stop, roughly ordered from north to south:\n\n### 🌉 **Half Moon Bay**  \n- Just 30 miles south of SF  \n- Charming coastal town with beaches, tide pools, and great seafood  \n- Stop at **Pillar Point Harbor** or walk the **Coastal Trail**\n\n### 🏞️ **Santa Cruz**  \n- Famous for its beach boardwalk (oldest in California!), surfing, and laid-back vibe  \n- Visit the **Santa Cruz Beach Boardwalk** or explore **Natural Bridges State Beach**\n\n### 🐬 **Monterey & Carmel-by-the-Sea**  \n- **Monterey**: Don’t miss the world-class **Monterey Bay Aquarium** and Cannery Row  \n- **Carmel**: Quaint village with art galleries, fairytale cottages, and **Carmel Beach**  \n- Optional detour: **17-Mile Drive** through Pebble Beach (toll road with stunning ocean views)\n\n### 🌲 **Big Sur**  \n- The crown jewel of the PCH! Dramatic cliffs, redwoods, and ocean vistas  \n- Must-stops:  \n  - **Bixby Creek Bridge** (iconic photo spot)  \n  - **McWay Falls** at Julia Pfeiffer Burns State Park (80-ft waterfall onto a beach!)  \n  - **Nepenthe** restaurant for lunch with panoramic views  \n\n> ⚠️ Note: Check road conditions before heading through Big Sur—landslides occasionally close Highway 1.\n\n### 🍷 **San Simeon**  \n- Home of **Hearst Castle**, the opulent estate of newspaper magnate William Randolph Hearst  \n- Also great for spotting **elephant seals** at the **Piedras Blancas Rookery** just north of town\n\n### 🏖️ **Cambria & Morro Bay**  \n- **Cambria**: Cozy seaside village with unique shops and forest-meets-ocean scenery  \n- **Morro Bay**: Known for **Morro Rock**, kayaking, and fresh oysters\n\n### 🌴 **San Luis Obispo (SLO)**  \n- A relaxed college town with a historic mission, farmers’ market (Thursday nights!), and great food  \n- Nearby: **Bubblegum Alley** and **Madonna Inn** (quirky, Instagrammable hotel)\n\n### 🏄 **Pismo Beach**  \n- Classic Central Coast surf town with dunes and a long pier  \n- Try clam chowder—it’s the “Clam Capital of the World”!\n\n### 🌺 **Santa Barbara**  \n- “The American Riviera” with Spanish architecture, palm-lined streets, and wine tasting  \n- Stroll **Stearns Wharf**, visit the **Mission Santa Barbara**, or relax on **East Beach**\n\n### 🏙️ **Final Stretch to Los Angeles**  \n- From Santa Barbara, you can stay on Highway 1 through **Malibu** (stop at **El Matador Beach** or **Point Dume**)  \n- Or hop on US-101 for a quicker arrival into LA\n\n---\n\n### Tips:\n- **Allow 2–3 days** if you want to enjoy the stops without rushing  \n- **Book lodging in advance**, especially in Big Sur, Carmel, or Santa Barbara  \n- **Fill your gas tank**—some stretches (like Big Sur) have limited services  \n- **Pack layers**—coastal weather changes fast, even in summer!\n\nWould you like help planning an itinerary based on how many days you have?",
        "role": "assistant"
      }
    }
  ],
  "created": 1776471088,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-8ebaff89-c5a7-9010-b5a4-84e5f446841a",
  "model": "qwen3-max",
  "object": "chat.completion",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 821,
    "prompt_tokens": 81,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "total_tokens": 902
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3-max',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3-max",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
Rain slicked the cobblestones of Blackwater Lane, turning the gaslight into smears of gold on wet stone. Detective Aris Thorne hunched deeper into his trench coat, the damp wool smell a familiar companion to the city’s usual perfume of coal smoke and despair. Another dead end—literally and figuratively—in the case of the vanished heiress, Elara Vance. The alley reeked of stale beer and something sharper, metallic.

Then he saw it.

Nestled in a puddle near a overflowing gutter, half-submerged but gleaming with unnatural clarity, was a single playing card. Not just any card. The Queen of Hearts. But this one was wrong. Horribly wrong.

The queen’s face wasn’t printed ink. It was *stitched*. Delicate, almost surgical sutures traced her features—a crimson thread for lips, fine black silk for eyes, silver wire forming the curve of a regal brow. And where the heart symbol should be, centered on her chest, was a tiny, perfect keyhole, wrought from what looked like tarnished silver. Rainwater pooled around it, but the stitches remained unnervingly dry, as if repelling the downpour.

Thorne crouched, ignoring the ache in his knees and the cold seeping through his trousers. He didn’t touch it. Not yet. This wasn’t evidence left by accident; it was a message. A challenge. And the meticulous, chilling craftsmanship whispered of a mind far more dangerous than the common cutpurse or jealous rival he’d been chasing. The rain drummed a frantic rhythm on his hat, but the only sound he truly heard was the sudden, icy thrum of his own pulse. The game, it seemed, had just changed its rules.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "Rain slicked the cobblestones of Blackwater Lane, turning the gaslight into smears of gold on wet stone. Detective Aris Thorne hunched deeper into his trench coat, the damp wool smell a familiar companion to the city’s usual perfume of coal smoke and despair. Another dead end—literally and figuratively—in the case of the vanished heiress, Elara Vance. The alley reeked of stale beer and something sharper, metallic.\n\nThen he saw it.\n\nNestled in a puddle near a overflowing gutter, half-submerged but gleaming with unnatural clarity, was a single playing card. Not just any card. The Queen of Hearts. But this one was wrong. Horribly wrong.\n\nThe queen’s face wasn’t printed ink. It was *stitched*. Delicate, almost surgical sutures traced her features—a crimson thread for lips, fine black silk for eyes, silver wire forming the curve of a regal brow. And where the heart symbol should be, centered on her chest, was a tiny, perfect keyhole, wrought from what looked like tarnished silver. Rainwater pooled around it, but the stitches remained unnervingly dry, as if repelling the downpour.\n\nThorne crouched, ignoring the ache in his knees and the cold seeping through his trousers. He didn’t touch it. Not yet. This wasn’t evidence left by accident; it was a message. A challenge. And the meticulous, chilling craftsmanship whispered of a mind far more dangerous than the common cutpurse or jealous rival he’d been chasing. The rain drummed a frantic rhythm on his hat, but the only sound he truly heard was the sudden, icy thrum of his own pulse. The game, it seemed, had just changed its rules.",
        "role": "assistant"
      }
    }
  ],
  "created": 1776471079,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-7bdc3457-d069-92c5-9ea0-0f1c3987d776",
  "model": "qwen3-max",
  "object": "chat.completion",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 362,
    "prompt_tokens": 21,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "total_tokens": 383
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3-max',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3-max",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
**Recursion** is a programming technique where a function calls itself to solve a problem by breaking it down into smaller, similar subproblems.

## Key Components of Recursion

1. **Base case**: A condition that stops the recursion (prevents infinite loops)
2. **Recursive case**: The function calls itself with modified arguments that move toward the base case

## Simple Example: Calculating Factorial

The factorial of a number `n` (written as `n!`) is the product of all positive integers from 1 to n.
- 5! = 5 × 4 × 3 × 2 × 1 = 120
- By definition: 0! = 1

### Recursive Implementation

```python
def factorial(n):
    # Base case: stop when n is 0 or 1
    if n <= 1:
        return 1
    
    # Recursive case: n! = n × (n-1)!
    return n * factorial(n - 1)

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

### How it works step by step:

```
factorial(5)
├── 5 * factorial(4)
    ├── 4 * factorial(3)
        ├── 3 * factorial(2)
            ├── 2 * factorial(1)
                └── returns 1 (base case)
            └── returns 2 * 1 = 2
        └── returns 3 * 2 = 6
    └── returns 4 * 6 = 24
└── returns 5 * 24 = 120
```

## Why Recursion Works

Each recursive call works on a **smaller version** of the original problem until it reaches the simplest case (base case). Then, the results bubble back up to build the final answer.

**Important**: Always ensure your recursive function has a proper base case, otherwise it will run infinitely and cause a stack overflow error!
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1776471081,
    "id": "chatcmpl-269e4881-6d79-91da-ad5b-a5d16443cade",
    "model": "qwen3-max",
    "object": "chat.completion.chunk",
    "system_fingerprint": null,
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "**"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1776471081,
    "id": "chatcmpl-269e4881-6d79-91da-ad5b-a5d16443cade",
    "model": "qwen3-max",
    "object": "chat.completion.chunk",
    "system_fingerprint": null,
    "usage": null
  },
  "... 74 more chunks omitted ...",
  {
    "choices": [],
    "created": 1776471081,
    "id": "chatcmpl-269e4881-6d79-91da-ad5b-a5d16443cade",
    "model": "qwen3-max",
    "object": "chat.completion.chunk",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 422,
      "prompt_tokens": 19,
      "prompt_tokens_details": {
        "cached_tokens": 0
      },
      "total_tokens": 441
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting Qwen use DashScope's built-in web search via enable_search</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3-max',
  {
    enable_search: true,
    max_tokens: 4096,
    messages: [
      {
        content:
          'What were the top news stories about Cloudflare this week? Summarise in three bullets.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3-max",
  "enable_search": true,
  "max_tokens": 4096,
  "messages": [
    {
      "content": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
      "role": "user"
    }
  ]
}'
```

```
As of the week ending June 23, 2026, the top Cloudflare news stories include:

- **Acquisition of VoidZero**: On June 4, 2026, Cloudflare announced it acquired VoidZero to accelerate development of the AI-native web, enhancing its platform for next-generation agentic applications.

- **Secure Sandboxes for Claude Managed Agents**: On May 19, 2026, Cloudflare introduced secure, scalable sandboxes integrated with Anthropic’s Claude Managed Agents, strengthening runtime security for AI agents—a key update still resonating in early June coverage.

- **Industry Recognition and Strategic Momentum**: Throughout June, Cloudflare continued to be highlighted as a Leader in Edge Development Platforms (per an independent research firm report on May 5, widely cited in June) and maintained media visibility through its ongoing “Agents Week 2026” initiatives, reinforcing its position at the forefront of agentic AI infrastructure.
```

```json
{
  "id": "chatcmpl-5860fcba-c7bc-9e5e-afd8-d32376b5a423",
  "object": "chat.completion",
  "created": 1782161284,
  "model": "qwen3-max",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "As of the week ending June 23, 2026, the top Cloudflare news stories include:\n\n- **Acquisition of VoidZero**: On June 4, 2026, Cloudflare announced it acquired VoidZero to accelerate development of the AI-native web, enhancing its platform for next-generation agentic applications.\n\n- **Secure Sandboxes for Claude Managed Agents**: On May 19, 2026, Cloudflare introduced secure, scalable sandboxes integrated with Anthropic’s Claude Managed Agents, strengthening runtime security for AI agents—a key update still resonating in early June coverage.\n\n- **Industry Recognition and Strategic Momentum**: Throughout June, Cloudflare continued to be highlighted as a Leader in Edge Development Platforms (per an independent research firm report on May 5, widely cited in June) and maintained media visibility through its ongoing “Agents Week 2026” initiatives, reinforcing its position at the forefront of agentic AI infrastructure."
      },
      "finish_reason": "stop",
      "logprobs": null
    }
  ],
  "usage": {
    "prompt_tokens": 3589,
    "completion_tokens": 196,
    "total_tokens": 3785,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "system_fingerprint": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

Chat CompletionsResponses

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen3-max/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen3-max/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen3-max/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen3-max/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/qwen3-max/#page","headline":"Qwen 3 Max","description":"Alibaba's Qwen 3 Max is a large language model with strong coding, reasoning, and multilingual capabilities, served via DashScope's OpenAI-compatible endpoint.","url":"https://developers.cloudflare.com/ai/models/alibaba/qwen3-max/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's Qwen 3.5 is a 397B-parameter mixture-of-experts model with 17B active parameters, offering strong reasoning capabilities with efficient inference.
title: Qwen 3.5 397B A17B
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# Qwen 3.5 397B A17B

Text Generation • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/qwen3.5-397b-a17b/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/qwen3.5-397b-a17b`

- Third-party
- Zero data retention

Alibaba's Qwen 3.5 is a 397B-parameter mixture-of-experts model with 17B active parameters, offering strong reasoning capabilities with efficient inference.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://www.alibabacloud.com/en/solutions/generative-ai/qwen) |
| Zero data retention | Yes |
| Request formats | Chat Completions, Responses |
| Pricing | <ul><li>Input (per 1M tokens)$0.60</li><li>Output (per 1M tokens)$3.60</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/qwen3.5-397b-a17b',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.5-397b-a17b",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The three laws of thermodynamics describe how energy, heat, and entropy behave in physical systems. Here they are, explained simply:

### 1. The First Law: Conservation of Energy
**The Definition:** Energy cannot be created or destroyed; it can only be transferred or changed from one form to another.
**What it means:** The total amount of energy in the universe is constant. If you put energy into a system (like heating a pot of water), that energy doesn't disappear; it turns into internal energy (hot water) or work (steam moving a lid).
*   **Simple Summary:** "You can't get something for nothing."

### 2. The Second Law: Entropy
**The Definition:** The total entropy (disorder or randomness) of an isolated system can never decrease over time.
**What it means:** Energy naturally flows from a concentrated state to a dispersed state. For example, heat always flows naturally from a hot object to a cold object, never the reverse, unless work is done. Because of this, no machine is 100% efficient; some energy is always lost as waste heat, increasing the disorder of the universe.
*   **Simple Summary:** "You can't even break even." (You always lose some usable energy as heat).

### 3. The Third Law: Absolute Zero
**The Definition:** As the temperature of a system approaches absolute zero, the entropy of the system approaches a constant minimum.
**What it means:** Absolute zero (0 Kelvin or -273.15°C) is the theoretical point where all molecular motion stops. This law implies that it is impossible to cool any substance to exactly absolute zero in a finite number of steps. As you get closer to that temperature, the system becomes perfectly ordered.
*   **Simple Summary:** "You can't get out of the game." (You can never reach absolute zero).

***

### Bonus: The Zeroth Law
Although it was formulated after the first three, it is so fundamental that it was named the "Zeroth" law.
**The Definition:** If two systems are each in thermal equilibrium with a third system, then they are in thermal equilibrium with each other.
**What it means:** This is the law that allows us to use thermometers. If Thermometer A says Object B is 70°F, and Thermometer A says Object C is 70°F, then Object B and Object C are the same temperature.

### The "Gambling" Analogy
Physicist C.P. Snow famously summarized the laws using a gambling analogy:
1.  **First Law:** You can't win (you can't get more energy out than you put in).
2.  **Second Law:** You can't break even (you will always lose some energy to heat/friction).
3.  **Third Law:** You can't leave the table (you can never reach absolute zero to stop entropy).
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "The three laws of thermodynamics describe how energy, heat, and entropy behave in physical systems. Here they are, explained simply:\n\n### 1. The First Law: Conservation of Energy\n**The Definition:** Energy cannot be created or destroyed; it can only be transferred or changed from one form to another.\n**What it means:** The total amount of energy in the universe is constant. If you put energy into a system (like heating a pot of water), that energy doesn't disappear; it turns into internal energy (hot water) or work (steam moving a lid).\n*   **Simple Summary:** \"You can't get something for nothing.\"\n\n### 2. The Second Law: Entropy\n**The Definition:** The total entropy (disorder or randomness) of an isolated system can never decrease over time.\n**What it means:** Energy naturally flows from a concentrated state to a dispersed state. For example, heat always flows naturally from a hot object to a cold object, never the reverse, unless work is done. Because of this, no machine is 100% efficient; some energy is always lost as waste heat, increasing the disorder of the universe.\n*   **Simple Summary:** \"You can't even break even.\" (You always lose some usable energy as heat).\n\n### 3. The Third Law: Absolute Zero\n**The Definition:** As the temperature of a system approaches absolute zero, the entropy of the system approaches a constant minimum.\n**What it means:** Absolute zero (0 Kelvin or -273.15°C) is the theoretical point where all molecular motion stops. This law implies that it is impossible to cool any substance to exactly absolute zero in a finite number of steps. As you get closer to that temperature, the system becomes perfectly ordered.\n*   **Simple Summary:** \"You can't get out of the game.\" (You can never reach absolute zero).\n\n***\n\n### Bonus: The Zeroth Law\nAlthough it was formulated after the first three, it is so fundamental that it was named the \"Zeroth\" law.\n**The Definition:** If two systems are each in thermal equilibrium with a third system, then they are in thermal equilibrium with each other.\n**What it means:** This is the law that allows us to use thermometers. If Thermometer A says Object B is 70°F, and Thermometer A says Object C is 70°F, then Object B and Object C are the same temperature.\n\n### The \"Gambling\" Analogy\nPhysicist C.P. Snow famously summarized the laws using a gambling analogy:\n1.  **First Law:** You can't win (you can't get more energy out than you put in).\n2.  **Second Law:** You can't break even (you will always lose some energy to heat/friction).\n3.  **Third Law:** You can't leave the table (you can never reach absolute zero to stop entropy).",
        "reasoning_content": "Here's a thinking process that leads to the suggested answer:\n\n1.  **Analyze the Request:**\n    *   **Topic:** Thermodynamics.\n    *   **Question:** What are the three laws?\n    *   **Goal:** Provide a clear, accurate, and concise explanation of the three laws of thermodynamics.\n\n2.  **Identify the Core Content:**\n    *   *First Law:* Conservation of energy (energy cannot be created or destroyed, only changed).\n    *   *Second Law:* Entropy (disorder increases, heat flows hot to cold, efficiency limits).\n    *   *Third Law:* Absolute zero (entropy approaches a constant minimum as temperature approaches absolute zero).\n    *   *Zeroth Law:* (Optional but good to mention for completeness) Thermal equilibrium.\n\n3.  **Drafting the Explanations (Iterative Process):**\n\n    *   *First Law:*\n        *   *Draft 1:* Energy stays the same.\n        *   *Draft 2:* You can't create energy. It just changes form.\n        *   *Refinement:* Energy cannot be created or destroyed, only transformed or transferred. $\\Delta U = Q - W$.\n        *   *Analogy:* \"You can't win\" (can't get more energy out than you put in).\n\n    *   *Second Law:*\n        *   *Draft 1:* Things get messy. Heat goes to cold.\n        *   *Draft 2:* Entropy always increases. You can't break even.\n        *   *Refinement:* The total entropy of an isolated system always increases over time. Heat naturally flows from hot to cold. Perpetual motion machines are impossible.\n        *   *Analogy:* \"You can't break even\" (you always lose some energy as waste heat).\n\n    *   *Third Law:*\n        *   *Draft 1:* Absolute zero is cold.\n        *   *Draft 2:* At zero Kelvin, entropy stops.\n        *   *Refinement:* As temperature approaches absolute zero, the entropy of a system approaches a constant minimum. It is impossible to reach absolute zero.\n        *   *Analogy:* \"You can't get out of the game\" (you can never reach absolute zero).\n\n4.  **Structuring the Response:**\n    *   **Introduction:** Briefly define thermodynamics (study of heat/energy).\n    *   **The Laws (Numbered):**\n        *   Name of the law.\n        *   Formal definition.\n        *   Simple explanation/implication.\n        *   (Optional but helpful) The \"Gambling\" analogy is a classic way to remember them.\n    *   **Bonus:** Mention the Zeroth Law (since it logically comes first but was discovered later).\n    *   **Conclusion:** Summary sentence.\n\n5.  **Refining the Content (Self-Correction during drafting):**\n    *   *Check:* Did I explain *Entropy* clearly? It's a tricky concept. I should define it as \"disorder\" or \"randomness\" for simplicity, though \"energy dispersal\" is more accurate physically. Let's stick to \"disorder/randomness\" for a general overview but mention energy quality.\n    *   *Check:* Is the math necessary? Maybe include the formula for the First Law ($\\Delta U = Q - W$) but keep it secondary to the text explanation.\n    *   *Check:* Make sure to distinguish between \"isolated system\" and just \"system.\"\n\n6.  **Final Polish (similar to the provided good output):**\n\n    *   *First Law:* Conservation of Energy. \"Energy cannot be created or destroyed...\"\n    *   *Second Law:* Entropy. \"Total entropy of an isolated system can never decrease...\" Mention heat flow.\n    *   *Third Law:* Absolute Zero. \"Entropy approaches a constant value as temperature approaches absolute zero...\"\n\n    *   *The \"Gin Rummy\" Analogy:*\n        1.  You can't win.\n        2.  You can't break even.\n        3.  You can't quit the game.\n\n7.  **Final Output Generation:** (This matches the structured response provided in the good output.)\n    *   *Zeroth Law:* Added as a footnote or brief mention because it's foundational.\n\n8.  **Review against constraints:** The user asked for \"the three laws.\" I will provide the three main ones but briefly acknowledge the Zeroth law for accuracy.\n\n**(Self-Correction Example during the process):** I initially thought about just saying \"Energy is conserved.\" But that's too brief. I need to explain *how* (transformation). For the Second Law, just saying \"Entropy increases\" is confusing to laypeople. I need to add \"heat flows from hot to cold\" or \"energy becomes less useful.\"\n\n9.  **Final Output Construction.** (Proceed to generate the response.)",
        "role": "assistant"
      }
    }
  ],
  "created": 1776471119,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-551fb302-f3c7-927c-879d-7103aaea0479",
  "model": "qwen3.5-397b-a17b",
  "object": "chat.completion",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 1675,
    "completion_tokens_details": {
      "reasoning_tokens": 1056,
      "text_tokens": 1675
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "text_tokens": 19
    },
    "total_tokens": 1694
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.5-397b-a17b',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.5-397b-a17b",
  "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"
    }
  ]
}'
```

````
# Reading JSON Files in Python

Python's built-in `json` module makes it easy to read and work with JSON data. Here's a comprehensive guide:

## 1. Basic Example: Reading a JSON File

```python
import json

with open('data.json', 'r') as file:
    data = json.load(file)

print(data)
```

- `json.load()` reads JSON from a file object.
- The `with` statement ensures the file is properly closed after reading.

## 2. Reading JSON from a String

```python
import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)

print(data['name'])  # Output: Alice
```

- `json.loads()` parses JSON from a string.

## 3. With Error Handling

```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found!")
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")
```

## 4. Complete Example with Sample Data

**data.json**
```json
{
    "name": "John",
    "age": 25,
    "city": "New York",
    "hobbies": ["reading", "gaming"]
}
```

**Python Code**
```python
import json

with open('data.json', 'r') as file:
    data = json.load(file)

print(f"Name: {data['name']}")
print(f"Age: {data['age']}")
print(f"Hobbies: {', '.join(data['hobbies'])}")
```

## 5. Key Differences: `load()` vs `loads()`

| Method      | Purpose                        |
|-------------|--------------------------------|
| `json.load()`   | Read JSON from a **file**        |
| `json.loads()`  | Read JSON from a **string**      |

## 6. Useful Options

```python
# Pretty-print JSON data
print(json.dumps(data, indent=4))

# Read with specific encoding
with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
```

## 7. Working with JSON Arrays

```python
# If your JSON file contains a list
with open('users.json', 'r') as file:
    users = json.load(file)  # Returns a list

for user in users:
    print(user['name'])
```

## Key Points

- ✅ Always use `with open()` for safe file handling
- ✅ Use `json.load()` for files, `json.loads()` for strings
- ✅ JSON objects become Python dictionaries
- ✅ JSON arrays become Python lists
- ✅ Handle exceptions for robust code

This covers the most common scenarios for reading JSON in Python. Let me know if you'd like to learn about writing JSON files too!
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "# Reading JSON Files in Python\n\nPython's built-in `json` module makes it easy to read and work with JSON data. Here's a comprehensive guide:\n\n## 1. Basic Example: Reading a JSON File\n\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n- `json.load()` reads JSON from a file object.\n- The `with` statement ensures the file is properly closed after reading.\n\n## 2. Reading JSON from a String\n\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)\n\nprint(data['name'])  # Output: Alice\n```\n\n- `json.loads()` parses JSON from a string.\n\n## 3. With Error Handling\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r') as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"File not found!\")\nexcept json.JSONDecodeError as e:\n    print(f\"Invalid JSON: {e}\")\n```\n\n## 4. Complete Example with Sample Data\n\n**data.json**\n```json\n{\n    \"name\": \"John\",\n    \"age\": 25,\n    \"city\": \"New York\",\n    \"hobbies\": [\"reading\", \"gaming\"]\n}\n```\n\n**Python Code**\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(f\"Name: {data['name']}\")\nprint(f\"Age: {data['age']}\")\nprint(f\"Hobbies: {', '.join(data['hobbies'])}\")\n```\n\n## 5. Key Differences: `load()` vs `loads()`\n\n| Method      | Purpose                        |\n|-------------|--------------------------------|\n| `json.load()`   | Read JSON from a **file**        |\n| `json.loads()`  | Read JSON from a **string**      |\n\n## 6. Useful Options\n\n```python\n# Pretty-print JSON data\nprint(json.dumps(data, indent=4))\n\n# Read with specific encoding\nwith open('data.json', 'r', encoding='utf-8') as file:\n    data = json.load(file)\n```\n\n## 7. Working with JSON Arrays\n\n```python\n# If your JSON file contains a list\nwith open('users.json', 'r') as file:\n    users = json.load(file)  # Returns a list\n\nfor user in users:\n    print(user['name'])\n```\n\n## Key Points\n\n- ✅ Always use `with open()` for safe file handling\n- ✅ Use `json.load()` for files, `json.loads()` for strings\n- ✅ JSON objects become Python dictionaries\n- ✅ JSON arrays become Python lists\n- ✅ Handle exceptions for robust code\n\nThis covers the most common scenarios for reading JSON in Python. Let me know if you'd like to learn about writing JSON files too!",
        "reasoning_content": "This is a straightforward question about reading JSON files in Python. I should provide a clear, practical answer with code examples. Let me cover:\n\n1. The basic method using the json module\n2. Different ways to read JSON (from file, from string)\n3. Error handling\n4. Common use cases\n\nLet me provide a helpful, comprehensive answer with examples.",
        "role": "assistant"
      }
    }
  ],
  "created": 1776471107,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-e13707d8-7ad1-9e21-81bb-ada8479d43a5",
  "model": "qwen3.5-397b-a17b",
  "object": "chat.completion",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 735,
    "completion_tokens_details": {
      "reasoning_tokens": 76,
      "text_tokens": 735
    },
    "prompt_tokens": 35,
    "prompt_tokens_details": {
      "text_tokens": 35
    },
    "total_tokens": 770
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.5-397b-a17b',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.5-397b-a17b",
  "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"
    }
  ]
}'
```

```
The best stops depend heavily on which route you choose. There are two main options:

1.  **Highway 1 (Pacific Coast Highway):** The scenic, iconic route. It takes longer (8–10+ hours driving time) but is much more beautiful.
2.  **Interstate 5 (I-5):** The fastest route (5–6 hours), but mostly flat farmland and less scenic.

Here are the best stops for both routes, ordered from North to South:

### **Option 1: The Scenic Route (Highway 1)**
*Best if you have 2 days or want the classic California experience.*

*   **Half Moon Bay (30 mins from SF):** Great for a quick coffee and a walk on the beach before leaving the Bay Area.
*   **Santa Cruz (1.5 hours from SF):** Visit the **Santa Cruz Boardwalk** for classic amusement park vibes or surf at Steamer Lane.
*   **Monterey & Carmel-by-the-Sea (2.5 hours from SF):**
    *   **Monterey Bay Aquarium:** World-class marine life.
    *   **17-Mile Drive:** A scenic toll road with stunning ocean views.
    *   **Carmel:** Quaint village feel, great for lunch and browsing art galleries.
*   **Big Sur (3.5 hours from SF):** The highlight of the trip.
    *   **Bixby Creek Bridge:** The most photographed bridge in California.
    *   **McWay Falls:** An 80-foot waterfall that drops directly onto the beach.
    *   *Note: Check Caltrans for road closures before you go, as landslides occasionally close this section.*
*   **San Luis Obispo (SLO) (5.5 hours from SF):** A good halfway point to sleep. Visit **Bubblegum Alley** or the Mission San Luis Obispo.
*   **Solvang (6 hours from SF):** A slight detour off the 101, this is a unique Danish-style village with bakeries and windmills.
*   **Santa Barbara (7 hours from SF):** Known as the "American Riviera." Visit the **Old Mission**, the **Courthouse Sunroom** for views, and **Stearns Wharf**.
*   **Malibu (8.5 hours from SF):** You're almost there! Stop at **Santa Monica Pier** or **Venice Beach** to officially mark the end of the trip.

### **Option 2: The Fast Route (I-5 South)**
*Best if you just want to get to LA quickly.*

*   **Gilroy Premium Outlets (1 hour from SF):** Good for shopping and lunch; known as the "Garlic Capital of the World."
*   **Kettleman City (2.5 hours from SF):** Mostly known for another large outlet mall and fast food stops in the middle of the valley.
*   **Six Flags Magic Mountain (5 hours from SF):** Located in Valencia, just north of LA. Great if you like roller coasters and have extra time.

### **Quick Tips for the Trip**
*   **Time:** If you take Highway 1, I highly recommend splitting it into **two days**. Trying to do it in one day means you'll be driving in the dark and miss the views.
*   **Gas:** Gas prices are higher along Highway 1. Fill up in larger towns like Monterey or San Luis Obispo.
*   **Food:** You can't miss an **In-N-Out Burger** along the way (there are many on both routes).
*   **Traffic:** Avoid leaving SF on Friday afternoon or entering LA during rush hour (3 PM–7 PM) if possible.

Do you think you'll prefer the scenic route or the faster one? I can help you plan a schedule based on that!
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "The best stops depend heavily on which route you choose. There are two main options:\n\n1.  **Highway 1 (Pacific Coast Highway):** The scenic, iconic route. It takes longer (8–10+ hours driving time) but is much more beautiful.\n2.  **Interstate 5 (I-5):** The fastest route (5–6 hours), but mostly flat farmland and less scenic.\n\nHere are the best stops for both routes, ordered from North to South:\n\n### **Option 1: The Scenic Route (Highway 1)**\n*Best if you have 2 days or want the classic California experience.*\n\n*   **Half Moon Bay (30 mins from SF):** Great for a quick coffee and a walk on the beach before leaving the Bay Area.\n*   **Santa Cruz (1.5 hours from SF):** Visit the **Santa Cruz Boardwalk** for classic amusement park vibes or surf at Steamer Lane.\n*   **Monterey & Carmel-by-the-Sea (2.5 hours from SF):**\n    *   **Monterey Bay Aquarium:** World-class marine life.\n    *   **17-Mile Drive:** A scenic toll road with stunning ocean views.\n    *   **Carmel:** Quaint village feel, great for lunch and browsing art galleries.\n*   **Big Sur (3.5 hours from SF):** The highlight of the trip.\n    *   **Bixby Creek Bridge:** The most photographed bridge in California.\n    *   **McWay Falls:** An 80-foot waterfall that drops directly onto the beach.\n    *   *Note: Check Caltrans for road closures before you go, as landslides occasionally close this section.*\n*   **San Luis Obispo (SLO) (5.5 hours from SF):** A good halfway point to sleep. Visit **Bubblegum Alley** or the Mission San Luis Obispo.\n*   **Solvang (6 hours from SF):** A slight detour off the 101, this is a unique Danish-style village with bakeries and windmills.\n*   **Santa Barbara (7 hours from SF):** Known as the \"American Riviera.\" Visit the **Old Mission**, the **Courthouse Sunroom** for views, and **Stearns Wharf**.\n*   **Malibu (8.5 hours from SF):** You're almost there! Stop at **Santa Monica Pier** or **Venice Beach** to officially mark the end of the trip.\n\n### **Option 2: The Fast Route (I-5 South)**\n*Best if you just want to get to LA quickly.*\n\n*   **Gilroy Premium Outlets (1 hour from SF):** Good for shopping and lunch; known as the \"Garlic Capital of the World.\"\n*   **Kettleman City (2.5 hours from SF):** Mostly known for another large outlet mall and fast food stops in the middle of the valley.\n*   **Six Flags Magic Mountain (5 hours from SF):** Located in Valencia, just north of LA. Great if you like roller coasters and have extra time.\n\n### **Quick Tips for the Trip**\n*   **Time:** If you take Highway 1, I highly recommend splitting it into **two days**. Trying to do it in one day means you'll be driving in the dark and miss the views.\n*   **Gas:** Gas prices are higher along Highway 1. Fill up in larger towns like Monterey or San Luis Obispo.\n*   **Food:** You can't miss an **In-N-Out Burger** along the way (there are many on both routes).\n*   **Traffic:** Avoid leaving SF on Friday afternoon or entering LA during rush hour (3 PM–7 PM) if possible.\n\nDo you think you'll prefer the scenic route or the faster one? I can help you plan a schedule based on that!",
        "reasoning_content": "Thinking Process:\n\n1.  **Analyze the Request:**\n    *   **Task:** Plan a road trip from San Francisco (SF) to Los Angeles (LA).\n    *   **Specific Question:** \"What are some good places to stop?\"\n    *   **Context:** The user previously asked for help planning the trip, and I confirmed the distance/time and offered route/stop suggestions. Now they want specific stops.\n\n2.  **Identify Key Routes:**\n    *   There are two main routes for SF to LA:\n        *   **I-5 South:** Fastest, inland, mostly agriculture/flat, less scenic.\n        *   **Highway 1 (Pacific Coast Highway - PCH):** Scenic, coastal, slower, more stops, iconic.\n    *   *Decision:* Since the user asked for \"good places to stop,\" they are likely interested in the scenic route (Highway 1) or a mix. I should present options based on the route because the stops differ significantly. I'll focus primarily on Highway 1 as it's the classic \"road trip\" experience, but mention I-5 options for efficiency.\n\n3.  **Brainstorm Stops (Highway 1/PCH):**\n    *   *Half Moon Bay:* Close to SF, beaches, pumpkin season.\n    *   *Santa Cruz:* Boardwalk, surf culture.\n    *   *Monterey/Carmel:* Aquarium, 17-Mile Drive, Cannery Row.\n    *   *Big Sur:* Bixby Bridge, McWay Falls, hiking.\n    *   *San Luis Obispo (SLO):* Bubblegum Alley, Mission.\n    *   *Solvang:* Danish village (slightly inland off the 101).\n    *   *Santa Barbara:* Courthouse, Stearns Wharf, \"American Riviera.\"\n    *   *Malibu:* Beaches, celebrity homes, nearing LA.\n\n4.  **Brainstorm Stops (I-5):**\n    *   *Gilroy:* Garlic capital (outlets).\n    *   *Coalinga:* Pretty much nothing.\n    *   *Kettleman City:* Outlets.\n    *   *Grapevine:* Tejon Pass (scary drive), Lebec.\n    *   *Valencia:* Six Flags.\n    *   *Note:* I-5 is boring. I should emphasize Highway 1 for a \"road trip\" vibe.\n\n5.  **Structure the Response:**\n    *   **Acknowledge the Route Choice:** Crucial because stops depend on the route. Recommend Highway 1 for scenery, I-5 for speed.\n    *   **Categorize Stops:** Group them geographically (North to South) so the user can visualize the flow.\n    *   **Highlight Must-Sees:** Pick the top attractions for each stop.\n    *   **Practical Tips:** Mention driving time, reservations (Big Sur), and best time to travel.\n\n6.  **Drafting the Content (Iterative refinement):**\n    *   *Intro:* Clarify the two main routes.\n    *   *Route 1: Pacific Coast Highway (Highway 1)* - The Scenic Choice.\n        *   Stop 1: Monterey/Carmel (Aquarium, 17-Mile).\n        *   Stop 2: Big Sur (Bixby, McWay Falls). *Warning: Check road conditions.*\n        *   Stop 3: San Luis Obispo (SLO).\n        *   Stop 4: Santa Barbara (Courthouse, Wharf).\n        *   Stop 5: Malibu (Beaches).\n    *   *Route 2: Interstate 5* - The Fast Choice.\n        *   Gilroy Premium Outlets.\n        *   Kettleman City Outlets.\n        *   Six Flags Magic Mountain (near end).\n    *   *Tips:* Check Caltrans for road closures (Big Sur slides are common), book accommodations early, allow 2 days for PCH.\n\n7.  **Refining for Helpfulness:**\n    *   Make sure to mention that Highway 1 is currently open but always check for closures due to landslides.\n    *   Suggest splitting the trip over 2 days if taking PCH.\n    *   Keep the tone enthusiastic and helpful.\n\n8.  **Final Review:** Does this answer the user's question directly? Yes. Is it accurate? Yes. Is it safe advice (regarding road conditions)? Yes.\n\n    *(Self-Correction during drafting)*: I should make sure not to overwhelm them. Keep the list curated. Focus on the \"best\" stops. Also, remind them that Highway 1 takes much longer than I-5.\n\n9.  **Final Output Generation:** (Matches the planned structure).\n    *   Greeting & Route Clarification.\n    *   Highway 1 Stops (North to South).\n    *   I-5 Stops (Briefly).\n    *   Practical Tips.\n\n10. **Post-computation check:** Ensure I don't give outdated info about Big Sur closures. As of my last update, it's generally open but prone to closures. I will advise checking current status.\n\n    *Let's build the response.*\n    *   Start with the route distinction.\n    *   List PCH stops: Half Moon Bay, Santa Cruz, Monterey/Carmel, Big Sur, SLO, Santa Barbara, Malibu.\n    *   List I-5 stops: Gilroy, Kettleman, Valencia.\n    *   Add tips on timing and reservations.\n\n    *Wait, one more thing:* Food recommendations add value. Maybe mention In-N-Out or specific local spots? Keep it general enough to be useful but specific enough to be actionable.\n\n    *Okay, ready to write.*",
        "role": "assistant"
      }
    }
  ],
  "created": 1776471146,
  "gatewayMetadata": {
    "keySource": 
... response truncated ...
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.5-397b-a17b',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.5-397b-a17b",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
The rain didn't fall so much as it hovered, a wet gray mist that clung to Detective Silas Vane's trench coat like a second skin. He ducked under the yellow tape, the flashing blue and red lights of the cruisers painting the puddles in fractured neon. Inside the apartment, the air was still, smelling faintly of copper and old paper.

The victim lay sprawled across the Persian rug, a man of means who had died in a place of solitude. The uniformed officers had already tagged the obvious: the empty pistol on the desk, the shattered whiskey glass, the note that screamed suicide but felt too practiced to be real.

Vane ignored them all. He knelt beside the body, his knees cracking in the silence. He wasn't looking at the dead man's face, but at his right hand. The fingers were curled tight, locked in rigor mortis around something small and metallic.

"Bag it," Vane said, his voice gravelly from too many cigarettes and not enough sleep.

An officer stepped forward with evidence tweezers, but Vane held up a gloved hand. He leaned in closer. Resting in the palm of the dead man's hand was a die. It was heavy, made of brushed steel, cold to the touch even through the latex of his glove.

Vane frowned. He turned the object slightly with the tip of the tweezers.

One face showed a single dot. The next, two. The third, three. But as he rotated it, the geometry stopped making sense. There were no opposing sides that added up to seven. There wasn't even a standard cube shape; it was slightly asymmetrical, worn smooth on one edge as if it had been rolled a million times.

And then he saw the seventh face.

Standard dice have six. This one had a flat, polished surface where a corner should have been, etched with a symbol Vane didn't recognize: a circle bisected by a jagged line.

He glanced at the sealed windows, then back at the die. It was warm. Not body heat warm, but vibrating with a low, humless energy that tickled the tips of his fingers. Someone hadn't just dropped this; someone had placed it here after the heart stopped beating.

"Change of plans," Vane said, standing up and pocketing the evidence bag without sealing it. "Don't bag the body yet. I think he was waiting for someone to roll again."
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "The rain didn't fall so much as it hovered, a wet gray mist that clung to Detective Silas Vane's trench coat like a second skin. He ducked under the yellow tape, the flashing blue and red lights of the cruisers painting the puddles in fractured neon. Inside the apartment, the air was still, smelling faintly of copper and old paper.\n\nThe victim lay sprawled across the Persian rug, a man of means who had died in a place of solitude. The uniformed officers had already tagged the obvious: the empty pistol on the desk, the shattered whiskey glass, the note that screamed suicide but felt too practiced to be real.\n\nVane ignored them all. He knelt beside the body, his knees cracking in the silence. He wasn't looking at the dead man's face, but at his right hand. The fingers were curled tight, locked in rigor mortis around something small and metallic.\n\n\"Bag it,\" Vane said, his voice gravelly from too many cigarettes and not enough sleep.\n\nAn officer stepped forward with evidence tweezers, but Vane held up a gloved hand. He leaned in closer. Resting in the palm of the dead man's hand was a die. It was heavy, made of brushed steel, cold to the touch even through the latex of his glove.\n\nVane frowned. He turned the object slightly with the tip of the tweezers.\n\nOne face showed a single dot. The next, two. The third, three. But as he rotated it, the geometry stopped making sense. There were no opposing sides that added up to seven. There wasn't even a standard cube shape; it was slightly asymmetrical, worn smooth on one edge as if it had been rolled a million times.\n\nAnd then he saw the seventh face.\n\nStandard dice have six. This one had a flat, polished surface where a corner should have been, etched with a symbol Vane didn't recognize: a circle bisected by a jagged line.\n\nHe glanced at the sealed windows, then back at the die. It was warm. Not body heat warm, but vibrating with a low, humless energy that tickled the tips of his fingers. Someone hadn't just dropped this; someone had placed it here after the heart stopped beating.\n\n\"Change of plans,\" Vane said, standing up and pocketing the evidence bag without sealing it. \"Don't bag the body yet. I think he was waiting for someone to roll again.\"",
        "reasoning_content": "Thinking Process:\n\n1.  **Analyze the Request:**\n    *   **Topic:** A detective finding an unusual clue.\n    *   **Format:** Short story opening.\n    *   **Tone:** Implicitly mystery/noir/thriller (given the genre).\n    *   **Goal:** Hook the reader, establish atmosphere, introduce the detective and the clue.\n\n2.  **Brainstorming Core Elements:**\n    *   *Detective:* Needs a name, a vibe (tired, observant, cynical?). Let's go with Elias Thorne. Grizzled, maybe a bit old-school.\n    *   *Setting:* Crime scene. Rain is cliché but effective. Maybe an abandoned place? A library? A high-tech lab? Let's try a cramped, overly warm apartment. Contrast the cold case with the heat.\n    *   *The Clue:* Needs to be \"unusual.\" Not a fingerprint or a shell casing. Something out of place. A living thing? A sound? A smell? An object that shouldn't exist?\n        *   Idea 1: A clock running backwards.\n        *   Idea 2: A bird inside a sealed room.\n        *   Idea 3: A book written in a language that doesn't exist.\n        *   Idea 4: A single, fresh flower in a rotting room.\n        *   Idea 5: A pocket watch filled with sand instead of gears.\n        *   *Selection:* Let's go with something sensory and slightly surreal. A pocket watch filled with sand is good, but maybe too steampunk. How about a sound? No, visual is better for an opening. Let's try a *living* clue in a dead place. A origami bird? No. How about a photograph that changes? Too sci-fi.\n        *   *Revised Selection:* A single, pristine white glove, but it's wet with saltwater, despite being miles from the ocean in a dry season. Or... a key made of ice that hasn't melted.\n        *   *Final Decision:* A music box that plays a tune no one has heard, found in a place where music is forbidden/impossible. Or simpler: A specific, anachronistic object. Let's go with a *pocket watch that ticks backwards*. It implies time manipulation or a specific signature. Actually, let's make it more tangible. A *seed* from a plant extinct for a century, found in the victim's clenched fist.\n\n3.  **Drafting - Scene Setting:**\n    *   Rain against the window.\n    *   Police tape.\n    *   The body (briefly mentioned, don't linger too much, focus on the clue).\n    *   Elias's internal state.\n\n4.  **Drafting - The Discovery:**\n    *   Elias is searching.\n    *   He finds something the uniforms missed.\n    *   The realization of its significance.\n\n5.  **Refining the Prose:**\n    *   Show, don't tell.\n    *   Use sensory details (smell of copper, sound of rain, texture of the object).\n    *   Keep it tight.\n\n6.  **Writing - First Pass (Mental):**\n    Elias stood over the body. It was dead. He looked around. He saw something on the floor. It was a blue marble. But it was warm. He picked it up. It hummed. He knew this meant trouble.\n\n    *Critique:* Too bland. Needs more atmosphere.\n\n7.  **Writing - Second Pass (Closer to final):**\n    The rain hammered the precinct roof. Elias Thorne didn't care. He was at the scene. The victim was slumped in the chair. Elias looked at the desk. Everything was normal except one thing. A single gear. But it was made of wood. Wood doesn't work in watches. He picked it up. It smelled like lavender.\n\n    *Critique:* Better. Let's polish the \"unusual\" aspect. A wooden gear is okay, but let's make it more striking. A *live moth* pinned to the wall with a murder weapon? No. Let's go with the *extinct seed* idea. It implies history and impossibility.\n\n8.  **Finalizing the Concept:**\n    *   Detective: Elias Thorne.\n    *   Scene: A locked room, study.\n    *   Clue: A flower petal that shouldn't exist. Specifically, a *Night-Blooming Cereus* that blooms only once, but it's midday, or a species thought extinct. Let's go with a *blue rose* that isn't dyed. No, let's go with *sand* in a inland house.\n    *   *Wait, I like the \"watch ticking backwards\" idea.* It's classic but effective. Let's twist it. A watch that *doesn't tick*, but breathes. No, too fantasy.\n    *   *Okay, final choice:* A key made of glass, found in a lock of wood. It shouldn't fit, but it does.\n    *   *Actually, let's go with something simpler but eerie.* A photograph of the detective himself, taken at the crime scene, found in the victim's wallet, dated tomorrow.\n    *   *No, keep it grounded.* A single, wet footprint that leads *out* of a sealed room, but the floor is dry everywhere else.\n    *   *Okay, let's settle on:* A pocket watch filled with seawater, found in a desert town.\n    *   *Wait, I'll write about a specific object:* A child's toy soldier, but it's wearing a uniform from a war that never happened.\n\n    *Let's pivot to atmosphere.* The rain, the body, the object.\n    Object: A silver locket. Inside, not a picture, but a coordinate.\n    Object: A matchbook from a club that burned down ten years ago.\n    Object: A single ice cube that won't melt.\n\n    *Let's go with the Ice Cube.* It's visceral.\n\n    *Re-evaluating:* The prompt asks for an \"unusual clue.\"\n    Let's try: A bird. A live canary in a cage, in a house where the owner was allergic and no pets were allowed, singing a specific tune.\n    Actually, I think the *extinct flower* is the strongest visual.\n\n    *Drafting the scene:*\n    Elias Thorne hated rainy nights. The body is in the library. He finds a petal. It's from a Ghost Orchid. They don't grow here. They barely exist.\n\n    *Let's write it.*\n\n9.  **Polishing:**\n    *   Focus on the lighting (flickering bulb).\n    *   The silence vs. the rain.\n    *   Th
... response truncated ...
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.5-397b-a17b',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.5-397b-a17b",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
# Understanding Recursion

**Recursion** is a programming technique where a function calls itself to solve a problem. It's like solving a big problem by breaking it down into smaller versions of the same problem.

## Key Components

Every recursive function needs two essential parts:

1. **Base Case** – The condition that stops the recursion (prevents infinite loops)
2. **Recursive Case** – Where the function calls itself with a simpler version of the problem

## Simple Example: Calculating Factorial

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

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

### How It Works: `factorial(4)`

```
factorial(4)
= 4 * factorial(3)
= 4 * (3 * factorial(2))
= 4 * (3 * (2 * factorial(1)))
= 4 * (3 * (2 * 1))    ← Base case reached!
= 4 * (3 * 2)
= 4 * 6
= 24
```

**Visual Flow:**
```
factorial(4) → 4 × factorial(3)
                   ↓
              3 × factorial(2)
                   ↓
              2 × factorial(1)
                   ↓
                   1  ← Base case!
```

## Another Simple Example: Countdown

```python
def countdown(n):
    if n <= 0:  # Base case
        print("Blastoff!")
        return
    
    print(n)  # Do something
    countdown(n - 1)  # Recursive call

countdown(3)
# Output: 3, 2, 1, Blastoff!
```

## When to Use Recursion

✅ **Good for:**
- Tree/graph traversals
- Mathematical sequences (factorial, Fibonacci)
- Problems that naturally break into similar subproblems

⚠️ **Watch out for:**
- Missing base case (causes infinite recursion)
- Too many recursive calls (can cause stack overflow)
- Problems better solved with iteration (for performance)

## Key Takeaway

Think of recursion like Russian nesting dolls – you keep opening smaller dolls until you reach the smallest one (base case), then work your way back out!
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": null,
          "reasoning_content": "",
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1776471147,
    "id": "chatcmpl-a04b3264-a267-9868-80d3-bd0ef7353605",
    "model": "qwen3.5-397b-a17b",
    "object": "chat.completion.chunk",
    "system_fingerprint": null,
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": null,
          "reasoning_content": "This"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1776471147,
    "id": "chatcmpl-a04b3264-a267-9868-80d3-bd0ef7353605",
    "model": "qwen3.5-397b-a17b",
    "object": "chat.completion.chunk",
    "system_fingerprint": null,
    "usage": null
  },
  "... 192 more chunks omitted ...",
  {
    "choices": [],
    "created": 1776471147,
    "id": "chatcmpl-a04b3264-a267-9868-80d3-bd0ef7353605",
    "model": "qwen3.5-397b-a17b",
    "object": "chat.completion.chunk",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 656,
      "completion_tokens_details": {
        "reasoning_tokens": 108,
        "text_tokens": 656
      },
      "prompt_tokens": 21,
      "prompt_tokens_details": {
        "text_tokens": 21
      },
      "total_tokens": 677
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting Qwen use DashScope's built-in web search via enable_search</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.5-397b-a17b',
  {
    enable_search: true,
    max_tokens: 4096,
    messages: [
      {
        content:
          'What were the top news stories about Cloudflare this week? Summarise in three bullets.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.5-397b-a17b",
  "enable_search": true,
  "max_tokens": 4096,
  "messages": [
    {
      "content": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
      "role": "user"
    }
  ]
}'
```

```
Based on the provided knowledge base (current context June 2026), here are the top recent news stories about Cloudflare:

*   **Acquisition of VoidZero:** On June 4, 2026, Cloudflare announced the acquisition of VoidZero to build the future of the AI-native web, marking its latest strategic move in the AI sector.
*   **Secure Sandboxes for Claude Agents:** On May 19, 2026, Cloudflare introduced secure, scalable sandboxes for Claude managed agents, enhancing security for AI agent lifecycles.
*   **Q1 2026 Financial Results:** Cloudflare announced its first-quarter 2026 financial results on May 7, 2026, alongside being named a leader in edge development platforms by an independent research firm.
```

```json
{
  "id": "chatcmpl-1dcd0242-41e4-9959-b650-2328b2a35e8c",
  "object": "chat.completion",
  "created": 1782161740,
  "model": "qwen3.5-397b-a17b",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Based on the provided knowledge base (current context June 2026), here are the top recent news stories about Cloudflare:\n\n*   **Acquisition of VoidZero:** On June 4, 2026, Cloudflare announced the acquisition of VoidZero to build the future of the AI-native web, marking its latest strategic move in the AI sector.\n*   **Secure Sandboxes for Claude Agents:** On May 19, 2026, Cloudflare introduced secure, scalable sandboxes for Claude managed agents, enhancing security for AI agent lifecycles.\n*   **Q1 2026 Financial Results:** Cloudflare announced its first-quarter 2026 financial results on May 7, 2026, alongside being named a leader in edge development platforms by an independent research firm.",
        "reasoning_content": "Thinking Process:\n\n1.  **Analyze the Request:**\n    *   Topic: Top news stories about Cloudflare.\n    *   Timeframe: \"This week\" (relative to the current date provided in the knowledge base).\n    *   Format: Summarize in three bullets.\n    *   Language: The user asked in English, so the response should be in English.\n\n2.  **Determine the Current Date:**\n    *   The knowledge base contains multiple timestamps.\n    *   One source says \"搜索结果收录于 2026 年 6 月 13 日\" (Search results recorded on June 13, 2026).\n    *   Another source says \"撰于 2026 年 6 月 4 日\" (Written on June 4, 2026).\n    *   Another source says \"消息于 2026 年 2 月 8 日发布\" (Message published on February 8, 2026).\n    *   Another source says \"该信息的时间戳是 2026 年 4 月 19 日\" (Timestamp is April 19, 2026).\n    *   Another source says \"资料日期为 2024 年 6 月 18 日\" (Data date is June 18, 2024).\n    *   Another source says \"2026 年 6 月 8 日的资料\" (Data from June 8, 2026).\n    *   The most recent and relevant \"current\" date context seems to be around June 2026, specifically mid-June 2026 (June 13, 2026 is the latest search record date).\n    *   However, looking at the \"Media Overview | Cloudflare\" section, it lists press releases for June 2026.\n    *   The list shows:\n        *   2026 年 6 月 4 日 (June 4, 2026): \"cloudflare acquires voidzero to build the future of the ai-native web\"\n        *   2026 年 5 月 19 日 (May 19, 2026): \"cloudflare brings secure, scalable sandboxes to claude managed agents\"\n        *   2026 年 5 月 7 日 (May 7, 2026): \"cloudflare announces first quarter 2026 financial results\"\n        *   2026 年 5 月 5 日 (May 5, 2026): \"cloudflare named a leader in edge development platforms report...\"\n    *   If \"this week\" refers to the week surrounding the latest data point (June 13, 2026), I need to look for news around early to mid-June 2026.\n    *   The only June 2026 press release listed is June 4, 2026 (\"cloudflare acquires voidzero...\").\n    *   There is also a mention of \"2026 年 6 月 2 日\" (June 2, 2026) in the Spanish section regarding ITBrief about \"vinext\".\n    *   There is a mention of \"2026 年 6 月 8 日的资料\" (June 8, 2026) for the official press releases list.\n    *   Since the search record date is June 13, 2026, \"this week\" would roughly be June 9 - June 15, or perhaps the most recent significant news available in the context of the provided knowledge base (which seems to cluster around early June 2026).\n    *   However, the knowledge base primarily highlights the June 4th acquisition as the top June news.\n    *   Let's look for other recent items. The \"Media Overview\" shows June 2026 has only 1 item listed in the 1-10 range (June 4).\n    *   The Spanish section mentions \"febrero de 2026 26 de febrero de 2026\" for Vinext, but also says \"2026 年 6 月 2 日\" (June 2, 2026) in the header context. Wait, the Spanish text says \"ITBrief Cloudflare unveils vinext... febrero de 2026 26 de febrero de 2026（2026 年 6 月 2 日）\". This is confusing. It might mean the article was accessed June 2, but published Feb 26.\n    *   The most prominent recent news in the provided text for June 2026 is the acquisition of VoidZero.\n    *   Other recent news (May 2026) includes: Secure sandboxes for Claude agents (May 19), Q1 2026 Financial Results (May 7), Leader in Edge Development (May 5).\n    *   If I must strictly adhere to \"this week\" relative to the latest timestamp (June 13, 2026), the June 4th news is the closest significant event (about 1.5 weeks prior). There isn't much else specifically dated June 9-13 in the text.\n    *   However, often in these tasks, \"this week\" implies the most recent news available in the context provided. The context heavily features June 2026 news.\n    *   Let's select the top 3 most recent/significant stories from the provided text that represent the latest \"news cycle\" available (June 2026).\n    *   Story 1: Acquisition of VoidZero (June 4, 2026).\n    *   Story 2: Secure sandboxes for Claude managed agents (May 19, 2026) - This is late May, close to June.\n    *   Story 3: Q1 2026 Financial Results (May 7, 2026) OR Threat Intelligence Report (March 2026) OR Agents Week (April 2026).\n    *   Actually, looking at the \"Media Overview\" for June 2026, it says \"显示 1-10 个，共 17 个\" (Showing 1-10 of 17). But only one is explicitly dated June 4th in the list provided.\n    *   Wait, the text says \"2026 年 6 月 8 日的资料\" (Data from June 8, 2026) for the press release list.\n    *   If today is June 13, 2026 (search record date), the June 4th news is the most recent major announcement.\n    *   I need to find two more recent stories. The May 19th story about Claude agents is the next most recent.\n    *   The May 7th financial results are also recent.\n    *   Alternatively, there is mention of \"Agents Week 2026\" wrapped up around April 19, 2026.\n    *   Let's prioritize the June and May 2026 news as the \"top stories\" relative to the provided knowledge base's \"current\" timeframe (June 2026).\n\n    *   Candidate 1: Cloudflare acquires VoidZero to build the AI-native web (June 4, 2026).\n    *   Candidate 2: Cloudflare brings secure, scalable sandboxes to Claude managed agents (May 19, 2026).\n    *   Candidate 3: Cloudflare announces First Quarter 2026 Financial Results (May 7, 2026) OR Cloudflare named a leader in edge development platforms (May 5, 2026).\n    *   Let's pick the Financial Results as it's usually a top story.\n    *   Wait, is there anything else? The Spanish section mentions \"ITBrief Cloudflare unveils vinext... 2026 年 6 月 2 日\". This might be interpreted as a June 2nd news item about Vinext (Vite-based Next.js rival). This is closer to \"this week\" (June 13) than May 7.\n    *   So:\n        1.  Acquisition of VoidZero (June 4).\n        2.  Unveiling Vinext (June 2 - based on the header date context though the text says Feb 26, the header says June 2. I should be careful. The text says \"febrero de 2026 26 de febrero de 2026（2026 年 6 月 2 日）\". This likely means the article was accessed/recorded on June 2, but published Feb 26. I should probably stick to the clearly dated June 4 press release).\n        3.  Secure sandboxes for Claude (May 19).\n\n    *   Actually, looking closely at the first block: \"2026 年 6 月 显示 1-10 个，共 17 个\". It lists \"cloudflare acquires voidzero...\" on June 4. It doesn't list others for June.\n    *   So the top stories are likely the June 4 acquisition, and the late May stories.\n    *   Let's formulate the bullets based on the most recent significant announcements available in the text (June 2026 context).\n\n    *   Bullet 1: Acquisition of VoidZero (June 4, 2026).\n    *   Bullet 2: Secure sandboxes for Claude agents (May 19, 2026).\n    *   Bullet 3: Q1 2026 Financial Results (May 7, 2026) OR Being named a leader in edge development (May 5, 2026). Financial results are usually more significant.\n    *   Wait, the prompt asks for \"this week\". If the current date is June 13, 2026, June 4 is la
... response truncated ...
```

</details>

## Parameters

Schema variant

Chat CompletionsResponses

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen3.5-397b-a17b/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen3.5-397b-a17b/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen3.5-397b-a17b/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen3.5-397b-a17b/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/qwen3.5-397b-a17b/#page","headline":"Qwen 3.5 397B A17B","description":"Alibaba's Qwen 3.5 is a 397B-parameter mixture-of-experts model with 17B active parameters, offering strong reasoning capabilities with efficient inference.","url":"https://developers.cloudflare.com/ai/models/alibaba/qwen3.5-397b-a17b/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's Qwen 3.7 Max is the largest and most capable model in the Qwen3.7 series, a next-generation flagship built for the agent-centric era with deep strengths in programming, office and productivity tasks, and long-term autonomous execution, served via DashScope's OpenAI-compatible endpoint.
title: Qwen 3.7 Max
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# Qwen 3.7 Max

Text Generation • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-max/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/qwen3.7-max`

- Third-party

Alibaba's Qwen 3.7 Max is the largest and most capable model in the Qwen3.7 series, a next-generation flagship built for the agent-centric era with deep strengths in programming, office and productivity tasks, and long-term autonomous execution, served via DashScope's OpenAI-compatible endpoint.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://www.qwencloud.com/models/qwen3.7-max) |
| Request formats | Chat Completions, Responses |
| Pricing | <ul><li>Input (per 1M tokens)$1.25</li><li>Output (per 1M tokens)$3.75</li><li>Cached input (per 1M tokens)$0.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/qwen3.7-max',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.7-max",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The three laws of thermodynamics govern the behavior of energy, heat, and work in the universe. Here is a clear breakdown of each:

### 1. The First Law of Thermodynamics (Law of Conservation of Energy)
* **The Rule:** Energy cannot be created or destroyed in an isolated system; it can only change from one form to another. 
* **What it means:** The total amount of energy in the universe is constant. If a system gains or loses energy, it must be transferred from or to its surroundings.
* **Example:** When you burn gasoline in a car engine, the chemical energy in the fuel isn't destroyed; it is transformed into kinetic energy (movement) and thermal energy (heat). 

### 2. The Second Law of Thermodynamics (Law of Entropy)
* **The Rule:** The total entropy (a measure of disorder or randomness) of an isolated system will always increase over time; it can never decrease.
* **What it means:** Energy transformations are never 100% efficient. Whenever energy changes forms, some of it is always lost as unusable waste heat. It also dictates that heat will naturally flow from a hotter object to a colder object, never the reverse (unless you put work into the system, like a refrigerator does).
* **Example:** A dropped glass shatters into many pieces (increasing disorder). The glass will never spontaneously reassemble itself. Similarly, a hot cup of coffee will always cool down to match the temperature of the room.

### 3. The Third Law of Thermodynamics (Law of Absolute Zero)
* **The Rule:** As the temperature of a system approaches absolute zero (0 Kelvin, or -273.15°C), the entropy of the system approaches a constant minimum. 
* **What it means:** Absolute zero is the theoretical point where all molecular motion stops. The third law implies that it is physically impossible to cool any system to exactly absolute zero in a finite number of steps. You can get infinitely close, but never actually reach it.
* **Example:** Scientists have cooled atoms to fractions of a billionth of a degree above absolute zero, but reaching exactly 0 K is impossible.

***

**Bonus: The "Zeroth" Law**
You might occasionally hear about the **Zeroth Law of Thermodynamics**. It was formulated *after* the first three laws, but scientists realized it was so fundamentally important that it needed to come before the First Law (hence "Zeroth"). 
* **The Rule:** If system A is in thermal equilibrium with system B, and system B is in thermal equilibrium with system C, then system A is in thermal equilibrium with system C. 
* **What it means:** This law establishes the very concept of **temperature** and is the scientific principle that allows thermometers to work.

**A famous, humorous way to summarize the laws:**
* **1st Law:** You can't win (you can't get something for nothing).
* **2nd Law:** You can't break even (you always lose some energy to entropy).
* **3rd Law:** You can't get out of the game (you can never reach absolute zero).
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "The three laws of thermodynamics govern the behavior of energy, heat, and work in the universe. Here is a clear breakdown of each:\n\n### 1. The First Law of Thermodynamics (Law of Conservation of Energy)\n* **The Rule:** Energy cannot be created or destroyed in an isolated system; it can only change from one form to another. \n* **What it means:** The total amount of energy in the universe is constant. If a system gains or loses energy, it must be transferred from or to its surroundings.\n* **Example:** When you burn gasoline in a car engine, the chemical energy in the fuel isn't destroyed; it is transformed into kinetic energy (movement) and thermal energy (heat). \n\n### 2. The Second Law of Thermodynamics (Law of Entropy)\n* **The Rule:** The total entropy (a measure of disorder or randomness) of an isolated system will always increase over time; it can never decrease.\n* **What it means:** Energy transformations are never 100% efficient. Whenever energy changes forms, some of it is always lost as unusable waste heat. It also dictates that heat will naturally flow from a hotter object to a colder object, never the reverse (unless you put work into the system, like a refrigerator does).\n* **Example:** A dropped glass shatters into many pieces (increasing disorder). The glass will never spontaneously reassemble itself. Similarly, a hot cup of coffee will always cool down to match the temperature of the room.\n\n### 3. The Third Law of Thermodynamics (Law of Absolute Zero)\n* **The Rule:** As the temperature of a system approaches absolute zero (0 Kelvin, or -273.15°C), the entropy of the system approaches a constant minimum. \n* **What it means:** Absolute zero is the theoretical point where all molecular motion stops. The third law implies that it is physically impossible to cool any system to exactly absolute zero in a finite number of steps. You can get infinitely close, but never actually reach it.\n* **Example:** Scientists have cooled atoms to fractions of a billionth of a degree above absolute zero, but reaching exactly 0 K is impossible.\n\n***\n\n**Bonus: The \"Zeroth\" Law**\nYou might occasionally hear about the **Zeroth Law of Thermodynamics**. It was formulated *after* the first three laws, but scientists realized it was so fundamentally important that it needed to come before the First Law (hence \"Zeroth\"). \n* **The Rule:** If system A is in thermal equilibrium with system B, and system B is in thermal equilibrium with system C, then system A is in thermal equilibrium with system C. \n* **What it means:** This law establishes the very concept of **temperature** and is the scientific principle that allows thermometers to work.\n\n**A famous, humorous way to summarize the laws:**\n* **1st Law:** You can't win (you can't get something for nothing).\n* **2nd Law:** You can't break even (you always lose some energy to entropy).\n* **3rd Law:** You can't get out of the game (you can never reach absolute zero).",
        "reasoning_content": "Here's a thinking process that leads to the suggested answer:\n\n1.  **Analyze the Request:**\n    *   **Topic:** The three laws of thermodynamics.\n    *   **Goal:** Provide a clear, accurate, and concise explanation of each law.\n\n2.  **Identify the Core Concepts:**\n    *   *Zeroth Law:* (Wait, the prompt asks for \"the three laws.\" Usually, people mean the First, Second, and Third. However, the Zeroth law is fundamental. I should probably mention the First, Second, and Third as the primary answer, but add a note about the Zeroth law for completeness and accuracy.)\n    *   *First Law:* Conservation of energy. Energy cannot be created or destroyed, only transformed. ($\\Delta U = Q - W$).\n    *   *Second Law:* Entropy. The total entropy of an isolated system always increases over time. Heat flows from hot to cold. No engine is 100% efficient.\n    *   *Third Law:* Absolute zero. As temperature approaches absolute zero, the entropy of a system approaches a constant minimum (usually zero for a perfect crystal).\n\n3.  **Draft the Explanations (Iterative refinement for clarity):**\n\n    *   *Introduction:* Briefly state what thermodynamics is (the study of heat, energy, and work) and introduce the laws.\n\n    *   *First Law (Law of Conservation of Energy):*\n        *   *Draft 1:* Energy can't be created or destroyed. It just changes forms.\n        *   *Refinement:* Make it more scientific but accessible. \"Energy cannot be created or destroyed in an isolated system; it can only change forms.\" Give an example (e.g., chemical energy in gas turning into kinetic energy in a car).\n\n    *   *Second Law (Law of Entropy):*\n        *   *Draft 1:* Entropy always increases. Heat goes from hot to cold.\n        *   *Refinement:* \"The total entropy (disorder or randomness) of an isolated system can never decrease over time; it can only remain constant or increase.\" Explain the practical implication: heat naturally flows from hotter objects to colder ones, and no machine can be 100% efficient because some energy is always lost as waste heat.\n\n    *   *Third Law (Law of Absolute Zero):*\n        *   *Draft 1:* You can't reach absolute zero. Entropy is zero at absolute zero.\n        *   *Refinement:* \"As the temperature of a system approaches absolute zero (0 Kelvin or -273.15°C), the entropy of the system approaches a constant minimum.\" Explain the practical implication: It is impossible to cool a system to exactly absolute zero in a finite number of steps.\n\n    *   *Bonus/Context (The Zeroth Law):*\n        *   *Draft:* There's also a zeroth law about thermal equilibrium.\n        *   *Refinement:* \"Note: There is actually a **Zeroth Law**...\" Explain it simply: If A is in thermal equilibrium with B, and B with C, then A is in equilibrium with C. (This establishes the concept of temperature). Explain *why* it's called \"zeroth\" (it was formulated after the first three but is logically more fundamental).\n\n4.  **Review and Format:**\n    *   Use bolding for key terms.\n    *   Use bullet points or numbered lists for readability.\n    *   Ensure the tone is informative and accessible.\n    *   *Self-Correction during review:* Did I answer the prompt directly? Yes, I covered the three laws. Adding the Zeroth law as a \"bonus\" is good practice because it shows thoroughness without ignoring the specific phrasing of the user's question.\n\n5.  **Final Polish:** (This matches the provided good output, ensuring clear headings, simple definitions, and real-world implications for each law.) *See final output for the exact wording.*\n    *   *Check against common mnemonics:* (1st: You can't win. 2nd: You can't break even. 3rd: You can't get out of the game.) -> *Decided to include this as a fun/summative conclusion to make it memorable.*\n\n6.  **Final Output Generation.** (Proceed to generate response.)-",
        "role": "assistant"
      }
    }
  ],
  "created": 1785166054,
  "id": "chatcmpl-c736c215-8d76-9ff8-88b2-119f358b4751",
  "model": "qwen3.7-max",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 1590,
    "completion_tokens_details": {
      "reasoning_tokens": 924
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "total_tokens": 1609
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.7-max',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.7-max",
  "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"
    }
  ]
}'
```

````
To read a JSON file in Python, you use the built-in **`json`** module along with Python's built-in **`open()`** function. 

Here is the quickest and most standard way to do it:

### 1. The Quick Way
```python
import json

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

print(data)
```

### 2. The Best Practice Way (with Error Handling)
In real-world applications, it is highly recommended to specify the `encoding` and handle potential errors (like the file not existing or the JSON being formatted incorrectly).

```python
import json

file_path = 'data.json'

try:
    # encoding='utf-8' prevents errors with special characters on Windows
    with open(file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
        
    print("Successfully loaded JSON!")
    
except FileNotFoundError:
    print(f"Error: The file {file_path} was not found.")
except json.JSONDecodeError:
    print(f"Error: The file {file_path} does not contain valid JSON.")
```

---

### How JSON translates to Python
When `json.load()` reads the file, it automatically converts JSON data types into Python data types:

| JSON Type | Python Type |
| :--- | :--- |
| Object `{}` | Dictionary `dict` |
| Array `[]` | List `list` |
| String `""` | String `str` |
| Number `123` | Integer `int` or Float `float` |
| Boolean `true/false`| Boolean `True/False` |
| Null `null` | `None` |

**Example of accessing the data:**
If your `data.json` file looks like this:
```json
{
    "users": [
        {"name": "Alice", "age": 28},
        {"name": "Bob", "age": 34}
    ]
}
```
You can interact with it exactly like a normal Python dictionary and list:
```python
# Accessing data
print(data["users"][0]["name"])  # Output: Alice

# Looping through data
for user in data["users"]:
    print(f"{user['name']} is {user['age']} years old.")
```

---

### ⚠️ Common Mistake: `load()` vs `loads()`
Beginners often confuse these two functions. 
* Use **`json.load(file_object)`** when reading directly from a **file**.
* Use **`json.loads(json_string)`** (the "s" stands for string) when you have JSON data stored in a **string variable**.

```python
import json

# Using loads() for a string
json_string = '{"name": "Alice", "age": 28}'
data_from_string = json.loads(json_string) 
```
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "To read a JSON file in Python, you use the built-in **`json`** module along with Python's built-in **`open()`** function. \n\nHere is the quickest and most standard way to do it:\n\n### 1. The Quick Way\n```python\nimport json\n\n# Open the file and load its contents\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n### 2. The Best Practice Way (with Error Handling)\nIn real-world applications, it is highly recommended to specify the `encoding` and handle potential errors (like the file not existing or the JSON being formatted incorrectly).\n\n```python\nimport json\n\nfile_path = 'data.json'\n\ntry:\n    # encoding='utf-8' prevents errors with special characters on Windows\n    with open(file_path, 'r', encoding='utf-8') as file:\n        data = json.load(file)\n        \n    print(\"Successfully loaded JSON!\")\n    \nexcept FileNotFoundError:\n    print(f\"Error: The file {file_path} was not found.\")\nexcept json.JSONDecodeError:\n    print(f\"Error: The file {file_path} does not contain valid JSON.\")\n```\n\n---\n\n### How JSON translates to Python\nWhen `json.load()` reads the file, it automatically converts JSON data types into Python data types:\n\n| JSON Type | Python Type |\n| :--- | :--- |\n| Object `{}` | Dictionary `dict` |\n| Array `[]` | List `list` |\n| String `\"\"` | String `str` |\n| Number `123` | Integer `int` or Float `float` |\n| Boolean `true/false`| Boolean `True/False` |\n| Null `null` | `None` |\n\n**Example of accessing the data:**\nIf your `data.json` file looks like this:\n```json\n{\n    \"users\": [\n        {\"name\": \"Alice\", \"age\": 28},\n        {\"name\": \"Bob\", \"age\": 34}\n    ]\n}\n```\nYou can interact with it exactly like a normal Python dictionary and list:\n```python\n# Accessing data\nprint(data[\"users\"][0][\"name\"])  # Output: Alice\n\n# Looping through data\nfor user in data[\"users\"]:\n    print(f\"{user['name']} is {user['age']} years old.\")\n```\n\n---\n\n### ⚠️ Common Mistake: `load()` vs `loads()`\nBeginners often confuse these two functions. \n* Use **`json.load(file_object)`** when reading directly from a **file**.\n* Use **`json.loads(json_string)`** (the \"s\" stands for string) when you have JSON data stored in a **string variable**.\n\n```python\nimport json\n\n# Using loads() for a string\njson_string = '{\"name\": \"Alice\", \"age\": 28}'\ndata_from_string = json.loads(json_string) \n```",
        "reasoning_content": "Here's a thinking process that leads to the suggested answer:\n\n1.  **Understand the User's Goal:** The user wants to know how to read a JSON file using Python.\n\n2.  **Identify the Core Mechanism:** Python has a built-in module called `json`. The specific function needed to read from a *file* is `json.load()` (not `json.loads()`, which is for strings). The built-in `open()` function is used to access the file.\n\n3.  **Determine the Best Practices:**\n    *   Use the `with` statement (context manager) when opening files. This ensures the file is properly closed even if an error occurs.\n    *   Specify the encoding (usually `utf-8`) to avoid cross-platform encoding issues.\n    *   Handle potential exceptions (e.g., `FileNotFoundError`, `json.JSONDecodeError`).\n\n4.  **Structure the Answer:** A good technical answer should be structured logically:\n    *   **Direct Answer/Quick Example:** Give the most common, straightforward code snippet immediately.\n    *   **Detailed Explanation:** Explain *why* the code works (the `json` module, `open()`, `with` statement).\n    *   **Robust Example (Error Handling):** Show how to do it safely in a real-world scenario.\n    *   **Alternative (Reading from a string):** Briefly mention `json.loads()` just in case they actually have a JSON string, not a file.\n    *   **Working with the Data:** Show a quick example of how to access the data once it's loaded (since JSON becomes Python dictionaries/lists).\n\n5.  **Drafting the Content:**\n\n    *   *Quick Example:*\n        ```python\n        import json\n\n        with open('data.json', 'r') as file:\n            data = json.load(file)\n\n        print(data)\n        ```\n\n    *   *Explanation:*\n        *   `import json`: Built-in module.\n        *   `with open(...)`: Context manager, handles closing.\n        *   `'r'`: Read mode.\n        *   `json.load(file)`: Parses JSON into Python objects (dicts/lists).\n\n    *   *Robust Example (Error Handling):*\n        ```python\n        import json\n\n        try:\n            with open('data.json', 'r', encoding='utf-8') as file:\n                data = json.load(file)\n        except FileNotFoundError:\n            print(\"The file was not found.\")\n        except json.JSONDecodeError:\n            print(\"The file is not valid JSON.\")\n        ```\n\n    *   *Data Access Example:*\n        Assume `data.json` has `{\"name\": \"Alice\", \"age\": 30}`.\n        ```python\n        print(data['name']) # Output: Alice\n        ```\n\n    *   *Bonus/Clarification (`load` vs `loads`):*\n        *   `json.load(file_object)` -> for files.\n        *   `json.loads(json_string)` -> for strings (\"s\" stands for string).\n\n6.  **Review and Refine:**\n    *   *Tone:* Helpful, clear, and educational.\n    *   *Formatting:* Use code blocks with Python syntax highlighting. Bold key terms.\n    *   *Completeness:* Did I mention `encoding='utf-8'`? Yes, added it to the robust example as it's a best practice.\n\n7.  **Final Output Generation:** (This matches the provided good response.) Note: I will make sure the distinction between `load` and `loads` is clear, as it's a very common beginner mistake. Keep it concise but comprehensive. Keep the examples copy-pasteable. Provide a sample JSON structure so the data access example makes sense. Let's write it out. \n*(Self-Correction during drafting: Make sure to explicitly state that JSON objects become Python dictionaries, and JSON arrays become Python lists. This helps bridge the conceptual gap.)* -> *Added to the explanation.*",
        "role": "assistant"
      }
    }
  ],
  "created": 1785166084,
  "id": "chatcmpl-028ae142-ab40-9d99-a88e-af943d570ccc",
  "model": "qwen3.7-max",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 1512,
    "completion_tokens_details": {
      "reasoning_tokens": 858
    },
    "prompt_tokens": 35,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "total_tokens": 1547
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.7-max',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.7-max",
  "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"
    }
  ]
}'
```

```
The stops you'll want to make depend entirely on which route you choose! You basically have two options: the **Scenic Coastal Route** (Highway 101 and Highway 1) or the **Fast Inland Route** (Interstate 5). 

Here are the best stops for both:

### Option 1: The Scenic Coastal Route (Highway 101 & Hwy 1)
*This is the famous, beautiful drive. It takes 8 to 10+ hours of pure driving, so it’s highly recommended to break this into a 2-day trip.*

*   **Santa Cruz:** Stop to see the historic Santa Cruz Beach Boardwalk or surf at Steamer Lane. 
*   **Monterey & Carmel-by-the-Sea:** Monterey is home to the world-class **Monterey Bay Aquarium** and Cannery Row. Just south is Carmel, a gorgeous, fairy-tale-like village with great art galleries and a beautiful white-sand beach.
*   **Big Sur:** This is the most dramatic coastal scenery in California. Must-see stops include the **Bixby Creek Bridge** (the iconic concrete arch bridge) and **McWay Falls** (a waterfall that drops directly onto the beach). *Note: Always check Caltrans for Highway 1 road closures before you go, as landslides occasionally close parts of this road.*
*   **San Simeon:** Stop at the **Elephant Seal Vista Point** to see hundreds of massive wild elephant seals lounging on the beach. If you book in advance, you can also tour the massive, opulent **Hearst Castle** on the hill above.
*   **Santa Barbara:** Known as the "American Riviera," this is a perfect place to stop for lunch, walk around the historic Santa Barbara Mission, or relax on the beach before the final 2-hour push into LA.

### Option 2: The Fast Inland Route (Interstate 5)
*This is the route you take if you just want to get to LA in 5 to 6 hours. It's mostly flat farmland, but there are a few fun pit stops to break up the drive.*

*   **Gilroy:** Known as the "Garlic Capital of the World." It's a good spot to grab a quick bite or pick up some garlic-flavored snacks and souvenirs.
*   **Harris Ranch (Coalinga):** This is a legendary California road trip institution. It’s a massive restaurant, hotel, and butcher shop right off the I-5. It’s famous for its steaks, and it's the perfect place to stretch your legs and grab a high-quality meal.
*   **Bakersfield:** If you like country music, stop at the **Buck Owens Crystal Palace**, a museum, restaurant, and music venue dedicated to the "Bakersfield Sound" of country music. 
*   **Castaic Lake:** Just about 45 minutes north of LA, this is a nice spot for a quick picnic or a walk by the water to decompress before hitting LA traffic.

**To help me narrow this down for you:**
1. Are you planning to do this drive in **one day**, or do you have time to make it a **multi-day trip**?
2. Are you more interested in **nature/scenery**, **food**, or **history/quirky attractions**?
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "The stops you'll want to make depend entirely on which route you choose! You basically have two options: the **Scenic Coastal Route** (Highway 101 and Highway 1) or the **Fast Inland Route** (Interstate 5). \n\nHere are the best stops for both:\n\n### Option 1: The Scenic Coastal Route (Highway 101 & Hwy 1)\n*This is the famous, beautiful drive. It takes 8 to 10+ hours of pure driving, so it’s highly recommended to break this into a 2-day trip.*\n\n*   **Santa Cruz:** Stop to see the historic Santa Cruz Beach Boardwalk or surf at Steamer Lane. \n*   **Monterey & Carmel-by-the-Sea:** Monterey is home to the world-class **Monterey Bay Aquarium** and Cannery Row. Just south is Carmel, a gorgeous, fairy-tale-like village with great art galleries and a beautiful white-sand beach.\n*   **Big Sur:** This is the most dramatic coastal scenery in California. Must-see stops include the **Bixby Creek Bridge** (the iconic concrete arch bridge) and **McWay Falls** (a waterfall that drops directly onto the beach). *Note: Always check Caltrans for Highway 1 road closures before you go, as landslides occasionally close parts of this road.*\n*   **San Simeon:** Stop at the **Elephant Seal Vista Point** to see hundreds of massive wild elephant seals lounging on the beach. If you book in advance, you can also tour the massive, opulent **Hearst Castle** on the hill above.\n*   **Santa Barbara:** Known as the \"American Riviera,\" this is a perfect place to stop for lunch, walk around the historic Santa Barbara Mission, or relax on the beach before the final 2-hour push into LA.\n\n### Option 2: The Fast Inland Route (Interstate 5)\n*This is the route you take if you just want to get to LA in 5 to 6 hours. It's mostly flat farmland, but there are a few fun pit stops to break up the drive.*\n\n*   **Gilroy:** Known as the \"Garlic Capital of the World.\" It's a good spot to grab a quick bite or pick up some garlic-flavored snacks and souvenirs.\n*   **Harris Ranch (Coalinga):** This is a legendary California road trip institution. It’s a massive restaurant, hotel, and butcher shop right off the I-5. It’s famous for its steaks, and it's the perfect place to stretch your legs and grab a high-quality meal.\n*   **Bakersfield:** If you like country music, stop at the **Buck Owens Crystal Palace**, a museum, restaurant, and music venue dedicated to the \"Bakersfield Sound\" of country music. \n*   **Castaic Lake:** Just about 45 minutes north of LA, this is a nice spot for a quick picnic or a walk by the water to decompress before hitting LA traffic.\n\n**To help me narrow this down for you:**\n1. Are you planning to do this drive in **one day**, or do you have time to make it a **multi-day trip**?\n2. Are you more interested in **nature/scenery**, **food**, or **history/quirky attractions**?",
        "reasoning_content": "Thinking Process:\n\n1.  **Analyze the User's Request:**\n    *   **Goal:** The user wants recommendations for good places to stop on a road trip from San Francisco (SF) to Los Angeles (LA).\n    *   **Context:** Previous turn established the distance (~380 miles) and time (5-6 hours via I-5, though scenic routes take longer). The user explicitly asked for \"scenic routes or interesting stops\" in the first prompt, and now confirmed they want stop suggestions.\n    *   **Key Consideration:** The SF to LA drive has two main routes:\n        *   *Interstate 5 (I-5):* The fast, inland route (mostly agricultural/flat, fewer \"scenic\" stops, good for speed).\n        *   *Highway 101 / Pacific Coast Highway (PCH / Hwy 1):* The scenic, coastal route (takes much longer, 8-10+ hours, but has the best stops).\n    *   **Strategy:** I need to present options based on the route they choose (Fast vs. Scenic) because the stops are completely different. I should highlight the best stops for the Coastal route (since people usually want \"interesting/scenic\" stops) and maybe a couple for the Inland route just in case.\n\n2.  **Brainstorming Stops (Coastal Route - Hwy 101 / Hwy 1):**\n    *   *Half Moon Bay / Pescadero:* Good for a quick coastal start, pumpkin patches, bakery.\n    *   *Santa Cruz:* Surf City, Boardwalk, Mystery Spot.\n    *   *Monterey / Carmel-by-the-Sea:* Monterey Bay Aquarium, 17-Mile Drive, Carmel's fairy-tale cottages.\n    *   *Big Sur:* Bixby Creek Bridge, McWay Falls, Hearst Castle (a bit further south in San Simeon). *Crucial note: Check Hwy 1 closures, though as an AI, I should just advise them to check Caltrans.*\n    *   *San Luis Obispo (SLO) / Pismo Beach:* Bubblegum Alley, sand dunes, dinosaur caves.\n    *   *Santa Barbara:* \"American Riviera\", Mission, State Street, beaches.\n\n3.  **Brainstorming Stops (Inland Route - I-5 / 99):**\n    *   *Gilroy:* Garlic capital.\n    *   *Harris Ranch:* Famous steakhouse/restaurant right off the I-5.\n    *   *Bakersfield:* Basque food, Buck Owens Crystal Palace.\n    *   *Castaic Lake / Magic Mountain:* Just before LA.\n\n4.  **Structuring the Response:**\n    *   **Acknowledge the Route Choice:** Briefly explain that the stops depend heavily on whether they take the **Fast Route (I-5)** or the **Scenic Coastal Route (Highway 101/1)**.\n    *   **Option 1: The Scenic Coastal Route (Highway 101 & Highway 1)** - *Highly Recommended for stops.*\n        *   Group by region (North to South).\n        *   *Monterey & Carmel:* Aquarium, 17-Mile Drive.\n        *   *Big Sur:* Bixby Bridge, McWay Falls (add a caveat about checking road conditions).\n        *   *San Simeon:* Hearst Castle, Elephant Seal Vista Point.\n        *   *Santa Barbara:* Mission, beaches, wine.\n    *   **Option 2: The Fast Inland Route (Interstate 5)** - *For when time is tight.*\n        *   *Harris Ranch:* Classic road trip food stop.\n        *   *Buck Owens Crystal Palace (Bakersfield):* Country music history.\n        *   *California Living Museum / Bakersfield:* Quick stretch.\n    *   **Interactive Follow-up:** Ask them which route appeals to them more, how many days they have, or if they have specific interests (food, nature, history).\n\n5.  **Drafting the Content (Iterative refinement for tone and clarity):**\n    *   *Tone:* Enthusiastic, helpful, organized.\n    *   *Formatting:* Use bolding, bullet points for readability.\n\n    *(Self-Correction during drafting)*: Make sure to emphasize that Big Sur / Hwy 1 takes *much* longer. If they only have one day, doing SF to LA via Big Sur is a brutal 10-12 hour drive. I should recommend breaking the coastal route into a 2-day trip.\n\n6.  **Finalizing the Output Structure:**\n    *   Introduction: Route distinction (Coastal vs. Inland).\n    *   Coastal Stops (The \"Best\" Stops).\n    *   Inland Stops (The \"Quick\" Stops).\n    *   Pro-Tip (Road conditions / Time management).\n    *   Closing question to narrow down their preferences.\n\n7.  **Generate Response.** (Proceeding to generate based on these structured thoughts). \n    *   *Check against safety/policy:* All good. Standard travel advice.\n    *   *Check against constraints:* None specific, just be helpful. Keep it concise but detailed enough to be useful. \n    *   *Wait, check Big Sur road closures:* Paul's Slide / Regatta Point have had closures recently. I will add a generic \"check Caltrans\" warning. Always good practice for Hwy 1. \n    *   Let's write it out. \n    *   *Coastal:* Santa Cruz -> Monterey/Carmel -> Big Sur -> San Simeon -> Santa Barbara.\n    *   *Inland:* Gilroy -> Harris Ranch -> Bakersfield.\n    *   *Questions:* How many days? Interests? \n    *   Done. Ready to output. \n    *   *Wait, I shouldn't just list them, I should describe WHY they are good.* (e.g., Elephant seals, Aquarium). Added brief descriptions. \n    *   Looks solid. \n    *   End thought process.",
        "role": "assistant"
      }
    }
  ],
  "created": 1785166112,
  "id": "chatcmpl-2db0da2f-228b-949c-8a29-
... response truncated ...
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.7-max',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.7-max",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
At its core, **recursion** is a problem-solving method where the solution to a problem depends on solutions to smaller instances of the same problem. 

In programming, recursion happens when **a function calls itself** until it reaches a specific stopping point.

### A Real-Life Analogy
Imagine you are standing in a massive line for a concert, and you want to know what position you are in. You can't see the front of the line, so you tap the person in front of you and ask, "What number in line are you?" 
* That person doesn't know either, so they tap the person in front of them and ask the same question. 
* This repeats until the question reaches the very first person in line. 
* The first person says, "I'm number 1!" 
* That answer is then passed back down the line, person by person, until it finally reaches you. 

You just used recursion! You broke a big problem (finding your place in a long line) into a smaller, identical problem (asking the person directly in front of you).

---

### The Two Golden Rules of Recursion
For recursion to work properly and not crash your computer, every recursive function must have two parts:
1. **The Base Case (The Stop Sign):** The condition where the function stops calling itself. Without this, you get an infinite loop.
2. **The Recursive Step:** The part where the function calls itself with a smaller or simpler input, moving closer to the base case.

---

### A Simple Code Example: Factorial
In math, the factorial of a number (written as `n!`) is the product of all positive integers less than or equal to `n`. 
For example: `5! = 5 × 4 × 3 × 2 × 1 = 120`.

Notice the pattern: `5!` is just `5 × 4!`. 
This makes it perfect for recursion.

Here is how you write it in Python:

```python
def factorial(n):
    # 1. BASE CASE: The stopping condition
    if n == 1:
        return 1
    
    # 2. RECURSIVE STEP: The function calls itself with a smaller number
    else:
        return n * factorial(n - 1)
```

### How it Executes (Step-by-Step)
If you call `factorial(3)`, here is exactly what the computer does behind the scenes:

1. **Call 1:** `factorial(3)` 
   * *Is 3 == 1?* No. 
   * *Action:* Return `3 * factorial(2)`. (But it has to figure out what `factorial(2)` is first, so it pauses and opens a new call).
2. **Call 2:** `factorial(2)`
   * *Is 2 == 1?* No.
   * *Action:* Return `2 * factorial(1)`. (Pauses and opens a new call).
3. **Call 3:** `factorial(1)`
   * *Is 1 == 1?* **Yes! (Base Case reached)**
   * *Action:* Return `1`.

Now, the computer resolves the paused calls from the bottom up:
* Call 3 returns **`1`**
* Call 2 resolves to `2 * 1` = **`2`**
* Call 1 resolves to `3 * 2` = **`6`**

The final answer is **6**.

### Summary
* **Think of recursion as a loop**, but instead of using `for` or `while`, the function repeats by calling itself.
* **Always define a Base Case**, or your program will run out of memory (a "Stack Overflow" error) because it will keep calling itself forever. 
* Recursion is incredibly useful for tasks that have nested or branching structures, like searching through folders on your computer, navigating a maze, or analyzing family trees.
````

```json
[
  {
    "model": "qwen3.7-max",
    "id": "chatcmpl-b8935594-8259-9437-afb2-3e621bfc68a6",
    "created": 1785166153,
    "object": "chat.completion.chunk",
    "usage": null,
    "choices": [
      {
        "logprobs": null,
        "index": 0,
        "delta": {
          "content": "",
          "role": "assistant",
          "reasoning_content": ""
        },
        "finish_reason": null
      }
    ]
  },
  {
    "model": "qwen3.7-max",
    "id": "chatcmpl-b8935594-8259-9437-afb2-3e621bfc68a6",
    "choices": [
      {
        "delta": {
          "content": "",
          "reasoning_content": "思考"
        },
        "index": 0,
        "finish_reason": null,
        "logprobs": null
      }
    ],
    "created": 1785166153,
    "object": "chat.completion.chunk",
    "usage": null
  },
  "... 473 more chunks omitted ...",
  {
    "model": "qwen3.7-max",
    "id": "chatcmpl-b8935594-8259-9437-afb2-3e621bfc68a6",
    "choices": [],
    "created": 1785166153,
    "object": "chat.completion.chunk",
    "usage": {
      "total_tokens": 1649,
      "completion_tokens": 1628,
      "prompt_tokens": 21,
      "completion_tokens_details": {
        "reasoning_tokens": 771
      },
      "prompt_tokens_details": {
        "cached_tokens": 0
      }
    }
  }
]
```

</details>

## Parameters

Schema variant

Chat CompletionsResponses

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-max/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-max/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-max/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-max/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-max/#page","headline":"Qwen 3.7 Max","description":"Alibaba's Qwen 3.7 Max is the largest and most capable model in the Qwen3.7 series, a next-generation flagship built for the agent-centric era with deep strengths in programming, office and productivity tasks, and long-term autonomous execution, served via DashScope's OpenAI-compatible endpoint.","url":"https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-max/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's Qwen 3.7 Plus is the cost-effective member of the Qwen3.7 series, pairing strong text capabilities with image and video understanding and full-stack agent-level intelligence for coding, tool use, and GUI-based automation, served via DashScope's OpenAI-compatible endpoint.
title: Qwen 3.7 Plus
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# Qwen 3.7 Plus

Text Generation • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-plus/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/qwen3.7-plus`

- Third-party

Alibaba's Qwen 3.7 Plus is the cost-effective member of the Qwen3.7 series, pairing strong text capabilities with image and video understanding and full-stack agent-level intelligence for coding, tool use, and GUI-based automation, served via DashScope's OpenAI-compatible endpoint.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://www.qwencloud.com/models/qwen3.7-plus) |
| Request formats | Chat Completions, Responses |
| Pricing | <ul><li>Input (per 1M tokens)$0.32</li><li>Output (per 1M tokens)$1.28</li><li>Cached input (per 1M tokens)$0.064</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/qwen3.7-plus',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.7-plus",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The laws of thermodynamics govern how energy moves and transforms in the universe. Here are the three main laws, explained simply:

### 1. The First Law: The Law of Conservation of Energy
* **The Rule:** Energy cannot be created or destroyed; it can only be transferred or changed from one form to another.
* **In simple terms:** The total amount of energy in the universe is always the same. You can't get energy out of nowhere. 
* **Example:** When you burn wood, the chemical energy stored in the wood isn't destroyed. It is simply converted into heat energy and light energy. 

### 2. The Second Law: The Law of Entropy
* **The Rule:** The total entropy (disorder or randomness) of an isolated system will always increase over time. Additionally, heat naturally flows from a hotter object to a colder one, never the reverse without adding work.
* **In simple terms:** Things naturally move from a state of order to a state of disorder. Because of this, no machine or process can ever be 100% efficient; some energy is always lost as waste heat. This is also why perpetual motion machines are impossible.
* **Example:** If you leave a hot cup of coffee on a table, it will eventually cool down to room temperature. The heat disperses into the air, increasing the overall disorder (entropy) of the room. The coffee will never spontaneously heat back up.

### 3. The Third Law: The Law of Absolute Zero
* **The Rule:** As the temperature of a system approaches absolute zero, its entropy approaches a constant minimum (essentially zero for a perfect crystal).
* **In simple terms:** Absolute zero (0 Kelvin, or -273.15°C) is the theoretical temperature where all atomic and molecular motion completely stops. Because it is impossible to remove all heat from a system, it is physically impossible to ever actually reach absolute zero.

***

**A Quick Note on the "Zeroth" Law:**
While you asked for the three laws, physicists actually recognize a **Zeroth Law of Thermodynamics**, which was formulated after the other three but is considered so fundamental that it had to come first. 
* **The Zeroth Law** states that if two objects are both in thermal equilibrium with a third object, then they are in thermal equilibrium with each other. This law is what allows us to define and measure **temperature** using thermometers.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "The laws of thermodynamics govern how energy moves and transforms in the universe. Here are the three main laws, explained simply:\n\n### 1. The First Law: The Law of Conservation of Energy\n* **The Rule:** Energy cannot be created or destroyed; it can only be transferred or changed from one form to another.\n* **In simple terms:** The total amount of energy in the universe is always the same. You can't get energy out of nowhere. \n* **Example:** When you burn wood, the chemical energy stored in the wood isn't destroyed. It is simply converted into heat energy and light energy. \n\n### 2. The Second Law: The Law of Entropy\n* **The Rule:** The total entropy (disorder or randomness) of an isolated system will always increase over time. Additionally, heat naturally flows from a hotter object to a colder one, never the reverse without adding work.\n* **In simple terms:** Things naturally move from a state of order to a state of disorder. Because of this, no machine or process can ever be 100% efficient; some energy is always lost as waste heat. This is also why perpetual motion machines are impossible.\n* **Example:** If you leave a hot cup of coffee on a table, it will eventually cool down to room temperature. The heat disperses into the air, increasing the overall disorder (entropy) of the room. The coffee will never spontaneously heat back up.\n\n### 3. The Third Law: The Law of Absolute Zero\n* **The Rule:** As the temperature of a system approaches absolute zero, its entropy approaches a constant minimum (essentially zero for a perfect crystal).\n* **In simple terms:** Absolute zero (0 Kelvin, or -273.15°C) is the theoretical temperature where all atomic and molecular motion completely stops. Because it is impossible to remove all heat from a system, it is physically impossible to ever actually reach absolute zero.\n\n***\n\n**A Quick Note on the \"Zeroth\" Law:**\nWhile you asked for the three laws, physicists actually recognize a **Zeroth Law of Thermodynamics**, which was formulated after the other three but is considered so fundamental that it had to come first. \n* **The Zeroth Law** states that if two objects are both in thermal equilibrium with a third object, then they are in thermal equilibrium with each other. This law is what allows us to define and measure **temperature** using thermometers.",
        "reasoning_content": "Here's a thinking process that leads to the suggested answer:\n\n1.  **Analyze the Request:**\n    *   **Topic:** The three laws of thermodynamics.\n    *   **Goal:** Clearly explain what they are.\n    *   **Target Audience:** General audience (needs to be accurate but accessible, avoiding overly dense jargon where possible, or explaining it if used).\n\n2.  **Recall/Research the Three Laws of Thermodynamics:**\n    *   *Zeroth Law:* (Wait, there are technically *four* laws, but the prompt asks for the \"three.\" I should mention the Zeroth Law briefly for completeness, but focus primarily on the First, Second, and Third).\n    *   *First Law:* Conservation of energy. Energy cannot be created or destroyed, only transformed.\n    *   *Second Law:* Entropy. The total entropy of an isolated system always increases over time. Heat flows from hot to cold. No process is 100% efficient.\n    *   *Third Law:* Absolute zero. As temperature approaches absolute zero, entropy approaches a minimum (usually zero for a perfect crystal).\n\n3.  **Draft the Explanations (Iterative refinement for clarity):**\n\n    *   *Introduction:* Briefly state what thermodynamics is (the study of heat, energy, and work) to set the context.\n\n    *   *First Law (Conservation of Energy):*\n        *   *Scientific definition:* Energy can neither be created nor destroyed; it can only be transferred or changed from one form to another.\n        *   *Simple analogy/example:* A car engine turning fuel (chemical energy) into motion (kinetic energy) and heat. The total energy remains the same.\n\n    *   *Second Law (Entropy):*\n        *   *Scientific definition:* The total entropy (disorder) of an isolated system can never decrease over time. Heat naturally flows from hotter objects to colder ones.\n        *   *Simple analogy/example:* A hot cup of coffee cooling down in a room. You can't build a 100% efficient engine because some energy is always lost as waste heat (increasing overall disorder).\n\n    *   *Third Law (Absolute Zero):*\n        *   *Scientific definition:* As the temperature of a system approaches absolute zero (0 Kelvin or -273.15°C), the entropy of the system approaches a constant minimum.\n        *   *Simple analogy/example:* Absolute zero is the theoretical point where all molecular motion stops. You can't actually reach this point.\n\n    *   *Addressing the \"Zeroth Law\":*\n        *   Since the prompt specifically asked for *three*, I should answer with the main three (1st, 2nd, 3rd). However, in physics, the *Zeroth Law* is fundamental (it defines temperature). I will add a brief \"Bonus/Note\" about the Zeroth Law at the end to be thorough and accurate without confusing the main answer.\n\n4.  **Review and Refine:**\n    *   *Formatting:* Use bolding, bullet points, and clear headings to make it highly readable.\n    *   *Tone:* Informative, clear, and educational.\n    *   *Accuracy Check:* Are the definitions correct? Yes. Are the examples accurate? Yes.\n\n5.  **Final Output Generation:** (This matches the provided good response.)\n    *   *Drafting the response based on the above steps.* (See final output for the exact wording). Let me make sure the distinction between the formal law and the \"in simple terms\" is clear.\n\n    *(Self-Correction during drafting)*: Make sure to clearly state that the Second Law is why perpetual motion machines are impossible. That's a great practical takeaway for the reader.\n\n6.  **Final Polish:** (Produces the provided good response). Good structure, clear language, accurate physics. Include the Zeroth law as a fun fact at the end. Keep it concise. Let's go. 🚀👇🏼🔽",
        "role": "assistant"
      }
    }
  ],
  "created": 1785165311,
  "id": "chatcmpl-cadc5fbc-38d2-9d25-a2f0-d0322d13a6ed",
  "model": "qwen3.7-plus",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 1375,
    "completion_tokens_details": {
      "reasoning_tokens": 862,
      "text_tokens": 1375
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "text_tokens": 19
    },
    "total_tokens": 1394
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.7-plus',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.7-plus",
  "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"
    }
  ]
}'
```

````
To read a JSON file in Python, you can use the built-in **`json`** module. Specifically, you will use the **`json.load()`** function, which reads a JSON file and converts it into a Python dictionary or list.

Here is the standard and safest way to do it:

### Basic Example

```python
import json

# Open the file and load its contents
with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)

# Now 'data' is a Python dictionary (or list)
print(data)
```

### How it works:
1. **`import json`**: Imports Python's built-in JSON library.
2. **`with open(...) as file:`**: Opens the file in read mode (`'r'`). Using the `with` statement is a best practice because it automatically closes the file for you when the block of code is finished, even if an error occurs.
3. **`encoding='utf-8'`**: It is highly recommended to specify UTF-8 encoding, as JSON files are typically encoded this way.
4. **`json.load(file)`**: Parses the JSON data from the file object and converts it into native Python data types (JSON objects become Python dictionaries, JSON arrays become Python lists, etc.).

---

### Best Practice: Adding Error Handling
When reading files, things can go wrong (the file might not exist, or it might contain invalid JSON). It's a good idea to handle these exceptions:

```python
import json

try:
    with open('data.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
        print(data)
        
except FileNotFoundError:
    print("Error: The file was not found.")
except json.JSONDecodeError:
    print("Error: The file does not contain valid JSON.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
```

---

### Quick Tip: `load()` vs `loads()`
* **`json.load()`** (no "s"): Reads JSON data directly from a **file**.
* **`json.loads()`** (with an "s" for "string"): Reads JSON data from a **string** or bytes object. 

*(Example: `data = json.loads('{"name": "Alice"}')`)*
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "To read a JSON file in Python, you can use the built-in **`json`** module. Specifically, you will use the **`json.load()`** function, which reads a JSON file and converts it into a Python dictionary or list.\n\nHere is the standard and safest way to do it:\n\n### Basic Example\n\n```python\nimport json\n\n# Open the file and load its contents\nwith open('data.json', 'r', encoding='utf-8') as file:\n    data = json.load(file)\n\n# Now 'data' is a Python dictionary (or list)\nprint(data)\n```\n\n### How it works:\n1. **`import json`**: Imports Python's built-in JSON library.\n2. **`with open(...) as file:`**: Opens the file in read mode (`'r'`). Using the `with` statement is a best practice because it automatically closes the file for you when the block of code is finished, even if an error occurs.\n3. **`encoding='utf-8'`**: It is highly recommended to specify UTF-8 encoding, as JSON files are typically encoded this way.\n4. **`json.load(file)`**: Parses the JSON data from the file object and converts it into native Python data types (JSON objects become Python dictionaries, JSON arrays become Python lists, etc.).\n\n---\n\n### Best Practice: Adding Error Handling\nWhen reading files, things can go wrong (the file might not exist, or it might contain invalid JSON). It's a good idea to handle these exceptions:\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r', encoding='utf-8') as file:\n        data = json.load(file)\n        print(data)\n        \nexcept FileNotFoundError:\n    print(\"Error: The file was not found.\")\nexcept json.JSONDecodeError:\n    print(\"Error: The file does not contain valid JSON.\")\nexcept Exception as e:\n    print(f\"An unexpected error occurred: {e}\")\n```\n\n---\n\n### Quick Tip: `load()` vs `loads()`\n* **`json.load()`** (no \"s\"): Reads JSON data directly from a **file**.\n* **`json.loads()`** (with an \"s\" for \"string\"): Reads JSON data from a **string** or bytes object. \n\n*(Example: `data = json.loads('{\"name\": \"Alice\"}')`)*",
        "reasoning_content": "Thinking Process:\n\n1.  **Understand the User's Goal:** The user wants to know how to read a JSON file using Python.\n2.  **Identify the Core Tool:** The standard library module for handling JSON in Python is `json`. Specifically, the `json.load()` function is used to read JSON data from a file.\n3.  **Formulate the Solution:**\n    *   Import the `json` module.\n    *   Open the file using the `open()` function (preferably using a `with` statement for safe file handling).\n    *   Use `json.load()` to parse the JSON content into a Python dictionary (or list, depending on the JSON structure).\n4.  **Draft the Code Example:**\n    ```python\n    import json\n\n    with open('data.json', 'r') as file:\n        data = json.load(file)\n        print(data)\n    ```\n5.  **Add Context and Best Practices:**\n    *   Explain what `json.load()` does (converts JSON to Python dict/list).\n    *   Mention the `with` statement (ensures the file is properly closed).\n    *   Briefly mention error handling (e.g., `FileNotFoundError`, `json.JSONDecodeError`) as it's highly recommended for robust code.\n    *   Distinguish between `json.load()` (for files) and `json.loads()` (for strings), as this is a common point of confusion.\n6.  **Review and Refine:**\n    *   *Self-Correction during drafting:* Make sure to specify the encoding, usually `utf-8`, when opening files, as JSON is typically UTF-8.\n    *   *Updated Code:* `open('data.json', 'r', encoding='utf-8')`\n7.  **Final Output Generation:** (Structure the response clearly with a basic example, explanation, and advanced/best practice tips). Keep it concise but comprehensive. Provide a sample JSON file content so the user can visualize it.\n\n*Plan:*\n- Direct answer with the standard `json` module.\n- Code snippet showing the basic usage.\n- Explanation of the key components (`with open`, `json.load`).\n- Code snippet showing error handling (best practice).\n- Quick tip on `load` vs `loads`.\n- Example JSON data for context. \n*Execution.* \n*End of thought process.*",
        "role": "assistant"
      }
    }
  ],
  "created": 1785165338,
  "id": "chatcmpl-793351f2-4078-932e-b20b-4d495b52f9d3",
  "model": "qwen3.7-plus",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 1024,
    "completion_tokens_details": {
      "reasoning_tokens": 510,
      "text_tokens": 1024
    },
    "prompt_tokens": 35,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "text_tokens": 35
    },
    "total_tokens": 1059
  }
}
```

</details>

<details>

<summary>**Vision: Image Understanding** — Describing the contents of an image</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.7-plus',
  {
    messages: [
      {
        content: [
          {
            image_url: {
              url: 'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg',
            },
            type: 'image_url',
          },
          { text: 'What is depicted in the image?', type: 'text' },
        ],
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.7-plus",
  "messages": [
    {
      "content": [
        {
          "image_url": {
            "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
          },
          "type": "image_url"
        },
        {
          "text": "What is depicted in the image?",
          "type": "text"
        }
      ],
      "role": "user"
    }
  ]
}'
```

```
This image depicts a heartwarming scene of a young woman and her dog interacting on a sandy beach, likely during sunset or sunrise given the warm, golden lighting.

Here are the specific details:

*   **The Subjects:** A young woman with long dark hair is sitting on the sand, wearing a blue and white plaid shirt and dark pants. She is smiling happily at a large, light-colored dog (appearing to be a Golden Retriever or Labrador).
*   **The Action:** The dog is sitting facing the woman and has lifted its front paw to touch her hand. They appear to be doing a "high five" or a "shake" trick. The woman is holding the dog's paw with one hand and seems to be holding a treat in the other.
*   **The Setting:** They are on a beach with textured sand full of footprints. In the background, the ocean stretches out to the horizon with gentle waves rolling in. The sky is bright and hazy, suggesting the sun is low on the horizon, creating a lens flare effect on the right side of the image.
*   **Accessories:** The dog is wearing a blue harness with a colorful pattern, and a red rope leash is lying on the sand next to it. The woman is wearing a white watch.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "This image depicts a heartwarming scene of a young woman and her dog interacting on a sandy beach, likely during sunset or sunrise given the warm, golden lighting.\n\nHere are the specific details:\n\n*   **The Subjects:** A young woman with long dark hair is sitting on the sand, wearing a blue and white plaid shirt and dark pants. She is smiling happily at a large, light-colored dog (appearing to be a Golden Retriever or Labrador).\n*   **The Action:** The dog is sitting facing the woman and has lifted its front paw to touch her hand. They appear to be doing a \"high five\" or a \"shake\" trick. The woman is holding the dog's paw with one hand and seems to be holding a treat in the other.\n*   **The Setting:** They are on a beach with textured sand full of footprints. In the background, the ocean stretches out to the horizon with gentle waves rolling in. The sky is bright and hazy, suggesting the sun is low on the horizon, creating a lens flare effect on the right side of the image.\n*   **Accessories:** The dog is wearing a blue harness with a colorful pattern, and a red rope leash is lying on the sand next to it. The woman is wearing a white watch.",
        "reasoning_content": "The user wants a description of the image.\n\n1.  **Identify the main subjects:** A woman and a dog.\n2.  **Identify the setting:** A beach with sand and the ocean in the background. The lighting suggests sunset or sunrise (golden hour).\n3.  **Describe the action:** The woman is sitting on the sand. The dog is sitting facing her. They are doing a \"high five\" or shaking hands. The dog has its paw raised, and the woman is holding it.\n4.  **Describe the subjects in detail:**\n    *   **Woman:** Long dark hair, wearing a plaid shirt (blue/white/black check), dark pants (rolled up), smiling, looking at the dog. She has a watch on her wrist.\n    *   **Dog:** Looks like a Golden Retriever or Labrador Retriever (light golden fur). It's wearing a harness (blue with colorful patterns) and a leash is attached (red rope). It's sitting on its haunches.\n5.  **Describe the background/environment:** Sandy beach with footprints. Ocean waves in the background. The sky is bright, suggesting early morning or late afternoon sun. There's a lens flare or sun glare on the right side.\n6.  **Synthesize the description:** Combine these elements into a coherent paragraph. Start with the main action, then add details about the subjects and the setting.\n\n*Drafting the description:*\nThe image shows a woman and a dog on a beach. The woman is sitting on the sand, wearing a plaid shirt. The dog is a golden retriever or lab. They are shaking hands/high-fiving. The sun is setting or rising, creating a warm glow. The ocean is in the background.\n\n*Refining the description:*\nThis is a heartwarming photo of a young woman and her dog interacting on a sandy beach.\n- **The Woman:** She is sitting cross-legged or with legs bent on the sand, facing left. She has long brown hair and is wearing a blue and white plaid flannel shirt over dark pants. She is smiling broadly at the dog.\n- **The Dog:** It looks like a yellow Labrador or Golden Retriever. It is sitting facing the woman. It is wearing a colorful harness. The dog has lifted its front right paw to touch the woman's hand, performing a \"high five\" or \"shake\" trick.\n- **The Setting:** They are on a beach with textured sand. In the background, there is the ocean with small waves rolling in. The lighting is soft and warm, likely from a sunset or sunrise, with a bright flare coming from the right side of the frame.\n- **Details:** There is a red leash lying on the sand near the dog.\n\n*Final Polish:* Structure the answer clearly. Start with a general overview, then break down the details.",
        "role": "assistant"
      }
    }
  ],
  "created": 1785165357,
  "id": "chatcmpl-6856ed0e-4b37-9fd3-ae85-7d106cc018bd",
  "model": "qwen3.7-plus",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 874,
    "completion_tokens_details": {
      "reasoning_tokens": 602,
      "text_tokens": 272
    },
    "prompt_tokens": 2520,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "image_tokens": 2503,
      "text_tokens": 17
    },
    "total_tokens": 3394
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.7-plus',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.7-plus",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
At its core, **recursion** is a programming concept where a function calls *itself* in order to solve a problem. 

Instead of attacking a massive problem all at once, recursion breaks the problem down into smaller, simpler versions of the *exact same problem*, until it reaches a point that is easy to solve.

To understand it, let's look at a real-world analogy, followed by a simple coding example.

---

### The Real-World Analogy: The Line
Imagine you are standing in a long line, and you want to know what number you are in the line. 

Instead of counting everyone from the front, you use **recursion**:
1. **The Recursive Step:** You tap the person in front of you and ask, *"What number are you in the line?"*
2. That person doesn't know either, so they tap the person in front of *them* and ask the same question.
3. This continues down the line until it reaches the very first person.
4. **The Base Case:** The first person knows exactly where they are. They say, *"I am number 1."* They don't ask anyone else.
5. The answer gets passed back down the line. The second person adds 1 (so they are 2), the third person adds 1 (they are 3), and so on, until the answer finally reaches you.

In programming, the **Base Case** is the condition that tells the function to stop calling itself (the person at the front of the line). Without a base case, the function would loop forever!

---

### The Coding Example: Factorial
The most classic example of recursion is calculating a **factorial**. 
The factorial of 3 (written as `3!`) means multiplying 3 by every whole number below it: 
**`3! = 3 × 2 × 1 = 6`**

Here is how we write that using recursion in Python:

```python
def factorial(n):
    # 1. The Base Case (When do we stop?)
    if n == 1:
        return 1
    
    # 2. The Recursive Case (The function calls itself)
    else:
        return n * factorial(n - 1)
```

### How it works step-by-step
Let's trace what happens when we ask the computer for `factorial(3)`:

**Phase 1: The Calls (Going down the line)**
* `factorial(3)` sees that `n` is not 1. It returns `3 * factorial(2)`. *(Wait, we need to know what factorial(2) is!)*
* `factorial(2)` sees that `n` is not 1. It returns `2 * factorial(1)`. *(Wait, we need to know what factorial(1) is!)*
* `factorial(1)` hits the **Base Case**. It simply returns `1`.

**Phase 2: The Returns (Passing the answer back up the line)**
* Now the computer replaces `factorial(1)` with `1`. 
  * The previous step was `2 * factorial(1)`, which becomes `2 * 1 = 2`.
* Now the computer replaces `factorial(2)` with `2`.
  * The very first step was `3 * factorial(2)`, which becomes `3 * 2 = 6`.

The final answer is **6**.

---

### The Two Golden Rules of Recursion
Every recursive function **must** have these two parts, or your program will crash (usually resulting in a "Stack Overflow" error):
1. **The Base Case:** The condition where the function stops calling itself (e.g., `if n == 1`).
2. **The Recursive Case:** The part where the function calls itself, but with a modified input that moves *closer* to the base case (e.g., `n - 1`).

### Why use it?
While a simple `for` loop can calculate a factorial, recursion is incredibly powerful for problems that involve branching structures, like navigating through folders on your computer, searching through a family tree, or sorting complex data. It allows you to write clean, elegant code for problems that would otherwise require massive, confusing loops.
````

```json
[
  {
    "model": "qwen3.7-plus",
    "id": "chatcmpl-29158f9e-a9f4-9c08-9d9e-96bc58a68c5e",
    "created": 1785165376,
    "object": "chat.completion.chunk",
    "usage": null,
    "choices": [
      {
        "logprobs": null,
        "index": 0,
        "delta": {
          "content": "",
          "role": "assistant",
          "reasoning_content": ""
        },
        "finish_reason": null
      }
    ]
  },
  {
    "model": "qwen3.7-plus",
    "id": "chatcmpl-29158f9e-a9f4-9c08-9d9e-96bc58a68c5e",
    "choices": [
      {
        "delta": {
          "content": "",
          "reasoning_content": "Here"
        },
        "index": 0,
        "finish_reason": null,
        "logprobs": null
      }
    ],
    "created": 1785165376,
    "object": "chat.completion.chunk",
    "usage": null
  },
  "... 598 more chunks omitted ...",
  {
    "choices": [],
    "created": 1785165376,
    "id": "chatcmpl-29158f9e-a9f4-9c08-9d9e-96bc58a68c5e",
    "model": "qwen3.7-plus",
    "object": "chat.completion.chunk",
    "usage": {
      "completion_tokens": 2114,
      "completion_tokens_details": {
        "reasoning_tokens": 1194,
        "text_tokens": 2114
      },
      "prompt_tokens": 21,
      "prompt_tokens_details": {
        "cached_tokens": 0,
        "text_tokens": 21
      },
      "total_tokens": 2135
    }
  }
]
```

</details>

## Parameters

Schema variant

Chat CompletionsResponses

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-plus/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-plus/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-plus/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-plus/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-plus/#page","headline":"Qwen 3.7 Plus","description":"Alibaba's Qwen 3.7 Plus is the cost-effective member of the Qwen3.7 series, pairing strong text capabilities with image and video understanding and full-stack agent-level intelligence for coding, tool use, and GUI-based automation, served via DashScope's OpenAI-compatible endpoint.","url":"https://developers.cloudflare.com/ai/models/alibaba/qwen3.7-plus/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's Qwen 3.8 Max is a 2.4-trillion-parameter MoE flagship built for professional-grade coding and long-horizon autonomous work, capable of delivering complete, production-grade projects spanning 10+ days across legal, financial, design, and other specialized domains. Native visual understanding of images and extended video runs through the full plan-execute-verify cycle, served via DashScope's OpenAI-compatible endpoint.
title: Qwen 3.8 Max
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# Qwen 3.8 Max

Text Generation • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/qwen3.8-max/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/qwen3.8-max`

- Third-party

Alibaba's Qwen 3.8 Max is a 2.4-trillion-parameter MoE flagship built for professional-grade coding and long-horizon autonomous work, capable of delivering complete, production-grade projects spanning 10+ days across legal, financial, design, and other specialized domains. Native visual understanding of images and extended video runs through the full plan-execute-verify cycle, served via DashScope's OpenAI-compatible endpoint.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://www.qwencloud.com/models/qwen3.8-max) |
| Request formats | Chat Completions, Responses |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Output (per 1M tokens)$6.00</li><li>Cached input (per 1M tokens)$0.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/qwen3.8-max',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.8-max",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The three main laws of thermodynamics are:

1. **First Law — Conservation of Energy**  
   Energy cannot be created or destroyed; it can only be transferred or converted from one form to another.  
   In equation form:  
   \[
   \Delta U = Q - W
   \]  
   where \(\Delta U\) is the change in internal energy, \(Q\) is heat added to the system, and \(W\) is work done by the system.

2. **Second Law — Entropy Increases**  
   In any natural process, the total entropy of an isolated system tends to increase.  
   In simpler terms, energy naturally spreads out, and processes have a preferred direction—heat flows from hot to cold, not the reverse, without external work.

3. **Third Law — Absolute Zero Limit**  
   As the temperature of a system approaches absolute zero, its entropy approaches a minimum value.  
   It is impossible to reach absolute zero in a finite number of steps.

There is also a **Zeroth Law**, which says that if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This law establishes the concept of temperature.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "The three main laws of thermodynamics are:\n\n1. **First Law — Conservation of Energy**  \n   Energy cannot be created or destroyed; it can only be transferred or converted from one form to another.  \n   In equation form:  \n   \\[\n   \\Delta U = Q - W\n   \\]  \n   where \\(\\Delta U\\) is the change in internal energy, \\(Q\\) is heat added to the system, and \\(W\\) is work done by the system.\n\n2. **Second Law — Entropy Increases**  \n   In any natural process, the total entropy of an isolated system tends to increase.  \n   In simpler terms, energy naturally spreads out, and processes have a preferred direction—heat flows from hot to cold, not the reverse, without external work.\n\n3. **Third Law — Absolute Zero Limit**  \n   As the temperature of a system approaches absolute zero, its entropy approaches a minimum value.  \n   It is impossible to reach absolute zero in a finite number of steps.\n\nThere is also a **Zeroth Law**, which says that if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This law establishes the concept of temperature.",
        "reasoning_content": "We need answer user: \"What are the three laws of thermodynamics?\" Need likely mention there are four including zeroth? User asks three laws, likely first, second, third. Could also include zeroth? Need answer succinctly but detailed. Need final. Make sure not claim only three if common includes zeroth. Could say traditionally the “three laws” are first, second, third; there's also zeroth. Explain. Need maybe avoid too much. Final with bullet points.",
        "role": "assistant"
      }
    }
  ],
  "created": 1786048647,
  "id": "chatcmpl-2b915318-d6f0-9bab-88a6-504a5113fbc3",
  "model": "qwen3.8-max",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 356,
    "completion_tokens_details": {
      "reasoning_tokens": 99,
      "text_tokens": 356
    },
    "prompt_tokens": 57,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "text_tokens": 57
    },
    "total_tokens": 413
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.8-max',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.8-max",
  "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"
    }
  ]
}'
```

````
Use Python’s built-in `json` module:

```python
import json

with open("data.json", "r") as file:
    data = json.load(file)

print(data)
```

`data` will usually be a Python `dict` or `list`, depending on the JSON file.

If the JSON is a string instead of a file, use:

```python
import json

data = json.loads('{"name": "Alice"}')
```
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "Use Python’s built-in `json` module:\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\") as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n`data` will usually be a Python `dict` or `list`, depending on the JSON file.\n\nIf the JSON is a string instead of a file, use:\n\n```python\nimport json\n\ndata = json.loads('{\"name\": \"Alice\"}')\n```",
        "reasoning_content": "We need to answer user's simple question: \"How do I read a JSON file in Python?\" Need produce final. Need maybe include code using json.load, with open. Mention json.loads for string. Ensure helpful. No need overdo.",
        "role": "assistant"
      }
    }
  ],
  "created": 1786048656,
  "id": "chatcmpl-7d75d520-ba7c-98ac-bb93-3122e0d2ef4b",
  "model": "qwen3.8-max",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 154,
    "completion_tokens_details": {
      "reasoning_tokens": 49,
      "text_tokens": 154
    },
    "prompt_tokens": 73,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "text_tokens": 73
    },
    "total_tokens": 227
  }
}
```

</details>

<details>

<summary>**Vision: Image Understanding** — Describing the contents of an image</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.8-max',
  {
    messages: [
      {
        content: [
          {
            image_url: {
              url: 'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg',
            },
            type: 'image_url',
          },
          { text: 'What is depicted in the image?', type: 'text' },
        ],
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.8-max",
  "messages": [
    {
      "content": [
        {
          "image_url": {
            "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
          },
          "type": "image_url"
        },
        {
          "text": "What is depicted in the image?",
          "type": "text"
        }
      ],
      "role": "user"
    }
  ]
}'
```

```
The image shows a heartwarming beach scene at what appears to be sunset (golden hour). A young woman with long dark hair is sitting barefoot on the sand, wearing a black-and-white plaid flannel shirt and dark pants. She's smiling as she gives a "high five" to a yellow Labrador Retriever sitting opposite her—the dog has raised its paw to meet her open hand. In her other hand, she seems to be holding a small treat, suggesting a training or play moment.

Other details include:

- **The dog** is wearing a harness decorated with colorful paw prints, with a red leash trailing onto the sand.
- **The setting** is a sandy beach with the ocean and a breaking wave visible in the background.
- **The lighting** is soft and warm, with the sun creating a golden glow and slight lens flare on the right side, giving the scene a peaceful, affectionate mood.

Overall, it depicts the bond between a person and her dog during a playful, tender moment by the sea.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "The image shows a heartwarming beach scene at what appears to be sunset (golden hour). A young woman with long dark hair is sitting barefoot on the sand, wearing a black-and-white plaid flannel shirt and dark pants. She's smiling as she gives a \"high five\" to a yellow Labrador Retriever sitting opposite her—the dog has raised its paw to meet her open hand. In her other hand, she seems to be holding a small treat, suggesting a training or play moment.\n\nOther details include:\n\n- **The dog** is wearing a harness decorated with colorful paw prints, with a red leash trailing onto the sand.\n- **The setting** is a sandy beach with the ocean and a breaking wave visible in the background.\n- **The lighting** is soft and warm, with the sun creating a golden glow and slight lens flare on the right side, giving the scene a peaceful, affectionate mood.\n\nOverall, it depicts the bond between a person and her dog during a playful, tender moment by the sea.",
        "reasoning_content": "The user is asking me to describe what's shown in the image. Let me look at the image carefully.\n\nThe image shows a beach scene, and from the quality of the light it seems to be sunset or sunrise (golden hour). A young woman with long black hair is sitting on the sand, wearing a checkered (plaid) shirt and dark-colored pants/jeans, barefoot. She's smiling and appears to be doing a \"high five\" or \"shake hands\" with a dog—looks like a yellow/golden Labrador Retriever. The dog is sitting on the sand, lifting its front paw and placing it on the woman's hand. The dog is wearing a harness with a colorful pattern (looks like a paw print pattern), and a red leash is attached, dangling onto the sand.\n\nIn the background, you can see the sea with waves breaking, and the sky is bright and hazy, with warm sunlight streaming in from the right side of the image, creating a lens flare effect.\n\nThe scene depicts the bond between the woman and the dog, probably a training moment (the dog is doing a \"high five\" trick), and the woman might be holding a treat in her other hand.\n\nI should describe this clearly and concisely. Let me make it a friendly, descriptive response. No special instructions, just answer the question. Let me describe the main elements:\n\n- A woman sitting on a sandy beach\n- A Labrador Retriever dog\n- The two are doing a high five / shaking hands\n- Sunset/golden hour light\n- Ocean waves in the background\n- The dog is wearing a harness with a leash\n- The woman is smiling, wearing a plaid shirt, barefoot\n- She might be holding a treat\n\nFormat: A short descriptive paragraph is appropriate. No tools needed. It should be concise but complete. A medium-length paragraph should be fine. Let me try writing it.",
        "role": "assistant"
      }
    }
  ],
  "created": 1786048660,
  "id": "chatcmpl-8a8cec83-a8e2-9d27-9f9b-102906147b5c",
  "model": "qwen3.8-max",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 618,
    "completion_tokens_details": {
      "reasoning_tokens": 400,
      "text_tokens": 218
    },
    "prompt_tokens": 2520,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "image_tokens": 2503,
      "text_tokens": 17
    },
    "total_tokens": 3138
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'alibaba/qwen3.8-max',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/qwen3.8-max",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
Recursion is a way of solving a problem where a function calls itself to solve smaller versions of the same problem.

A recursive function usually has two parts:

1. **Base case** — when to stop  
2. **Recursive case** — calling itself with a smaller input

Example: calculating `3!` factorial.

```python
def factorial(n):
    if n == 1:          # base case
        return 1
    else:
        return n * factorial(n - 1)  # recursive case
```

Calling:

```python
print(factorial(3))
```

This works like:

```python
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1
```

So:

```python
3 * 2 * 1 = 6
```

Recursion is useful when a problem can be broken into smaller repeated subproblems.
````

```json
[
  {
    "model": "qwen3.8-max",
    "id": "chatcmpl-93de192c-09a4-9b99-8c9a-55f6302cc5c5",
    "created": 1786048673,
    "object": "chat.completion.chunk",
    "usage": null,
    "choices": [
      {
        "logprobs": null,
        "index": 0,
        "delta": {
          "content": "",
          "role": "assistant",
          "reasoning_content": ""
        },
        "finish_reason": null
      }
    ]
  },
  {
    "model": "qwen3.8-max",
    "id": "chatcmpl-93de192c-09a4-9b99-8c9a-55f6302cc5c5",
    "choices": [
      {
        "delta": {
          "content": "",
          "reasoning_content": "We"
        },
        "index": 0,
        "finish_reason": null,
        "logprobs": null
      }
    ],
    "created": 1786048673,
    "object": "chat.completion.chunk",
    "usage": null
  },
  "... 73 more chunks omitted ...",
  {
    "choices": [],
    "created": 1786048673,
    "id": "chatcmpl-93de192c-09a4-9b99-8c9a-55f6302cc5c5",
    "model": "qwen3.8-max",
    "object": "chat.completion.chunk",
    "usage": {
      "completion_tokens": 263,
      "completion_tokens_details": {
        "reasoning_tokens": 47,
        "text_tokens": 263
      },
      "prompt_tokens": 59,
      "prompt_tokens_details": {
        "cached_tokens": 0,
        "text_tokens": 59
      },
      "total_tokens": 322
    }
  }
]
```

</details>

## Parameters

Schema variant

Chat CompletionsResponses

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen3.8-max/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen3.8-max/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/qwen3.8-max/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/qwen3.8-max/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/qwen3.8-max/#page","headline":"Qwen 3.8 Max","description":"Alibaba's Qwen 3.8 Max is a 2.4-trillion-parameter MoE flagship built for professional-grade coding and long-horizon autonomous work, capable of delivering complete, production-grade projects spanning 10+ days across legal, financial, design, and other specialized domains. Native visual understanding of images and extended video runs through the full plan-execute-verify cycle, served via DashScope's OpenAI-compatible endpoint.","url":"https://developers.cloudflare.com/ai/models/alibaba/qwen3.8-max/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's Wan 2.6 text-to-image model generating images from text prompts with optional negative prompts and customizable dimensions.
title: Wan 2.6 Image
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# Wan 2.6 Image

Text-to-Image • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/wan-2.6-image/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/wan-2.6-image`

- Third-party
- Zero data retention

Alibaba's Wan 2.6 text-to-image model generating images from text prompts with optional negative prompts and customizable dimensions.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://wan.video/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.03</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/wan-2.6-image',
  { prompt: 'A golden retriever puppy playing in autumn leaves' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/wan-2.6-image",
  "input": {
    "prompt": "A golden retriever puppy playing in autumn leaves"
  }
}'
```

![Simple Generation](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/alibaba__wan-2.6-image/simple-generation.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://dashscope-463f.oss-accelerate.aliyuncs.com/1d/66/20260417/c057796c/32701268-BbftSa6r_189314ac1a36.png"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Custom Dimensions** — Specify image size in WxH format</summary>



```ts
const response = await env.AI.run(
  'alibaba/wan-2.6-image',
  {
    prompt:
      'A vast alien desert landscape with two suns setting on the horizon, ancient ruins in the foreground',
    size: '1024x768',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/wan-2.6-image",
  "input": {
    "prompt": "A vast alien desert landscape with two suns setting on the horizon, ancient ruins in the foreground",
    "size": "1024x768"
  }
}'
```

![Custom Dimensions](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/alibaba__wan-2.6-image/custom-dimensions.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://dashscope-463f.oss-accelerate.aliyuncs.com/1d/35/20260417/c057796c/3257252-vy1GbNI6_bc223e38c5b4.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Square Format** — Square image for social media or product photos</summary>



```ts
const response = await env.AI.run(
  'alibaba/wan-2.6-image',
  {
    prompt:
      'A sleek wireless headphone on a minimalist white marble surface with soft studio lighting',
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/wan-2.6-image",
  "input": {
    "prompt": "A sleek wireless headphone on a minimalist white marble surface with soft studio lighting",
    "size": "1024x1024"
  }
}'
```

![Square Format](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/alibaba__wan-2.6-image/square-format.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://dashscope-463f.oss-accelerate.aliyuncs.com/1d/84/20260417/c057796c/18355039-RFkWcHgG_0dcb1c1d6d95.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Negative Prompt** — Guide generation away from unwanted elements</summary>



```ts
const response = await env.AI.run(
  'alibaba/wan-2.6-image',
  {
    prompt: 'A detailed oil painting portrait of a Renaissance nobleman with intricate lace collar',
    negative_prompt: 'modern clothing, photograph, blurry, low quality',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/wan-2.6-image",
  "input": {
    "prompt": "A detailed oil painting portrait of a Renaissance nobleman with intricate lace collar",
    "negative_prompt": "modern clothing, photograph, blurry, low quality"
  }
}'
```

![Negative Prompt](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/alibaba__wan-2.6-image/negative-prompt.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://dashscope-463f.oss-accelerate.aliyuncs.com/1d/53/20260417/c057796c/26097304-eVhNm6uS_edc041cd5e2b.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Portrait Format** — Tall vertical image for portraits</summary>



```ts
const response = await env.AI.run(
  'alibaba/wan-2.6-image',
  {
    prompt: 'An elegant Art Deco poster featuring a jazz singer under a spotlight',
    size: '768x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/wan-2.6-image",
  "input": {
    "prompt": "An elegant Art Deco poster featuring a jazz singer under a spotlight",
    "size": "768x1024"
  }
}'
```

![Portrait Format](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/alibaba__wan-2.6-image/portrait-format.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://dashscope-463f.oss-accelerate.aliyuncs.com/1d/5a/20260417/c057796c/79957405-YTXQsRY6_8d8a6631f1d6.png"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`pattern: ^\\d+x\\d+$

negative\_prompt

`string`

image

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/wan-2.6-image/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/wan-2.6-image/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/wan-2.6-image/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/wan-2.6-image/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/wan-2.6-image/#page","headline":"Wan 2.6 Image","description":"Alibaba's Wan 2.6 text-to-image model generating images from text prompts with optional negative prompts and customizable dimensions.","url":"https://developers.cloudflare.com/ai/models/alibaba/wan-2.6-image/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's Wan 2.7 image-to-video model that generates videos from a reference image with optional text prompts. Supports 720P and 1080P output with durations from 2 to 15 seconds.
title: Wan 2.7 I2V
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# Wan 2.7 I2V

Image-to-Video • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/wan-2.7-i2v/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/wan-2.7-i2v`

- Third-party
- Zero data retention

Alibaba's Wan 2.7 image-to-video model that generates videos from a reference image with optional text prompts. Supports 720P and 1080P output with durations from 2 to 15 seconds.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://wan.video/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.10</li><li>@720p (per second)$0.10</li><li>@1080p (per second)$0.15</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/wan-2.7-i2v',
  {
    image:
      'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png',
    prompt: 'A gentle camera push-in on the scene with soft ambient lighting',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/wan-2.7-i2v",
  "input": {
    "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png",
    "prompt": "A gentle camera push-in on the scene with soft ambient lighting"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/alibaba/wan-2.7-i2v/simple-image-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**High Resolution** — Generate at 1080P with a longer duration</summary>



```ts
const response = await env.AI.run(
  'alibaba/wan-2.7-i2v',
  {
    image:
      'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png',
    prompt: 'Subject begins rapping confidently, head bobbing to the beat',
    duration: 10,
    resolution: '1080P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/wan-2.7-i2v",
  "input": {
    "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png",
    "prompt": "Subject begins rapping confidently, head bobbing to the beat",
    "duration": 10,
    "resolution": "1080P"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/alibaba/wan-2.7-i2v/high-resolution.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**With Negative Prompt** — Guide generation away from unwanted artifacts</summary>



```ts
const response = await env.AI.run(
  'alibaba/wan-2.7-i2v',
  {
    image:
      'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png',
    prompt: 'Subject slowly turns their head and smiles',
    duration: 5,
    negative_prompt: 'blurry, distorted face, extra limbs',
    resolution: '720P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/wan-2.7-i2v",
  "input": {
    "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png",
    "prompt": "Subject slowly turns their head and smiles",
    "duration": 5,
    "negative_prompt": "blurry, distorted face, extra limbs",
    "resolution": "720P"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/alibaba/wan-2.7-i2v/with-negative-prompt.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Reproducible Output** — Use a fixed seed for reproducibility</summary>



```ts
const response = await env.AI.run(
  'alibaba/wan-2.7-i2v',
  {
    image:
      'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png',
    prompt: 'Camera orbits slowly around the subject under streetlamp light',
    duration: 8,
    resolution: '720P',
    seed: 42,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/wan-2.7-i2v",
  "input": {
    "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/wpimhv/rap.png",
    "prompt": "Camera orbits slowly around the subject under streetlamp light",
    "duration": 8,
    "resolution": "720P",
    "seed": 42
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/alibaba/wan-2.7-i2v/reproducible-output.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

image

`string`requiredformat: uri

prompt

`string`

negative\_prompt

`string`

resolution

`string`enum: 720P, 1080P

duration

`integer`minimum: 2maximum: 15

seed

`integer`minimum: 0maximum: 2147483647

watermark

`boolean`

video

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/wan-2.7-i2v/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/wan-2.7-i2v/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/wan-2.7-i2v/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/wan-2.7-i2v/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/wan-2.7-i2v/#page","headline":"Wan 2.7 I2V","description":"Alibaba's Wan 2.7 image-to-video model that generates videos from a reference image with optional text prompts. Supports 720P and 1080P output with durations from 2 to 15 seconds.","url":"https://developers.cloudflare.com/ai/models/alibaba/wan-2.7-i2v/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's Wan 3.0 text-to-video model. Generates cinematic videos from text prompts with adaptive aspect ratio, 480P, 720P, or 1080P resolution, and configurable duration.
title: Wan 3.0 Video
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# Wan 3.0 Video

Text-to-Video • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/wan-3.0`

- Third-party

Alibaba's Wan 3.0 text-to-video model. Generates cinematic videos from text prompts with adaptive aspect ratio, 480P, 720P, or 1080P resolution, and configurable duration.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://www.alibabacloud.com/help/en/model-studio/models) |
| Pricing | <ul><li>Default (per second)$0.05</li><li>@480p (per second)$0.05</li><li>@720p (per second)$0.10</li><li>@1080p (per second)$0.20</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/wan-3.0',
  {
    prompt:
      'A kitten running across a rooftop under the moonlight, city neon lights flickering in the distance, cinematic quality, smooth camera movement.',
    resolution: '480P',
    ratio: 'adaptive',
    duration: 5,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/wan-3.0",
  "input": {
    "prompt": "A kitten running across a rooftop under the moonlight, city neon lights flickering in the distance, cinematic quality, smooth camera movement.",
    "resolution": "480P",
    "ratio": "adaptive",
    "duration": 5
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/alibaba/wan-3.0/adaptive-480p-text-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

prompt

`string`requiredminLength: 1maxLength: 2500

resolution

`string`enum: 480P, 720P, 1080P

ratio

`string`enum: adaptive, 16:9, 9:16, 1:1, 4:3, 3:4

duration

`integer`minimum: 1maximum: 15

video

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/wan-3.0/#page","headline":"Wan 3.0 Video","description":"Alibaba's Wan 3.0 text-to-video model. Generates cinematic videos from text prompts with adaptive aspect ratio, 480P, 720P, or 1080P resolution, and configurable duration.","url":"https://developers.cloudflare.com/ai/models/alibaba/wan-3.0/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Alibaba's Wan 3.0 Prime text-to-video model. Generates cinematic videos from text prompts with adaptive aspect ratio, 480P, 720P, or 1080P resolution, and configurable duration.
title: Wan 3.0 Prime Video
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Alibaba logo](https://developers.cloudflare.com/_astro/alibaba.BK31NAJz.svg)

# Wan 3.0 Prime Video

Text-to-Video • Alibaba

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0-prime/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`alibaba/wan-3.0-prime`

- Third-party

Alibaba's Wan 3.0 Prime text-to-video model. Generates cinematic videos from text prompts with adaptive aspect ratio, 480P, 720P, or 1080P resolution, and configurable duration.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.alibabacloud.com/help/en/legal) |
| More information | [link ↗](https://www.alibabacloud.com/help/en/model-studio/models) |
| Pricing | <ul><li>Default (per second)$0.068</li><li>@480p (per second)$0.068</li><li>@720p (per second)$0.14</li><li>@1080p (per second)$0.28</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'alibaba/wan-3.0-prime',
  {
    prompt:
      'A kitten running across a rooftop under the moonlight, city neon lights flickering in the distance, cinematic quality, smooth camera movement.',
    resolution: '480P',
    ratio: 'adaptive',
    duration: 5,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "alibaba/wan-3.0-prime",
  "input": {
    "prompt": "A kitten running across a rooftop under the moonlight, city neon lights flickering in the distance, cinematic quality, smooth camera movement.",
    "resolution": "480P",
    "ratio": "adaptive",
    "duration": 5
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/alibaba/wan-3.0-prime/adaptive-480p-text-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

prompt

`string`requiredminLength: 1maxLength: 2500

resolution

`string`enum: 480P, 720P, 1080P

ratio

`string`enum: adaptive, 16:9, 9:16, 1:1, 4:3, 3:4

duration

`integer`minimum: 1maximum: 15

video

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0-prime/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0-prime/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0-prime/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/alibaba/wan-3.0-prime/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/alibaba/wan-3.0-prime/#page","headline":"Wan 3.0 Prime Video","description":"Alibaba's Wan 3.0 Prime text-to-video model. Generates cinematic videos from text prompts with adaptive aspect ratio, 480P, 720P, or 1080P resolution, and configurable duration.","url":"https://developers.cloudflare.com/ai/models/alibaba/wan-3.0-prime/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Fable 5 is Anthropic's most capable widely released model, built for the most demanding reasoning and long-horizon agentic work. Adaptive thinking is always on, and the model supports a 1M token context window with up to 128k output tokens per request.
title: Claude Fable 5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Fable 5

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-fable-5`

- Third-party

Claude Fable 5 is Anthropic's most capable widely released model, built for the most demanding reasoning and long-horizon agentic work. Adaptive thinking is always on, and the model supports a 1M token context window with up to 128k output tokens per request.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://platform.claude.com/docs/en/about-claude/models/introducing-claude-fable-5-and-claude-mythos-5) |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$10.00</li><li>Output (per 1M tokens)$50.00</li><li>Cached input (per 1M tokens)$1.00</li><li>Cache creation (per 1M tokens)$12.50</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-fable-5',
  {
    max_tokens: 1024,
    messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-fable-5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
# The Three Laws of Thermodynamics

## First Law: Conservation of Energy
Energy cannot be created or destroyed—only converted from one form to another. The total energy of an isolated system remains constant.

**Formula:** ΔU = Q − W (change in internal energy = heat added − work done by the system)

**Example:** When you burn fuel in an engine, chemical energy converts to heat and mechanical work, but the total energy is conserved.

## Second Law: Entropy Increases
The entropy (disorder) of an isolated system always increases over time. Heat flows spontaneously from hot objects to cold ones, never the reverse.

**Key implications:**
- No heat engine can be 100% efficient
- Natural processes are irreversible
- It explains why time seems to have a direction ("arrow of time")

**Example:** An ice cube melts in warm water, but you'll never see warm water spontaneously form an ice cube.

## Third Law: Absolute Zero
As a system approaches absolute zero (0 Kelvin, or −273.15°C), its entropy approaches a minimum constant value. It's impossible to reach absolute zero in a finite number of steps.

**Example:** Scientists can get extremely close to absolute zero (billionths of a degree above), but never quite reach it.

---

**Bonus — The Zeroth Law:** Added later but considered more fundamental: if two systems are each in thermal equilibrium with a third system, they're in equilibrium with each other. This is what makes thermometers work!

A popular summary: *"You can't win (1st), you can't break even (2nd), and you can't quit the game (3rd)."*
```

```json
{
  "id": "msg_01TEGjkVwYzfuHrCs5V1Q9de",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAISqAIKYggOGAIqQOscSUEIqskVCTFKJ0i4W90Fia0m32aS+8j6gvpJQkVwCImYZvUlLT0ngohDiWPGx+uORrrkI5qUFGBXijU7UVkyDmNsYXVkZS1mYWJsZS01OAFCCHRoaW5raW5nEgwqVZaKUtMPjtT1ZB8aDHzMnpu8xeeshAEKESIwKiCTZBZGAysSVswoEkB20VfYeJeeMBAqcVEwop/ut0LXzwhnDUAEAYUg4kSv39yWKnTO/ICIz4jCyl7L4SMQd616l3PD2uCuyJRUtqnFLO40PxXgwz8fizzEJMSwFXcjTAkEOdo16C6bHJ7kahwYdjcrrvbQV8OFn0555bExOWsJYiTZVdRrO9XgzDVohWsByfew+FJU7cg/MhO5wA3FikOmOP01pBgB"
    },
    {
      "type": "text",
      "text": "# The Three Laws of Thermodynamics\n\n## First Law: Conservation of Energy\nEnergy cannot be created or destroyed—only converted from one form to another. The total energy of an isolated system remains constant.\n\n**Formula:** ΔU = Q − W (change in internal energy = heat added − work done by the system)\n\n**Example:** When you burn fuel in an engine, chemical energy converts to heat and mechanical work, but the total energy is conserved.\n\n## Second Law: Entropy Increases\nThe entropy (disorder) of an isolated system always increases over time. Heat flows spontaneously from hot objects to cold ones, never the reverse.\n\n**Key implications:**\n- No heat engine can be 100% efficient\n- Natural processes are irreversible\n- It explains why time seems to have a direction (\"arrow of time\")\n\n**Example:** An ice cube melts in warm water, but you'll never see warm water spontaneously form an ice cube.\n\n## Third Law: Absolute Zero\nAs a system approaches absolute zero (0 Kelvin, or −273.15°C), its entropy approaches a minimum constant value. It's impossible to reach absolute zero in a finite number of steps.\n\n**Example:** Scientists can get extremely close to absolute zero (billionths of a degree above), but never quite reach it.\n\n---\n\n**Bonus — The Zeroth Law:** Added later but considered more fundamental: if two systems are each in thermal equilibrium with a third system, they're in equilibrium with each other. This is what makes thermometers work!\n\nA popular summary: *\"You can't win (1st), you can't break even (2nd), and you can't quit the game (3rd).\"*"
    }
  ],
  "model": "claude-fable-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 20,
    "output_tokens": 577
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-fable-5',
  {
    max_tokens: 1024,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-fable-5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python."
}'
```

````
# Reading a JSON File in Python

Use the built-in `json` module with the `json.load()` function:

```python
import json

with open("data.json", "r", encoding="utf-8") as file:
    data = json.load(file)

print(data)
```

## Key Points

- **`json.load(file)`** — reads JSON from a *file object*
- **`json.loads(string)`** — parses JSON from a *string* (note the "s")
- The `with` statement automatically closes the file when done

## Accessing the Data

JSON objects become Python dictionaries, and JSON arrays become lists:

```python
# Given data.json:
# {
#   "name": "Alice",
#   "age": 30,
#   "hobbies": ["reading", "coding"]
# }

print(data["name"])        # Alice
print(data["age"])         # 30
print(data["hobbies"][0])  # reading
```

## Handling Errors

```python
import json

try:
    with open("data.json", "r", encoding="utf-8") as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found.")
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")
```

## Type Conversions

| JSON | Python |
|------|--------|
| object | `dict` |
| array | `list` |
| string | `str` |
| number | `int` / `float` |
| `true` / `false` | `True` / `False` |
| `null` | `None` |

That's all you need for most use cases. For very large files, consider streaming libraries like `ijson`.
````

```json
{
  "id": "msg_013oB35i6D6cJW17UoavzSEs",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAIS9wEKYggOGAIqQFeZ1YZ5RyQ9EbHCqt5fSx9vMAMrhvdbZ+CLKMjT6OXEkD0ktq1p+6St3xTcEVpxkyLpemCD799ZbfCwYd+hJ8wyDmNsYXVkZS1mYWJsZS01OAFCCHRoaW5raW5nEgzx2jYo+ujge2+SskIaDHjgiplZQMyTmf+LNyIwXid3ttbHyXFgieCEovuD3vs0EsVznHmbkYlIY9NyF+a/dx04UlNIrelymYxnEZX7KkPe1UpvY5zXlRmwx3hSBIEFA9FHalSXG7jipEwzoJeyxon8+/rF/zkHacZuq8melq/TmwNzVE4jNU6rDEuvJO0C4l9dGAE="
    },
    {
      "type": "text",
      "text": "# Reading a JSON File in Python\n\nUse the built-in `json` module with the `json.load()` function:\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n## Key Points\n\n- **`json.load(file)`** — reads JSON from a *file object*\n- **`json.loads(string)`** — parses JSON from a *string* (note the \"s\")\n- The `with` statement automatically closes the file when done\n\n## Accessing the Data\n\nJSON objects become Python dictionaries, and JSON arrays become lists:\n\n```python\n# Given data.json:\n# {\n#   \"name\": \"Alice\",\n#   \"age\": 30,\n#   \"hobbies\": [\"reading\", \"coding\"]\n# }\n\nprint(data[\"name\"])        # Alice\nprint(data[\"age\"])         # 30\nprint(data[\"hobbies\"][0])  # reading\n```\n\n## Handling Errors\n\n```python\nimport json\n\ntry:\n    with open(\"data.json\", \"r\", encoding=\"utf-8\") as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"File not found.\")\nexcept json.JSONDecodeError as e:\n    print(f\"Invalid JSON: {e}\")\n```\n\n## Type Conversions\n\n| JSON | Python |\n|------|--------|\n| object | `dict` |\n| array | `list` |\n| string | `str` |\n| number | `int` / `float` |\n| `true` / `false` | `True` / `False` |\n| `null` | `None` |\n\nThat's all you need for most use cases. For very large files, consider streaming libraries like `ijson`."
    }
  ],
  "model": "claude-fable-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 38,
    "output_tokens": 537
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-fable-5',
  {
    max_tokens: 1024,
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-fable-5",
  "max_tokens": 1024,
  "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"
    }
  ]
}'
```

```
Great question! Your stops depend a lot on which route you take, so let me break it down:

## Highway 1 / Pacific Coast Highway (Scenic Route)
This adds significant time (10+ hours of driving) but is one of the most beautiful drives in the world:

- **Half Moon Bay** – Charming coastal town, great for breakfast
- **Santa Cruz** – Beach boardwalk and surf culture
- **Monterey & Carmel** – World-class aquarium, scenic 17-Mile Drive
- **Big Sur** – Stunning cliffs, Bixby Bridge, McWay Falls, redwood hikes
- **San Simeon** – Hearst Castle and elephant seal viewing at Piedras Blancas
- **Morro Bay** – Iconic Morro Rock
- **Pismo Beach** – Classic beach town vibes
- **Santa Barbara** – Beautiful Spanish architecture, wine country nearby
- **Malibu** – Beaches and a great way to roll into LA

## Highway 101 (Balanced Option, ~7-8 hours)
- **San Jose** – Winchester Mystery House
- **Gilroy** – Garlic capital (and outlet shopping)
- **Paso Robles** – Excellent wine region
- **San Luis Obispo** – Cute college town, Bubblegum Alley
- **Solvang** – Quirky Danish village with bakeries and windmills
- **Santa Barbara** – Same as above

## I-5 (Fastest, ~5-6 hours)
Honestly, not much to see—mostly farmland. Best stop is **Harris Ranch** in Coalinga for a famous steak lunch.

**My suggestion:** If you have 2+ days, take Highway 1 and stay overnight in Monterey, Big Sur, or San Luis Obispo. If you only have one day, 101 gives you a nice mix of speed and scenery.

How much time do you have for the trip? That'll help narrow down the best plan!
```

```json
{
  "id": "msg_01JoMwDGJCvYbHtRYpMaaVCp",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAISnQIKYggOGAIqQK/zBQqMA66bUkZi524Lt0j+w8Eutw4fEZezWpC3T8DkRpnoqnfcGJL1WYXiD+kMGT1/gHSAjBTaezw2E8x5XM8yDmNsYXVkZS1mYWJsZS01OAFCCHRoaW5raW5nEgzQCE8UtUZmIwbubiUaDJd3PUdinhPnsMTDyCIwM6zPNTJBliPRjAxg0rXfsMOgkpBJ2f4PsQF8Qx1/OOnBTzzeThC3LqMxwIvRLQNpKmnrVhJc59urfrUjH5w+2LZJMmRg0KiCqdpSRx65zmj0us3grXlxJ5+5KQkaZMILR038gQ1uVGAQ6IhEzj2LaC5fGMRuo9onFlGkksp3s+gb1jaNoo7hEgxzzD+1GPmhtahCBIrXsJUBctAYAQ=="
    },
    {
      "type": "text",
      "text": "Great question! Your stops depend a lot on which route you take, so let me break it down:\n\n## Highway 1 / Pacific Coast Highway (Scenic Route)\nThis adds significant time (10+ hours of driving) but is one of the most beautiful drives in the world:\n\n- **Half Moon Bay** – Charming coastal town, great for breakfast\n- **Santa Cruz** – Beach boardwalk and surf culture\n- **Monterey & Carmel** – World-class aquarium, scenic 17-Mile Drive\n- **Big Sur** – Stunning cliffs, Bixby Bridge, McWay Falls, redwood hikes\n- **San Simeon** – Hearst Castle and elephant seal viewing at Piedras Blancas\n- **Morro Bay** – Iconic Morro Rock\n- **Pismo Beach** – Classic beach town vibes\n- **Santa Barbara** – Beautiful Spanish architecture, wine country nearby\n- **Malibu** – Beaches and a great way to roll into LA\n\n## Highway 101 (Balanced Option, ~7-8 hours)\n- **San Jose** – Winchester Mystery House\n- **Gilroy** – Garlic capital (and outlet shopping)\n- **Paso Robles** – Excellent wine region\n- **San Luis Obispo** – Cute college town, Bubblegum Alley\n- **Solvang** – Quirky Danish village with bakeries and windmills\n- **Santa Barbara** – Same as above\n\n## I-5 (Fastest, ~5-6 hours)\nHonestly, not much to see—mostly farmland. Best stop is **Harris Ranch** in Coalinga for a famous steak lunch.\n\n**My suggestion:** If you have 2+ days, take Highway 1 and stay overnight in Monterey, Big Sur, or San Luis Obispo. If you only have one day, 101 gives you a nice mix of speed and scenery.\n\nHow much time do you have for the trip? That'll help narrow down the best plan!"
    }
  ],
  "model": "claude-fable-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 103,
    "output_tokens": 706
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Creative Writing with Adaptive Thinking** — Use adaptive thinking with high effort to steer creative output. Adaptive thinking is always on for Claude Fable 5; use the `effort` parameter to control depth.</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-fable-5',
  {
    max_tokens: 2048,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    output_config: { effort: 'high' },
    thinking: { type: 'adaptive' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-fable-5",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "output_config": {
    "effort": "high"
  },
  "thinking": {
    "type": "adaptive"
  }
}'
```

```
# The Paper Bird

Detective Mara Voss had worked homicide for eleven years, and in that time she'd catalogued every variety of crime scene debris: shell casings, cigarette butts, the sad confetti of torn receipts. But she had never found an origami crane perched in a dead man's open palm.

The victim—Gerald Fitch, fifty-three, accountant—lay sprawled across his kitchen floor as though he'd simply decided to stop standing. No wounds. No struggle. Just the crane, folded from heavy cream paper, balanced on his hand like it had landed there of its own accord.

"Don't touch it," she said, though the rookie behind her hadn't moved. She crouched, knees popping, and angled her flashlight at the paper bird. There—faint lines beneath the folds. Writing.

She photographed it from six angles before lifting it with gloved fingers, and unfolded it wing by wing with the care of someone defusing a bomb. The creases gave up their secret slowly: a single sentence, written in tight, slanted script.

*He counted everything except his sins.*

Mara read it three times. Then she looked back at Gerald Fitch's face—peaceful, almost smug, even in death—and felt the familiar cold prickle at the base of her skull. The one that told her this wasn't an ending.

It was an invitation.
```

```json
{
  "id": "msg_01VaGXWd9kdzHMepPnPHTTvG",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAISxgIKYggOGAIqQCa14WJvO05NEThN13nBXzVEqA35Ki9nluIV0epwzd5nZM6Iyotcv9JA6vAh21iikvC/FNzJso0wR6JiUwir4ekyDmNsYXVkZS1mYWJsZS01OAFCCHRoaW5raW5nEgz1lKb9mdSCyv6XyPsaDNpKckL3pPM/5C9mkSIwNQrKl5lQs1F2p+1lxVtoAuthy8llMmyUgpy1coZQ4fmw3wlNJI98aNDajf9r3hGoKpEBiMAXur1Qp83FUupryf2Y2xHOMcH9MWev85QNIzNZapR30GC3aD1nTWv2a2cAUy9fZN+nEnPTstS8Wga900d1vDmhu42Yv+45MaE6Oa6syHzBO3+bSCZ/jioWSQxGhxw8jwGhR6DC6mp2iDYZGKpTExw7WftcL6mYpKgBus50atpeUCWXi7/IdHqDUkPRyb1LRxgB"
    },
    {
      "type": "text",
      "text": "# The Paper Bird\n\nDetective Mara Voss had worked homicide for eleven years, and in that time she'd catalogued every variety of crime scene debris: shell casings, cigarette butts, the sad confetti of torn receipts. But she had never found an origami crane perched in a dead man's open palm.\n\nThe victim—Gerald Fitch, fifty-three, accountant—lay sprawled across his kitchen floor as though he'd simply decided to stop standing. No wounds. No struggle. Just the crane, folded from heavy cream paper, balanced on his hand like it had landed there of its own accord.\n\n\"Don't touch it,\" she said, though the rookie behind her hadn't moved. She crouched, knees popping, and angled her flashlight at the paper bird. There—faint lines beneath the folds. Writing.\n\nShe photographed it from six angles before lifting it with gloved fingers, and unfolded it wing by wing with the care of someone defusing a bomb. The creases gave up their secret slowly: a single sentence, written in tight, slanted script.\n\n*He counted everything except his sins.*\n\nMara read it three times. Then she looked back at Gerald Fitch's face—peaceful, almost smug, even in death—and felt the familiar cold prickle at the base of her skull. The one that told her this wasn't an ending.\n\nIt was an invitation."
    }
  ],
  "model": "claude-fable-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 26,
    "output_tokens": 487
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-fable-5',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-fable-5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
# Recursion

**Recursion** is a programming concept where a function calls itself to solve a problem by breaking it down into smaller, similar subproblems.

## Key Components

Every recursive function needs two parts:

1. **Base case** — a condition that stops the recursion (prevents infinite loops)
2. **Recursive case** — where the function calls itself with a smaller/simpler input

## Simple Example: Factorial

The factorial of a number `n` (written `n!`) is the product of all positive integers up to `n`:

- `5! = 5 × 4 × 3 × 2 × 1 = 120`

Notice the pattern: `5! = 5 × 4!` — the problem contains a smaller version of itself. Perfect for recursion!

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

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

## How It Unfolds

```
factorial(5)
= 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 5 × 4 × 3 × 2 × 1      ← base case reached
= 120
```

The calls "stack up" until hitting the base case, then results are multiplied back up the chain.

## An Intuitive Analogy

Imagine you're in a movie theater line and want to know your position. Instead of counting everyone yourself, you ask the person in front of you, "What's your position?" They ask the person in front of them... until someone at the front says "I'm first!" (base case). Then each person adds 1 and passes the answer back.

## When to Use Recursion

Recursion shines for naturally recursive structures like:
- Tree traversal
- Directory/file systems
- Divide-and-conquer algorithms (e.g., merge sort)

⚠️ **Caution:** Without a proper base case, recursion runs forever and causes a *stack overflow*.
````

```json
[
  {
    "type": "message_start",
    "message": {
      "model": "claude-fable-5",
      "id": "msg_01Rwmx9xySGeaRDPFstZ7gMV",
      "type": "message",
      "role": "assistant",
      "content": [],
      "stop_reason": null,
      "stop_sequence": null,
      "stop_details": null,
      "usage": {
        "input_tokens": 22,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "cache_creation": {
          "ephemeral_5m_input_tokens": 0,
          "ephemeral_1h_input_tokens": 0
        },
        "output_tokens": 1,
        "service_tier": "standard",
        "inference_geo": "global"
      }
    }
  },
  {
    "type": "content_block_start",
    "index": 0,
    "content_block": {
      "type": "text",
      "text": ""
    }
  },
  "... 19 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5/#page","headline":"Claude Fable 5","description":"Claude Fable 5 is Anthropic's most capable widely released model, built for the most demanding reasoning and long-horizon agentic work. Adaptive thinking is always on, and the model supports a 1M token context window with up to 128k output tokens per request.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Fable 5.1 is Anthropic's next model in the Fable family, with improvements in agentic coding, long-running agentic workflows, knowledge work, front-end and visual code generation, and finance and analysis tasks. It supports adaptive thinking and a 1M token context window.
title: Claude Fable 5.1
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Fable 5.1

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5.1/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-fable-5.1`

- Third-party

Claude Fable 5.1 is Anthropic's next model in the Fable family, with improvements in agentic coding, long-running agentic workflows, knowledge work, front-end and visual code generation, and finance and analysis tasks. It supports adaptive thinking and a 1M token context window.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://platform.claude.com/docs/en/about-claude/models/overview) |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$10.00</li><li>Output (per 1M tokens)$50.00</li><li>Cached input (per 1M tokens)$0.25</li><li>Cache creation (per 1M tokens)$12.50</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-fable-5.1',
  {
    max_tokens: 1024,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-fable-5.1",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python."
}'
```

````
Use the built-in `json` module:

```python
import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(data)
```

**What this does:**
- `open(...)` opens the file; the `with` block closes it automatically.
- `json.load(f)` parses the file contents into Python objects:
  - JSON object `{}` → `dict`
  - JSON array `[]` → `list`
  - strings → `str`, numbers → `int`/`float`, `true`/`false` → `True`/`False`, `null` → `None`

**Example:** if `data.json` contains

```json
{"name": "Alice", "age": 30, "tags": ["admin", "user"]}
```

then:

```python
print(data["name"])     # Alice
print(data["tags"][0])  # admin
```

**Related tips:**
- If you already have JSON as a string (not a file), use `json.loads(text)` instead.
- To handle a missing or malformed file gracefully:

```python
import json

try:
    with open("data.json", encoding="utf-8") as f:
        data = json.load(f)
except FileNotFoundError:
    print("File not found")
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")
```

- To write JSON back out: `json.dump(data, f, indent=2)`.
````

```json
{
  "id": "msg_011CedBpeQJCnJHy2SvhfpSH",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Use the built-in `json` module:\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n\nprint(data)\n```\n\n**What this does:**\n- `open(...)` opens the file; the `with` block closes it automatically.\n- `json.load(f)` parses the file contents into Python objects:\n  - JSON object `{}` → `dict`\n  - JSON array `[]` → `list`\n  - strings → `str`, numbers → `int`/`float`, `true`/`false` → `True`/`False`, `null` → `None`\n\n**Example:** if `data.json` contains\n\n```json\n{\"name\": \"Alice\", \"age\": 30, \"tags\": [\"admin\", \"user\"]}\n```\n\nthen:\n\n```python\nprint(data[\"name\"])     # Alice\nprint(data[\"tags\"][0])  # admin\n```\n\n**Related tips:**\n- If you already have JSON as a string (not a file), use `json.loads(text)` instead.\n- To handle a missing or malformed file gracefully:\n\n```python\nimport json\n\ntry:\n    with open(\"data.json\", encoding=\"utf-8\") as f:\n        data = json.load(f)\nexcept FileNotFoundError:\n    print(\"File not found\")\nexcept json.JSONDecodeError as e:\n    print(f\"Invalid JSON: {e}\")\n```\n\n- To write JSON back out: `json.dump(data, f, indent=2)`."
    }
  ],
  "model": "claude-fable-5-1",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 40,
    "output_tokens": 451
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Multi-turn Conversation** — Continue a conversation with prior assistant context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-fable-5.1',
  {
    max_tokens: 1024,
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-fable-5.1",
  "max_tokens": 1024,
  "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"
    }
  ]
}'
```

```
Great choice! Your stops depend on which route you take, so here are the two main options:

**Highway 1 / Pacific Coast Highway (scenic, ~10-12 hours with stops, best over 2 days)**

- **Half Moon Bay** – Quaint coastal town with good seafood and beaches
- **Santa Cruz** – Beach Boardwalk, surfing culture, and redwoods nearby
- **Monterey** – World-class aquarium, Cannery Row, and Fisherman's Wharf
- **17-Mile Drive / Pebble Beach** – Iconic coastline with the Lone Cypress (small toll)
- **Carmel-by-the-Sea** – Charming village with galleries and Carmel Beach
- **Big Sur** – The highlight: Bixby Bridge, McWay Falls, Pfeiffer Beach (purple sand), and Nepenthe restaurant for lunch with a view
- **Hearst Castle (San Simeon)** – Fascinating mansion tour; the elephant seals at Piedras Blancas nearby are a fun free stop
- **Cambria / Morro Bay** – Morro Rock and a laid-back harbor town
- **San Luis Obispo** – Great downtown, Bubblegum Alley, and the quirky Madonna Inn
- **Pismo Beach** – Classic beach town, good for a break
- **Solvang** – A Danish-themed village with pastries and wine tasting
- **Santa Barbara** – Beautiful Spanish architecture, State Street, and the waterfront
- **Malibu** – Beaches and a final scenic stretch into LA

**US-101 (faster, ~6-7 hours)**

- **Gilroy** – Garlic capital, outlet shopping
- **Paso Robles** – Excellent wine country, less crowded than Napa
- **San Luis Obispo, Solvang, and Santa Barbara** are also on this route

**I-5 (fastest, ~6 hours, but not scenic)**

- **Harris Ranch** – The classic stop for a steak dinner
- **Casa de Fruta** – Roadside attraction with snacks and a small train

**Tips:**
- Check Caltrans for Highway 1 road closures—Big Sur sections sometimes close due to landslides
- If doing Highway 1, consider an overnight in Monterey/Carmel, Big Sur, or Cambria
- Fill up on gas before Big Sur; it's expensive and sparse there

Would you like help building a day-by-day itinerary based on how much time you have?
```

```json
{
  "id": "msg_011CedBqDdZMZFGUp1yQHKL2",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAQShAUKEAgRGAI4AUIIdGhpbmtpbmcSDIPYwphr/ruEkQm5GRoMi2EZKjsehazJ6il4IjB4hJSu75aNtzCRDW20p3aRVBEl75/aOV5i2an6izSSmbWjhFYvkCSKKvsu6DNM1cwqoQQ0QHB3yemi+cxK105ZiZr2sbYwafT0INKT3HAAvkp8y+Q7o0ro7AZj+6UIUfu9tedn1MFxcGXrh+D8zA9tUXMELTqT4pELiY76hDhkFcCopOoUOCedyQotgDHna+WOdUVKV8BgJaLrvnCYchIHSb0HnWesjzp4GvrOkw3rxfIOl16/W1DTJ638aSYk9ozUMdKxNdyS3OcSvlN7jWiZMOzF6pZ11LTrXOQKy+xWk6Z9TnZ2PoSgBvK2r4xR49xsh+beq0Tq6iYvwUYYMbEOu0xb4t2qHCYJ+80fmyQwxUXdL4fCv0DNuakFX4fzRBOfELrgTDz2LiYm1J2B3Au2KPK/Yet+Qr6KO0G4FOCS5zlGpe9WSVgYzSu/gXm7O1CIrsV6Vfxtq7pv5S/+CL4rwTGJUunzdl8qozMlaJ7uD4kEuK1AMaJ4bcLGxiYDZ1p22pdhtsSGvO1BTb/hPn8PPQfIkEDq8UmRTxCJ+XnfJNAeOeOwB+S9CESoBN85U7yBiPXwvhpgG5uqT1dz9URyMFQHSHbrqoGT3gcilcsYUxzAwA17H5Fvhs1p0/6J0ek21fK/9+3YuryKWHhvM1XFA0uOwZu0xhmatkmLSrmnxEITpP4xHH1OZ2SQUURWn9vjoNLiTAySVKFl26+4nvGcZqDExckEPcBqoU6w7vgFg8nEcHlhs+aSw5S4cNFD5wRizh/iDaZ9+wbkXw5qC/sQ8AtYThgB"
    },
    {
      "type": "text",
      "text": "Great choice! Your stops depend on which route you take, so here are the two main options:\n\n**Highway 1 / Pacific Coast Highway (scenic, ~10-12 hours with stops, best over 2 days)**\n\n- **Half Moon Bay** – Quaint coastal town with good seafood and beaches\n- **Santa Cruz** – Beach Boardwalk, surfing culture, and redwoods nearby\n- **Monterey** – World-class aquarium, Cannery Row, and Fisherman's Wharf\n- **17-Mile Drive / Pebble Beach** – Iconic coastline with the Lone Cypress (small toll)\n- **Carmel-by-the-Sea** – Charming village with galleries and Carmel Beach\n- **Big Sur** – The highlight: Bixby Bridge, McWay Falls, Pfeiffer Beach (purple sand), and Nepenthe restaurant for lunch with a view\n- **Hearst Castle (San Simeon)** – Fascinating mansion tour; the elephant seals at Piedras Blancas nearby are a fun free stop\n- **Cambria / Morro Bay** – Morro Rock and a laid-back harbor town\n- **San Luis Obispo** – Great downtown, Bubblegum Alley, and the quirky Madonna Inn\n- **Pismo Beach** – Classic beach town, good for a break\n- **Solvang** – A Danish-themed village with pastries and wine tasting\n- **Santa Barbara** – Beautiful Spanish architecture, State Street, and the waterfront\n- **Malibu** – Beaches and a final scenic stretch into LA\n\n**US-101 (faster, ~6-7 hours)**\n\n- **Gilroy** – Garlic capital, outlet shopping\n- **Paso Robles** – Excellent wine country, less crowded than Napa\n- **San Luis Obispo, Solvang, and Santa Barbara** are also on this route\n\n**I-5 (fastest, ~6 hours, but not scenic)**\n\n- **Harris Ranch** – The classic stop for a steak dinner\n- **Casa de Fruta** – Roadside attraction with snacks and a small train\n\n**Tips:**\n- Check Caltrans for Highway 1 road closures—Big Sur sections sometimes close due to landslides\n- If doing Highway 1, consider an overnight in Monterey/Carmel, Big Sur, or Cambria\n- Fill up on gas before Big Sur; it's expensive and sparse there\n\nWould you like help building a day-by-day itinerary based on how much time you have?"
    }
  ],
  "model": "claude-fable-5-1",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 105,
    "output_tokens": 930
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Stream a response for real-time output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-fable-5.1',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-fable-5.1",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
**Recursion** is a technique where a function solves a problem by calling itself on a smaller version of that same problem, until it reaches a simple case it can answer directly.

Every recursive function needs two parts:

1. **Base case** – the simplest input, where the answer is known immediately and no further calls are made. This is what stops the recursion.
2. **Recursive case** – the function calls itself with a "smaller" input, moving toward the base case.

## Example: Factorial

The factorial of *n* (written *n!*) is *n × (n−1) × (n−2) × ... × 1*. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.

Notice that 5! is just 5 × 4!. And 4! is 4 × 3!. This "defined in terms of itself" pattern is what makes it recursive.

```python
def factorial(n):
    if n == 1:                    # base case
        return 1
    return n * factorial(n - 1)   # recursive case
```

Tracing `factorial(4)`:

```
factorial(4)
= 4 * factorial(3)
= 4 * (3 * factorial(2))
= 4 * (3 * (2 * factorial(1)))
= 4 * (3 * (2 * 1))      ← base case reached
= 4 * (3 * 2)
= 4 * 6
= 24
```

The calls "stack up" until the base case is hit, then the results unwind back to the original call.

## A real-world analogy

Imagine you're in a long line and want to know your position. You ask the person in front of you, "What's your position?" They don't know either, so they ask the person in front of *them*. This continues until it reaches the person at the front, who says "I'm #1" (base case). Each person then adds 1 to the answer they receive and passes it back, until the number reaches you.

## Key things to remember

- **Without a base case**, the function calls itself forever (in practice, until the program crashes with a stack overflow).
- Each recursive call must make progress toward the base case.
- Recursion is especially natural for problems with self-similar structure: traversing trees, exploring directories, parsing nested expressions, or algorithms like merge sort and binary search.
````

```json
[
  {
    "type": "message_start",
    "message": {
      "model": "claude-fable-5-1",
      "id": "msg_011CedBrJsMHVisMiwBi3NSy",
      "type": "message",
      "role": "assistant",
      "content": [],
      "stop_reason": null,
      "stop_sequence": null,
      "stop_details": null,
      "usage": {
        "input_tokens": 24,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "cache_creation": {
          "ephemeral_5m_input_tokens": 0,
          "ephemeral_1h_input_tokens": 0
        },
        "output_tokens": 1,
        "service_tier": "standard",
        "inference_geo": "global"
      }
    }
  },
  {
    "type": "content_block_start",
    "index": 0,
    "content_block": {
      "type": "text",
      "text": ""
    }
  },
  "... 16 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5.1/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5.1/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5.1/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5.1/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5.1/#page","headline":"Claude Fable 5.1","description":"Claude Fable 5.1 is Anthropic's next model in the Fable family, with improvements in agentic coding, long-running agentic workflows, knowledge work, front-end and visual code generation, and finance and analysis tasks. It supports adaptive thinking and a 1M token context window.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-fable-5.1/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Haiku 4.5 delivers similar levels of coding performance at one-third the cost and more than twice the speed of larger models.
title: Claude Haiku 4.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Haiku 4.5

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-haiku-4.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-haiku-4.5`

- Third-party
- Zero data retention

Claude Haiku 4.5 delivers similar levels of coding performance at one-third the cost and more than twice the speed of larger models.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 200,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://www.anthropic.com/claude/haiku) |
| Zero data retention | Yes |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$1.00</li><li>Output (per 1M tokens)$5.00</li><li>Cached input (per 1M tokens)$0.10</li><li>Cache creation (per 1M tokens)$1.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-haiku-4.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-haiku-4.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
# The Three Laws of Thermodynamics

## First Law (Conservation of Energy)
Energy cannot be created or destroyed, only converted from one form to another. The total energy input to a system equals the change in internal energy plus the work done by the system.

## Second Law (Entropy)
The entropy (disorder) of an isolated system always increases over time. Heat naturally flows from hot to cold objects, not the reverse, and no process can be 100% efficient at converting heat to work.

## Third Law (Absolute Zero)
As temperature approaches absolute zero (0 Kelvin or -273.15°C), the entropy of a perfect crystal approaches zero. It's impossible to reach absolute zero through any finite process.

---

These laws form the foundation of thermodynamics and explain why perpetual motion machines are impossible and why certain processes naturally occur while others don't.
```

```json
{
  "content": [
    {
      "text": "# The Three Laws of Thermodynamics\n\n## First Law (Conservation of Energy)\nEnergy cannot be created or destroyed, only converted from one form to another. The total energy input to a system equals the change in internal energy plus the work done by the system.\n\n## Second Law (Entropy)\nThe entropy (disorder) of an isolated system always increases over time. Heat naturally flows from hot to cold objects, not the reverse, and no process can be 100% efficient at converting heat to work.\n\n## Third Law (Absolute Zero)\nAs temperature approaches absolute zero (0 Kelvin or -273.15°C), the entropy of a perfect crystal approaches zero. It's impossible to reach absolute zero through any finite process.\n\n---\n\nThese laws form the foundation of thermodynamics and explain why perpetual motion machines are impossible and why certain processes naturally occur while others don't.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01AudBc47nYro7MFJatA3KAW",
  "model": "claude-haiku-4-5-20251001",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 17,
    "output_tokens": 191
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-haiku-4.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
    temperature: 0.3,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-haiku-4.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python.",
  "temperature": 0.3
}'
```

````
# Reading a JSON File in Python

Here are the most common methods:

## 1. **Basic Method (Recommended)**
```python
import json

with open('file.json', 'r') as file:
    data = json.load(file)

print(data)
```

## 2. **Reading JSON String**
If you have JSON as a string instead:
```python
import json

json_string = '{"name": "John", "age": 30}'
data = json.loads(json_string)

print(data)
```

## 3. **With Error Handling**
```python
import json

try:
    with open('file.json', 'r') as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found")
except json.JSONDecodeError:
    print("Invalid JSON format")
```

## 4. **Pretty Print the Data**
```python
import json

with open('file.json', 'r') as file:
    data = json.load(file)

print(json.dumps(data, indent=2))
```

## Key Differences
| Method | Use Case |
|--------|----------|
| `json.load()` | Read from a file object |
| `json.loads()` | Parse a JSON string |

## Example
**file.json:**
```json
{
  "name": "Alice",
  "age": 25,
  "city": "New York"
}
```

**Python code:**
```python
import json

with open('file.json', 'r') as file:
    data = json.load(file)
    print(data['name'])  # Output: Alice
```

The `with` statement is recommended because it automatically closes the file when done.
````

```json
{
  "content": [
    {
      "text": "# Reading a JSON File in Python\n\nHere are the most common methods:\n\n## 1. **Basic Method (Recommended)**\n```python\nimport json\n\nwith open('file.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n## 2. **Reading JSON String**\nIf you have JSON as a string instead:\n```python\nimport json\n\njson_string = '{\"name\": \"John\", \"age\": 30}'\ndata = json.loads(json_string)\n\nprint(data)\n```\n\n## 3. **With Error Handling**\n```python\nimport json\n\ntry:\n    with open('file.json', 'r') as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"File not found\")\nexcept json.JSONDecodeError:\n    print(\"Invalid JSON format\")\n```\n\n## 4. **Pretty Print the Data**\n```python\nimport json\n\nwith open('file.json', 'r') as file:\n    data = json.load(file)\n\nprint(json.dumps(data, indent=2))\n```\n\n## Key Differences\n| Method | Use Case |\n|--------|----------|\n| `json.load()` | Read from a file object |\n| `json.loads()` | Parse a JSON string |\n\n## Example\n**file.json:**\n```json\n{\n  \"name\": \"Alice\",\n  \"age\": 25,\n  \"city\": \"New York\"\n}\n```\n\n**Python code:**\n```python\nimport json\n\nwith open('file.json', 'r') as file:\n    data = json.load(file)\n    print(data['name'])  # Output: Alice\n```\n\nThe `with` statement is recommended because it automatically closes the file when done.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_018PXaVwoWM8Eo7X51oCHmhz",
  "model": "claude-haiku-4-5-20251001",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 28,
    "output_tokens": 425
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-haiku-4.5',
  {
    max_tokens: 1024,
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-haiku-4.5",
  "max_tokens": 1024,
  "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"
    }
  ]
}'
```

```
# Good Stops on the SF to LA Route

**Halfway/Central Coast Options:**
- **San Luis Obispo** - Charming town with a mission, wineries, and Thursday night farmers market
- **Santa Barbara** - Beautiful coastal town with beaches, State Street shopping, and wine tasting
- **Solvang** - Danish village with unique architecture, wineries, and restaurants

**Scenic Detours:**
- **Big Sur** - Stunning coastal cliffs (adds time but worth it for photos)
- **Hearst Castle** - Historic mansion with tours in San Simeon
- **Monterey/Carmel** - Coastal towns with aquariums, beaches, and galleries

**Faster Route Stops:**
- **Salinas** - Agricultural hub, reasonable break point
- **Paso Robles** - Wine country with tasting rooms

**Tips:**
- Plan for 7-8 hours total if you want to stop for a meal and explore
- Big Sur adds 1-2 hours but offers incredible views
- Consider stopping overnight if you want a more relaxed trip

What's your timeline? Are you interested in nature, wine, food, or something else? That would help me narrow down recommendations.
```

```json
{
  "content": [
    {
      "text": "# Good Stops on the SF to LA Route\n\n**Halfway/Central Coast Options:**\n- **San Luis Obispo** - Charming town with a mission, wineries, and Thursday night farmers market\n- **Santa Barbara** - Beautiful coastal town with beaches, State Street shopping, and wine tasting\n- **Solvang** - Danish village with unique architecture, wineries, and restaurants\n\n**Scenic Detours:**\n- **Big Sur** - Stunning coastal cliffs (adds time but worth it for photos)\n- **Hearst Castle** - Historic mansion with tours in San Simeon\n- **Monterey/Carmel** - Coastal towns with aquariums, beaches, and galleries\n\n**Faster Route Stops:**\n- **Salinas** - Agricultural hub, reasonable break point\n- **Paso Robles** - Wine country with tasting rooms\n\n**Tips:**\n- Plan for 7-8 hours total if you want to stop for a meal and explore\n- Big Sur adds 1-2 hours but offers incredible views\n- Consider stopping overnight if you want a more relaxed trip\n\nWhat's your timeline? Are you interested in nature, wine, food, or something else? That would help me narrow down recommendations.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01H4xB3mngxiKQMyrfDoJzKe",
  "model": "claude-haiku-4-5-20251001",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 76,
    "output_tokens": 279
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-haiku-4.5',
  {
    max_tokens: 512,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    temperature: 0.8,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-haiku-4.5",
  "max_tokens": 512,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "temperature": 0.8
}'
```

```
# The Photograph

Detective Sarah Chen stood in the victim's apartment, her latex gloves snapping softly as she examined the bookshelf for the third time. The case had gone cold within hours—no signs of forced entry, no witnesses, no motive that made sense.

Then she saw it.

Wedged behind a row of paperbacks, barely visible, was a Polaroid photograph. Sarah's breath caught. Not because of what it showed—a lake at sunset, unremarkable—but because of what was written on the back in faded blue ink:

*"The day before everything changed."*

And underneath, a date: twenty-three years ago.

Sarah turned the photo over again, studying the water, the trees, the single figure standing at the shore. The figure's face was deliberately obscured by a smudge of thumb, as if someone had tried to erase it.

She'd been a detective for twelve years. She'd learned that most mysteries had ordinary answers: greed, passion, rage. But something about this photograph—the deliberate hiding place, the cryptic message, the erased face—told her this case was different.

This photograph wasn't evidence of a crime.

It was a warning.
```

```json
{
  "content": [
    {
      "text": "# The Photograph\n\nDetective Sarah Chen stood in the victim's apartment, her latex gloves snapping softly as she examined the bookshelf for the third time. The case had gone cold within hours—no signs of forced entry, no witnesses, no motive that made sense.\n\nThen she saw it.\n\nWedged behind a row of paperbacks, barely visible, was a Polaroid photograph. Sarah's breath caught. Not because of what it showed—a lake at sunset, unremarkable—but because of what was written on the back in faded blue ink:\n\n*\"The day before everything changed.\"*\n\nAnd underneath, a date: twenty-three years ago.\n\nSarah turned the photo over again, studying the water, the trees, the single figure standing at the shore. The figure's face was deliberately obscured by a smudge of thumb, as if someone had tried to erase it.\n\nShe'd been a detective for twelve years. She'd learned that most mysteries had ordinary answers: greed, passion, rage. But something about this photograph—the deliberate hiding place, the cryptic message, the erased face—told her this case was different.\n\nThis photograph wasn't evidence of a crime.\n\nIt was a warning.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01TG861uc7b1Tbn664aaCLPf",
  "model": "claude-haiku-4-5-20251001",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 21,
    "output_tokens": 269
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-haiku-4.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-haiku-4.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
# Recursion Explained

**Recursion** is when a function calls itself to solve smaller instances of the same problem until it reaches a simple base case.

## Key Components

1. **Base Case**: The condition that stops the recursion
2. **Recursive Case**: The function calling itself with a simpler input

## Simple Example: Factorial

Calculate 5! (5 × 4 × 3 × 2 × 1)

```python
def factorial(n):
    # Base case: stop here
    if n == 1:
        return 1
    
    # Recursive case: break problem into smaller piece
    return n * factorial(n - 1)

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

### How It Works

```
factorial(5)
→ 5 * factorial(4)
  → 4 * factorial(3)
    → 3 * factorial(2)
      → 2 * factorial(1)
        → return 1  [BASE CASE]
      → return 2 * 1 = 2
    → return 3 * 2 = 6
  → return 4 * 6 = 24
→ return 5 * 24 = 120
```

## Real-World Analogy

It's like opening Russian nesting dolls:
- Open a doll → find a smaller doll inside
- Open that doll → find an even smaller one
- Keep going until you reach the tiniest doll (base case)
- Now work backwards: you've reached the smallest piece

## Why Use Recursion?

✅ **Good for**: Problems with naturally recursive structure (trees, nested data, divide-and-conquer)  
⚠️ **Caution**: Can be slow and cause stack overflow if not careful

Recursion is elegant but always ensure you have a clear base case!
````

```json
[
  {
    "message": {
      "content": [],
      "id": "msg_01KvQp2GZvMb9V166tjgWh8q",
      "model": "claude-haiku-4-5-20251001",
      "role": "assistant",
      "stop_details": null,
      "stop_reason": null,
      "stop_sequence": null,
      "type": "message",
      "usage": {
        "cache_creation": {
          "ephemeral_1h_input_tokens": 0,
          "ephemeral_5m_input_tokens": 0
        },
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "inference_geo": "not_available",
        "input_tokens": 19,
        "output_tokens": 2,
        "service_tier": "standard"
      }
    },
    "type": "message_start"
  },
  {
    "content_block": {
      "text": "",
      "type": "text"
    },
    "index": 0,
    "type": "content_block_start"
  },
  "... 19 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting Claude use Anthropic's server-side web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-haiku-4.5',
  {
    max_tokens: 4096,
    messages: [
      {
        content:
          'What were the top news stories about Cloudflare this week? Summarise in three bullets.',
        role: 'user',
      },
    ],
    tools: [{ max_uses: 3, name: 'web_search', type: 'web_search_20250305' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-haiku-4.5",
  "max_tokens": 4096,
  "messages": [
    {
      "content": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
      "role": "user"
    }
  ],
  "tools": [
    {
      "max_uses": 3,
      "name": "web_search",
      "type": "web_search_20250305"
    }
  ]
}'
```

```
Let me search for more recent news from this week specifically.
```

```json
{
  "id": "msg_01NgyYq84DqRm9gyaizK2pMV",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01R5mdFCHNmfZ1M66S6yRNnU",
      "name": "web_search",
      "input": {
        "query": "Cloudflare news this week 2026"
      }
    },
    {
      "type": "web_search_tool_result",
      "tool_use_id": "srvtoolu_01R5mdFCHNmfZ1M66S6yRNnU",
      "content": [
        {
          "type": "web_search_result",
          "title": "Agents Week 2026 Updates and Announcements | Cloudflare",
          "url": "https://www.cloudflare.com/agents-week/updates/",
          "encrypted_content": "ErwSCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDGrK1TK/4MyJ5pWLqhoMsZ/1sL0RQUUS8HtDIjBpBIe4LeWTsr6UjAdDQnzh2epXCDyZidXcyvAU69ZzlEVR+LVkSnbH98uILPHs7aAqvxGblEgcuSB2rxJ+ABLNOk+jylstFVAIrC7wj9L8ENfM13EIFsie98TnIEeB88RRMIcW1KBSdxgTFW/XI2mQ48UAORSaPUAHj/J+0zKr1Ll4Rs3D6ZDxOLz3EI6Q0UN5EO4moFiCdId06XA0ckMReqYu8RwG9dL1+5xSPWsBDmcHBDJ2zdB2BCqVRt2Zcjttv80XdRmeiLscHnp2qq1e56PocFT3heawqfTvqoyLSPbo2q6qT/cSy91suchitJ18CJI8cQyxmelsAaTSxm7UG2+H+/Z9pJ2OK2H7fYD+GDzDNQHtciSno+8oY1EPRhiqODRIrXM3thL5k7JCtYvBNxSfGkpClDPkqdh7VleKSXjf0dhXdhjHOieGPaJ/MYvGVJGrjWIIRInwbpjTSSc1CO1ivFJb/WLdRdkbzkoTqYRe/cGQgywwN2W2KCD2/sfPz1xu28jbEEefubifHOCPYN7yBWi2daYQUAUIeE0LJyjH660OFdOP8QypTxFzEeTSq4cGJ+tm1Q7dviglL48U6x/l+A4eMh0R5hI9gA0NT7m8SB62Qt/QcjhfvyiJi5Pz76jXqwXM+sTcFtckT7BKLo+75fDzIOm5mhr0FTSIVU/VAEjSIobasdCtPsYQphMVAgHceAhfAArf6JDPFUH6pgMLP8dWgaKfNj9+sJAX6iLVjDAv4VQ1a9TVCnKS/5EldDTqyCrFBbrCfDB618mkwOq3sXk3a1zcOjUIKH3lhuc1/7wa8ossQ7RDaLFacocZCK4XqItUYr2+0LtoZpkyzxGeRqwZAeiXYvvr3BxiiCZRkMRlWoHJD0ujqCM0eguqPEcmFjB4Skkjh0xwVhV97wTc0XM+3iw8KhpcBHjYz89QnIzV4StGjVl7wFROeLVR6qKwpb9udGYNrqN6EdrVRxiKpNlEU3Wsel3q8bJ98LIwzr7ukkm2d26uordt8S+Xe/2I07LFsrXz0qtojBxUHhe4cQQ/Ce9ifc4cKesVpExlvGFETvjQDJFLx1NMTx+ijH+xhzRbr16hQ70MQXHaEUzN7Np6g8JXRYTOmxfWl/0Pe+gWYYJ1vPQDClB+SXb7/g9NeYtzVI5GHvZP6BKotel9ka5kiPosn+hOHGhhPB8d2FiYz5RXaW8cPPDdA8n5vy8nal/tzN3Mr6RefwLYScpNkaFRuk+1hHP7pTdLpVJaqc54qxPNb4kSAMnSuT7sSrnmsFdA2GIxPd3Rys6iyHApH6NwKi94YG0ErDQDXklsKDprul0k9P5iYtjnQIHahFUwAZQVDhu0lnopX5+F/jMO+jM8omRGzqsmtv1pQK2kTwOSpGUMeGWBOPi+XszBaKb0ohb3+aKFrK/FqV7ia6zCwTDDAwYaaScHi7CmnP2SSYJaawNUVQHr2FPvJS1VzViMm1ptDEsQA85YF7x6/V4u5Vtzav4KoIxFMTYWVzmt69K8pEL73dYL1VMGYUQztgxH74tLKO1boBPtD3BTGY3iv4+7HT7ybUpE7LJc79eJ598L/8PLqZR8NV2k5pT5aRZxZe5fkEZoAzuBJyqczLphkuRwXZUyvxOcAKF9mmLgO9NBE1zBpIhdaw0QMSd8lHOe1INkJeebP3025JV1M8MQhEAwduW1gAYauBStLnJPwgXfiF+qwk5NQJkzY8YFnsEtXTzLV4uxsbf5OvX1q/iwPexMQO0Vrt0uQh7jSIjvVy5rdlfiJFFT0qRuqcAyXwBTlX6kfj3qH3ebu9d1u5Dy8+XDVdwgTTQLZbvFUvyrWd7a5y2uP0vDR4CAQgPbkUuhSiRFglI3EVG0FpEABPcMi78w9gJMhRcbqeYlPKw3K56WsrqMsc6Vg1jVMKqdZaeVo3agg6K456nz5FLMfbGfzlz7TvhnN6nAeKaWL7EfNLuD27QurlsDAkjZK8uAB8hTrVS3QKZmXRyz7gO9CzaQhXvddZkqWu4lA3duL63AXRXndazZbfzaUCZGs1VUjF8cH789S0vOiX3+hI63MbPbK9mgKRpUFd1EnvapdPjGRaMWcYm1YiPcQVsuh2qB5g6y2ygU5yrFw2zXXTg3ipvBWmtd06gYye/DOkz1a4G/iVIMgtX3sXma0s4US94BIVsqchinCMmDbNyi+njMvON6WBsUfp9LFxYfvEcay6jVvhyuOOL5qmWwW0lktDecNRJI3ven1HWATxK9SRViWnX0GOiPQ8F6U9S6GRSTuU/ye8z/q8qFSMiUbV8VfYI/6fpSfAirlOYQb18UCdnVhu/qJXvADNyiAQsKOMKk8+DwrRoK7A3HXBm/xqGx8yMT/kdjXIUoes8jhlJgiZNr+97aMpuNS8yMP3VegIeaLHJ3mfxtgvd6nWzrjJHpoZAfFh1pXpB3G4ozS/hsRMGHR/bHmsK7CQ6xWz6vMVBgtQpwZJmqaXQDgtT+Wum7KduAsbpyhrpCk0tVIuLMW6+KgSwdQLkZb1JsR8pHajOWkc+gj4OY7IYMo00Nl1gPiUKgQO7xX+VDLXg144ShACi05ViYLXhTX8gacEJ7uhlIcK8gymvoZXMH3d+lM45uYPctz7Eqq3zE1c4I2AESX/6S7J0uKeb8+qr6IwOgey8RLQD6/v7IIiO9FdZsaPVHTg+OFHRrZ1K+CYUTvrgzG98/mNI3PchGOXCLgE9WREmhEsIrblCjavOB2y+CiQ6mLm1PHS26J1cL/1Lra/9eODw34CD/v7TXIzMtO7oJFHHMTe9HAYaAYjg8aKHbxVwwZbCogGm3VA9yHFJJQuHLpuLXGYZlhBb6RZofnT0IUTwHItACny/Z1jy+nMA7YExsQ4y8EDvngecv5Ja4D8DhruNHMV2hqgrUJAhOWRAZaX8qWRc3JuT2yIFUUiX7UgUJq2NWLXtw+JwDEZWOQQyvlcBu7Pl/I2yq9qTxX5uHtYpdrfMOToAtPd3xrPwaXR/igmTgwyco/ajIVOqJ9WfR67H9BvIYkS6jAZgMSB1RpKfyPoxoGAM=",
          "page_age": "May 18, 2026"
        },
        {
          "type": "web_search_result",
          "title": "Cloudflare Status",
          "url": "https://www.cloudflarestatus.com/",
          "encrypted_content": "EpchCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDEowHEXSjWDQXV+VzxoM51R+QK2kXeBZlXqfIjDax7dQo2TI9YOFzBs6960jhsZV7yo9ewySiGzXZcXft8Tv42W+WYzKQks1febgq34qmiAbhiPB266nLuSr+UWtLqH6hsfSIx3CY91/O6jehodCDoTuktH7/0cjCTjohCRmGRuLJgemsKIomoBcKRZlgkPi43Pih7ABDyaEkK446qIzDXwLFBbZWhWhh69z2AqpdcSduLo9a+UeLnd5WpWhs7pcZNY6g7JJtF97FCvvAT2XWln+V/PYUk/0ehb5q1QDO5SyRJzX4L739HeQyKkFw6R8pOdeb6I9KJIsSYdj/y1AndcLkmyYQfR2cgCSGD60SSnGNlIGeemOuqlbQyWAqIw4ysLUP1L4XH7H7tx103Qybv4RXkdT6bpruUgkDhrsC5FD8KSI5gkyZT6M/JszgbXhfv/whAauM6mzJPnSHtxut5swaSCAfIIME/cusa1hISapX3Llh5TLGiwOtbzOuX072TAKTELP0tLoI9p5nvOxLySnoOOWhEXjTiwOW3EFzO1Bxax1pJPC/t8ON72EEUrK2O5BIMGNIWiT5qErEQLlA7jcovUEpMgB9cHxiOyDQWxMC/+LkSsXqPQqBz2Rmh6Qyk1Tc5Yev5Kv80AYCTATLtD7VslTWQz4BUWtlKi70ztzaHJzJ1IB5Vq4ifx7rg+lZMSYGwbHsR2B+sJCcUAlhdJs/B6pY0J5RmAVDrUFhl5DpL/Zs8bplengJ1KKRc+cl67gJ9Fqt0izb8K8uI2n3O4kVHBBoLdcMKfalv0931Yk+SuZWfebACAt3bkG/TD3JhhswcjtqoOn2BtFpk7tbMNNyEh+35gUYUHCqlBBMx3l23L4DeOtqFJ6J6JTFPQFc7sqj2T54BUTAB/tsG3DPen14wNyUMKuUiT+lIN0lyRJVaSDeSH7A0gcMgGzmldPCYh1IaFlb5gk4e++Aha8w3NAQR/GoKOLzHOgDRWpCaHOdNxnYuypP/0AuIxLaMsc2Pcl5q8o69PO+4PXRISx79MSHy2EhZK2eMFvXOCrfigbYTSYBwWpzK+C+GZ4/5gRh72DYYaIA03ZGFvJMYLSzYiSp//9CLExnXXE2PwyNT0H3+899vis+Pf83GjHyZpiLkSyqEO4igziu1i5SycZYf3ETrLGT+q5aAxmZNs7ftzox08PUhBt/UU1Eia6HR6hzfK7uHjxzuobzNdQrqLCR6TQ6SjDrLPEM6AjS7aEp5SPKYqvRFqJ6mnyAXIdOsRjg7P+me1AvygyrZL5vOZ6FpvYzH0aisO5MLbVypReAp+EsExfZ4mToiMGusr7NeWYGDVRd2nWFu548e2jja8g2R4vTMJ7ByFnATxRcKZIUacBBlStDWdXAhrr3oE8rd7rnJNLePFlRqmffYTRkaTvh/Lx92BNI6e+EQMbB/bsXMDMuXKgrjOtFAcKPjtPRVdi7b9op7FAfzmTQJLUkmjw8hous4dOEnE0yOSHlQbmz+Dfu5/jVpVaRjrOhTpmDmOJYI/3WHyLhe402VnHbekuR8wf214zHNWBKgdD7y8YaAS+G49eMmlKyQ95zT8TwcpEahXDzcN17E9TDWmg5Yy9T8kmKZbQ5gnVYtDWPnrNWbbcODJlmTv8pOKKim9Era0osd5vOWWTVFs6GUlat5TXjhWVplWH6R1+PiDjF4RjzSky2NPMYeV4ncBT552FXYp9F7GOT855ZOUTAmn+Zzpo1w2vtfwtRLhzYBvwJH3xSp7eOMMKQX7sjuPyqSN78TFhDK+9/5PScBFEWzDRY3fpOSnyEhR1g1hraEq/eiJByEnqt5P+AgcDz3652LZ4hv/mi6HEniRE4Uvu7c+ovmVGPIoPWhj+x2D8KLOYEjcoaBidWGEIbfVlBtVmGTe07V8Sx8gBfA8Y43AalLoD4xYwaSow+BIW/nHNSOFMconecvlOlpXFHnOrBQa6FYCKXhf5WcBOm4dAi/qQRCIDtfzMOa/9olIFwJMsPXWmSu+Ez5v1HC9okt5LwuxHexZRg92B6NSk/IO0GKgHIH8HLNg2axagh94Ewgue4KEeTyS1zVP+7meZO2gM0ze5oH0Du5SX8Byc6TK5f8l0aJobMnwCsmi+US5TEaMl+fK8milzmBO+xPW91gXQabtvOjEVhE51+nZ4K9Gv5+73p9cSaf6u7MMC1g2LC9I6WyUNhqFBff6CsG4lR/CgiwDHvD2eEsKUxHysHapIj9oVJYPwnk30Or8p5h4NqmfEl2Ld47LkqCIZJdOXhpp8AnQngc14IV7i8GBV0K2tDFJAw7hKaELtje9gaCl/pviT5l7nLUZK0rSLYPf58RLg2i9EXUjlvvVcTxI9brGfV/jqDkVxM80i49I3ek/RCZjmaBonDnaLrA7/inrtR2iF8ZC3+Q8oyzqB+AKrnoCMDuV4PSoROiAVypiBgJuvNshG6I+m2zLuU1wpiJ8U83LBGZ4XP8I8bDPC2BqHSQ6N8zrExciiZswa1KMEeqwHJ954EQGsehNrJ+OjELX2nBYnzhPf8c6XDlbZnx7Iie1lKfIqAwuxK/pl3dcAO+eczWUNjRdgSnEyDkPTBPTG5tyCmjyPyUkK4NuEe71wWPIP0Sxzs6vQuPxBdGIjB6SXoj8+LgYZPHuiU9AslLtm2Ar9eCvbFiM87x/1O+NvvTA71mVEiluJkuJ/DGAPveTwwwHXfG49I8XfYXkLn5i68mjf2J4HFrakQXbfGWE6uuPgIISqHcgeJiGo8xbJdGMpTuOeqY3rkBi88Wyv+92V8uT3uDPeDh6QND6ePoI23XOT2XuRyeSpnWq2uAP1ebNRoKIKbLUjFGGgZlkF5j41XEqPskw17aU6Uk77YGaM/eu3QmyxKAPkdhHL0pISytmqT80skcQTsXnF3Xeo+wyZm9KM1M8l/UHp6/mIPq0XL6f5sMQq56eA2B0KvohK90i6UXMpKwKY4yHfSijsvUr1DOJ3TJEfvvYjlMX4BZfS8uHdUSgAuyI7qs1QzA1059NXbt7BJpn7NZHGTQy3FygV4tZxIHqmVp8wUnT2AwSgUcorWeWki5syNMOnCWue+H9YMSgERH92jwio/uwOLuRvsc3aar5ksWUgQIPaP69gNzDMuPPslkUzLq+n5fEWR29p34Lc9uUvWukVpa4+0DVIvHqJmyZkC2egQ/rYjfiON1vvzPhrK7t/bW9SJgXJB2y5564n2zGdTn0ngXnN7hN7HLoOYZbONGKFVcg4W02epwP5cW45wjZLXQw0roUBpudwVKcRs/v1DXndj0RqLe501YzjB1wpX8ENC2boz6TDMcRlx3278HHolzaZyXdm7FUkwpCr5LfehzvwjEPGfFLtzVPoJe9NOvsBlUjOUXV4n2DUxHJqfYwn9YPAPIs7yglrvXE83mhXf4/EYcFXwXroJOwakvqhloQZgLo8dKwyQ5VyOV4AyfEBHUCx2gUrgnq3LkZwJHNEs/qvDizZozxcMeLiXK1v90J2clxSfviOFV3J1GBe9QIJBe+E1bniDGkf8svUlffq3QjOZYoNzM3aH7gIzCxQkqgIq5DiRmeXOfRfX43gEQ3T+uP/LptK8nJrntOJxQ4GBnU0RlHkjCpAyANkzZBxVZsiIVy1sjlOS7XZpLs6WIssm2BCpc7BYOMBALQ0LoVehSNFWr83SWhhf117QfPx7sqiWf3IX9iuD16eon9gL3je8KKNtdT9Ny3akqT+bOTTwC1heWDqpuWUDum3ox8VlTXvokGAD4AsCbWBKqT54OSKO9k/YzDgbFcxAwd3oo33U+k2yNDxyIAFZcpYYNzj6stFuJPEUtdLqQfxQTAC7ofpyZkupoGrtLJETFjB9gikZAQqq4s/mbjAT0+QEd1yGaOpy
... response truncated ...
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

temperature

`number`minimum: 0maximum: 1

top\_p

`number`minimum: 0maximum: 1

top\_k

`number`exclusiveMinimum: 0

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-haiku-4.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-haiku-4.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-haiku-4.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-haiku-4.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-haiku-4.5/#page","headline":"Claude Haiku 4.5","description":"Claude Haiku 4.5 delivers similar levels of coding performance at one-third the cost and more than twice the speed of larger models.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-haiku-4.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Opus 4.5 brings further reasoning, coding, and agentic improvements over Opus 4.1, with stronger tool use and tighter instruction following.
title: Claude Opus 4.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Opus 4.5

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-opus-4.5`

- Third-party
- Zero data retention

Claude Opus 4.5 brings further reasoning, coding, and agentic improvements over Opus 4.1, with stronger tool use and tighter instruction following.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 200,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://www.anthropic.com/claude/opus) |
| Zero data retention | Yes |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$5.00</li><li>Output (per 1M tokens)$25.00</li><li>Cached input (per 1M tokens)$0.50</li><li>Cache creation (per 1M tokens)$6.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The three laws of thermodynamics are:

**First Law (Conservation of Energy):** Energy cannot be created or destroyed, only transferred or converted from one form to another. In a closed system, the change in internal energy equals heat added minus work done by the system.

**Second Law (Entropy):** In any natural process, the total entropy of an isolated system always increases or remains constant; it never decreases. Heat flows spontaneously from hot to cold, not the reverse. This also establishes that no heat engine can be 100% efficient.

**Third Law (Absolute Zero):** As temperature approaches absolute zero (0 Kelvin), the entropy of a perfect crystal approaches zero. It's impossible to reach absolute zero in a finite number of steps.

There's also sometimes a **Zeroth Law** mentioned, which states that if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other—essentially establishing temperature as a transitive property.
```

```json
{
  "content": [
    {
      "text": "The three laws of thermodynamics are:\n\n**First Law (Conservation of Energy):** Energy cannot be created or destroyed, only transferred or converted from one form to another. In a closed system, the change in internal energy equals heat added minus work done by the system.\n\n**Second Law (Entropy):** In any natural process, the total entropy of an isolated system always increases or remains constant; it never decreases. Heat flows spontaneously from hot to cold, not the reverse. This also establishes that no heat engine can be 100% efficient.\n\n**Third Law (Absolute Zero):** As temperature approaches absolute zero (0 Kelvin), the entropy of a perfect crystal approaches zero. It's impossible to reach absolute zero in a finite number of steps.\n\nThere's also sometimes a **Zeroth Law** mentioned, which states that if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other—essentially establishing temperature as a transitive property.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01KCBDSEEzS8kikdpAQHP1qf",
  "model": "claude-opus-4-5-20251101",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 17,
    "output_tokens": 215
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
    temperature: 0.3,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python.",
  "temperature": 0.3
}'
```

````
# Reading JSON Files in Python

Python's built-in `json` module makes it easy to read JSON files.

## Basic Example

```python
import json

# Read JSON file
with open('data.json', 'r') as file:
    data = json.load(file)

print(data)
```

## Common Scenarios

### Reading a JSON file with error handling

```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found")
except json.JSONDecodeError:
    print("Invalid JSON format")
```

### Reading a JSON string (not a file)

```python
import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)  # Note: loads() not load()

print(data['name'])  # Output: Alice
```

### Reading with specific encoding

```python
import json

with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
```

## Key Functions

| Function | Use Case |
|----------|----------|
| `json.load(file)` | Read from a file object |
| `json.loads(string)` | Parse a JSON string |

The result is typically a Python dictionary or list that you can work with normally.
````

```json
{
  "content": [
    {
      "text": "# Reading JSON Files in Python\n\nPython's built-in `json` module makes it easy to read JSON files.\n\n## Basic Example\n\n```python\nimport json\n\n# Read JSON file\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n## Common Scenarios\n\n### Reading a JSON file with error handling\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r') as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"File not found\")\nexcept json.JSONDecodeError:\n    print(\"Invalid JSON format\")\n```\n\n### Reading a JSON string (not a file)\n\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)  # Note: loads() not load()\n\nprint(data['name'])  # Output: Alice\n```\n\n### Reading with specific encoding\n\n```python\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as file:\n    data = json.load(file)\n```\n\n## Key Functions\n\n| Function | Use Case |\n|----------|----------|\n| `json.load(file)` | Read from a file object |\n| `json.loads(string)` | Parse a JSON string |\n\nThe result is typically a Python dictionary or list that you can work with normally.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_013RFtndBKXc2aNHCwT6Q3cP",
  "model": "claude-opus-4-5-20251101",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 28,
    "output_tokens": 338
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.5',
  {
    max_tokens: 1024,
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.5",
  "max_tokens": 1024,
  "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"
    }
  ]
}'
```

```
Here are some great stops depending on your route:

**Coastal Route (Highway 1) - longer but stunning:**
- **Half Moon Bay** - charming coastal town, good breakfast spot
- **Santa Cruz** - boardwalk, beaches, laid-back vibe
- **Monterey/Carmel** - Monterey Bay Aquarium, 17-Mile Drive, beautiful Carmel village
- **Big Sur** - dramatic cliffs, Bixby Bridge, McWay Falls (allow extra time here)
- **San Simeon** - Hearst Castle, elephant seal viewing
- **San Luis Obispo** - cute downtown, Bubblegum Alley
- **Santa Barbara** - Spanish architecture, wine tasting, beaches

**Inland Route (I-5) - fastest:**
- Honestly not much scenic appeal, mostly farmland
- Good for speed, not sightseeing

**Highway 101 (middle ground):**
- Passes through Paso Robles wine country
- Solvang - Danish-themed village

**My suggestion:** If you have time, take Highway 1 down and I-5 back (or vice versa).

How much time do you have for the trip? That'll help me narrow down recommendations.
```

```json
{
  "content": [
    {
      "text": "Here are some great stops depending on your route:\n\n**Coastal Route (Highway 1) - longer but stunning:**\n- **Half Moon Bay** - charming coastal town, good breakfast spot\n- **Santa Cruz** - boardwalk, beaches, laid-back vibe\n- **Monterey/Carmel** - Monterey Bay Aquarium, 17-Mile Drive, beautiful Carmel village\n- **Big Sur** - dramatic cliffs, Bixby Bridge, McWay Falls (allow extra time here)\n- **San Simeon** - Hearst Castle, elephant seal viewing\n- **San Luis Obispo** - cute downtown, Bubblegum Alley\n- **Santa Barbara** - Spanish architecture, wine tasting, beaches\n\n**Inland Route (I-5) - fastest:**\n- Honestly not much scenic appeal, mostly farmland\n- Good for speed, not sightseeing\n\n**Highway 101 (middle ground):**\n- Passes through Paso Robles wine country\n- Solvang - Danish-themed village\n\n**My suggestion:** If you have time, take Highway 1 down and I-5 back (or vice versa).\n\nHow much time do you have for the trip? That'll help me narrow down recommendations.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_014rC84VWk6CFhWNascdSZwf",
  "model": "claude-opus-4-5-20251101",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 76,
    "output_tokens": 290
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.5',
  {
    max_tokens: 512,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    temperature: 0.8,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.5",
  "max_tokens": 512,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "temperature": 0.8
}'
```

```
# The Cartographer's Last Note

Detective Sarah Chen had seen her share of strange crime scenes in fifteen years on the force, but this was the first time she'd found a victim clutching a map to a place that didn't exist.

The body lay in the cramped study, surrounded by towers of yellowed newspapers and the sour smell of old coffee. Standard enough for a recluse. But the paper gripped in Martin Voss's rigid fingers showed hand-drawn streets, elevation markers, and careful notations in faded ink—all depicting a coastal town called Meridian's Rest.

She'd checked. Twice. No such place existed in any database, any historical record, any atlas published in the last two centuries.

Yet the map showed wear patterns from years of folding and unfolding. Coffee stains. A thumbprint in the corner, pressed there so many times it had worn the paper thin.

Martin Voss had spent decades studying a town that had never been built.

Sarah photographed the map, then noticed something that made her breath catch. In the lower corner, nearly invisible against the aged paper, someone had written a date.

Tomorrow's date.

And below it, in handwriting that definitely wasn't the victim's: *You're early. We expected the other detective.*
```

```json
{
  "content": [
    {
      "text": "# The Cartographer's Last Note\n\nDetective Sarah Chen had seen her share of strange crime scenes in fifteen years on the force, but this was the first time she'd found a victim clutching a map to a place that didn't exist.\n\nThe body lay in the cramped study, surrounded by towers of yellowed newspapers and the sour smell of old coffee. Standard enough for a recluse. But the paper gripped in Martin Voss's rigid fingers showed hand-drawn streets, elevation markers, and careful notations in faded ink—all depicting a coastal town called Meridian's Rest.\n\nShe'd checked. Twice. No such place existed in any database, any historical record, any atlas published in the last two centuries.\n\nYet the map showed wear patterns from years of folding and unfolding. Coffee stains. A thumbprint in the corner, pressed there so many times it had worn the paper thin.\n\nMartin Voss had spent decades studying a town that had never been built.\n\nSarah photographed the map, then noticed something that made her breath catch. In the lower corner, nearly invisible against the aged paper, someone had written a date.\n\nTomorrow's date.\n\nAnd below it, in handwriting that definitely wasn't the victim's: *You're early. We expected the other detective.*",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01Xn7b7JzMzoHWDigjdGFniq",
  "model": "claude-opus-4-5-20251101",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 21,
    "output_tokens": 282
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
# Understanding Recursion

**Recursion** is when a function calls itself to solve a problem by breaking it down into smaller, similar subproblems.

## Key Components

1. **Base case** - The condition that stops the recursion
2. **Recursive case** - Where the function calls itself with a simpler input

## Simple Example: Factorial

```
factorial(5) = 5 × 4 × 3 × 2 × 1 = 120
```

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

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

## How It Works

```
factorial(5)
  → 5 × factorial(4)
       → 4 × factorial(3)
            → 3 × factorial(2)
                 → 2 × factorial(1)
                      → returns 1  ← base case hit
                 → returns 2 × 1 = 2
            → returns 3 × 2 = 6
       → returns 4 × 6 = 24
  → returns 5 × 24 = 120
```

## Simple Analogy

Think of Russian nesting dolls 🪆 — you keep opening smaller dolls until you reach the smallest one (base case), then you work your way back out.

---

**Remember:** Always have a base case, or your function will call itself forever (stack overflow)!
````

```json
[
  {
    "message": {
      "content": [],
      "id": "msg_016ZKcVY6ckQdq7TF4tE5AsJ",
      "model": "claude-opus-4-5-20251101",
      "role": "assistant",
      "stop_details": null,
      "stop_reason": null,
      "stop_sequence": null,
      "type": "message",
      "usage": {
        "cache_creation": {
          "ephemeral_1h_input_tokens": 0,
          "ephemeral_5m_input_tokens": 0
        },
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "inference_geo": "not_available",
        "input_tokens": 19,
        "output_tokens": 1,
        "service_tier": "standard"
      }
    },
    "type": "message_start"
  },
  {
    "content_block": {
      "text": "",
      "type": "text"
    },
    "index": 0,
    "type": "content_block_start"
  },
  "... 15 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting Claude use Anthropic's server-side web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.5',
  {
    max_tokens: 4096,
    messages: [
      {
        content:
          'What were the top news stories about Cloudflare this week? Summarise in three bullets.',
        role: 'user',
      },
    ],
    tools: [{ max_uses: 3, name: 'web_search', type: 'web_search_20250305' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.5",
  "max_tokens": 4096,
  "messages": [
    {
      "content": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
      "role": "user"
    }
  ],
  "tools": [
    {
      "max_uses": 3,
      "name": "web_search",
      "type": "web_search_20250305"
    }
  ]
}'
```

```
Based on the search results, here are the top Cloudflare news stories from this week:

• **Major outage caused by fiber cut (Today, June 22):**
```

```json
{
  "id": "msg_01TDBej8ibu9GLjmQqvtxwyc",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01KYaTPC99TmQFX6b2mmSCMA",
      "name": "web_search",
      "input": {
        "query": "Cloudflare news June 2026"
      }
    },
    {
      "type": "web_search_tool_result",
      "tool_use_id": "srvtoolu_01KYaTPC99TmQFX6b2mmSCMA",
      "content": [
        {
          "type": "web_search_result",
          "title": "Cloudflare Release Notes - June 2026 Latest Updates - Releasebot",
          "url": "https://releasebot.io/updates/cloudflare",
          "encrypted_content": "EswgCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDB5BPWjNVaw5TvtJUBoMp30JpVK6zhIap/xdIjCaS57635Hzp4Dh/7C8rC4RHOx8t3P1OMXt9HoVHK/HRHt9x5U7oVXksKA64i5voF8qzx8alSq+LQZiY59BvyQPOSVwouMnrzXJrgHCmOfV7TgadaJeXQn9tryT8Q+iICChkAaMJVxQi0K97eu39Kl6DCV6Kfa/rZZccpilZO/oiBm6zDnv6mQunUu42JrwwcQSkpYAE7nyvr+kW6S3Rpv/Rq3OxBt9Ar3Dq8XXyZ8uxCsfTFHX+ZoMuFHXuBvT7lT+nHvOLWavCRno8oCpZGmZs2cZruChCsFKDygfWBzeV/EcoAD9ddVOB8+D78Gs2ewmJckJsAkzSuGd6mDJKPDRlubf81E376rK8914iKxCz1x1hIqz7VwGKzZoIDXXY8fOVLWdMOwF1g1alfmunoyQ4kwwKCH8t6yCpOmX09ej8M+Bq+LZyBSYCAJqnRHrMtXtOspGDH5syuj0w8SIUwXn+IKOdmbo4wYNgQo5JsA3pnD6Ip18Wr0KBH+Auj2Oxl1W6EPjz61DSjkfsizY154mD4uEFzuS589ngusIeexowRza7GICa81OGsT0gGjwnfA0Ppp1NHHECY7G3ZA9n/exc2MXl5mdLSiVrn8fI0jryVdCCxXaGRMWCKUvExcEusSvhBtWWZxHw3uz2tUshUeJCGhGjBTKyM2WNUW9+WiqLYcP23m/Ttvon7DDwR/xWiyUCKlBaTMJDA4HIkb4EESLgzf437PT63S92A/5Xf256xYng/NdPW5cvFScQBoDihNAy+IHO/FQdrV433V8OCM5XhSe5RX23PGY4XwfSsZo9SiEN+7JP/5Duqno0V8Uhd5P8cakHaU0IC6YXFOc3WhYSThCBaFNWtt9U2V/04wn/BYWR5vp+JvnuRh5XeQTzBCA3ABysObMfZ+GtWNwzTZhS4Ylt3X5ts1XBwD2w2LfVZg6MyREwYJpfXgSYJF7cMC7kvBSlQ5og2KPAbet+xxuOgKLrRXgHpPKOcvSXO2DTdxpuggVSN2R3ZQ0lX8qTa9tfud3YymBcVdiQubA3DU4pPH5OqbYDj2uCe4PhN9OeyikLdrk7iLcPmdO5tvl14z33xHWU5XkIkzCaIU88E5W7cgaPaLxbBwbuOgHFwJMQAlWq6h5ktKvW7pFp81gscBpsLLSFCUQ50Wj+zVD+FLylZQRZ3UAw39Euf1xInXuX9exQZ8oZsUcm8YG0SlDVU0MKfpaxFbTkQ5weiGn/a02mdj/EpQUkyWkyephRZ1AodtUvhE6++EjSJhmLiBYWifDkWyFgjYEc29je1xl1MKZLZFQamVGVDZe10RgvpLqn/KnxWH+tlPXY+4L023ZKkWpePzaPPBlbVTsCuaxfBmNRF3JWrLZYeNrtEyKINueNj9kQDJi4q3mXDqfRKwVJDTdXJQxHDZyt7mO2ylJPmznXqDPS3jgPxXeDuP9xfow0HsgSOyNXLlViCy1/daL6kC0ZFg5A2684Z/qx9U6wKmw+Qv7ZGrfUg/ovqOXpLsODGp8UZIkZlD6PiQVZa3smjIxyCLz9CRWPDVJzn0NPzWJLhEL+nsRsjd7IxgF00CBxVSByIU8It8RRHerFlwy7cCG5I4eRsKZXZ70lp6rdGdjDJJp/2NIwUa5tcb0LgIuBN7RNMlr+/6I0NjC3INkOjZCgJv7NU91vVvMZHCDuECtZL9AfQ+Y0dZZXavgq/dNKI0fPda6XGmZv7SrvEC5w3+RTLX1tuxXxZQcN93U34swNCKMt8WgSKDqFdHuakpMjWHMEA2pcjzFRsPj3f/y8rxoQ6OvrVvlUua/JH7pSHhLwvjgrhEcq3AOyqLZu2CDz/eEL44VVtziAJtQ12AXMnMSBr/qK0WlsAGSe4ql30vLpjdJa+jDDDd1QjekNJqjNYKEjIrrO9JgyewzqeTFHun0CnjLNHkmK8y/sVta92Uly7qKhfoHqNoJPzVZ6Ai/NpcAlFuikbbWNhK1DUJRrixiLOi/89RE5UGwd0igVhVg/Xy88hA+4x7YyFDLMtsSBQo0nm/nssMoY2R5F7PmoOyjvC8o5mcDcd/s/57QkHUVHX51F0fKj8FNGZojzWxm7dwj3SMR8xOikGU68HCgTDRF+GwIuiQ2huo3ak89OEd5tabavEUOpFmRTloGDI/KrQDd4+1p0EbZYyJe+Z+JeCb6ip65RotW/i7k1jc2DCFlVlenfc1MyC+ZJLamUxEggNqRAteTKdQs6FCeAXJN6JjbAEJImMsksBiEHZSpiKaDLbxrShOZJWmi28FSxuy51zKYmZM4RcNf1FMy5HupO07VmyaN4ni9Judm1khtYVOjnvQ3roM+yHwhhE0EXGlv8aBseJRnB6WNc0Volv0nwL7Y4xnTV5E7OWo8R43DQbGcwQ+5zcqFEiQ6E+NpE9UrZ/0Aa4ocaesdh5BRI+5Z5gVAr++SlXzLM8dsmS41S+IKqGNl06XRmzl00MChQZcL53XAwVGOVX26h9faJFVLN/wKznNCGoewLOdBFGFIYZeruXEdGcfuygDl5XXDfgf9iOhU8BruCCCP4Yz/3nGG3dApgYYMN/eRBJC4sLWpwlwcxy4hkk0JapnhCzW/01Fc4/pwVNvBwZue43OfDnhCLvH4B19GxGrBXWIjf8FW2SjdvMtIVKcpzwMK5uo1r7PJ7X9yC1+dchCzb8HRYxEioMgUsociDhdg+wg0kVqmpCRD7KRSO2JyUsFxPM/GNdDE4F//+agDwh9uck3ZlwyBJPflg8W86Rhs5DZt1t/XtomJnAvGSofR1uAgFx9kwNBw9E9K/Zj0CtHzIMfYKV36Rw/AEPqz/YUQcBbay1+TBs+lNnqWXEny8XjmtAWM1PJ09WEwpgoMpCsfpUVHEnJJQkydJRspwZzrhy3lak7DUJcSk6SiZVcKLNXgd++y3tUPWdjTgJTvcSes95/QXHEDoWsRp2bmQaKmxrqLRJ7lixQqYS7Xf/ieSOqIRCjEAvfWP4EVzzIfTJTwW3whC3Yaem6zAeYFEayBWViK/VktQtxAhhWmYU0PqcR6svM1uzr0LjfM/P247SEC2dVnfcMiYvirqI6UsEiFoTDZ47D6mGyRYWRkoYf7HNOIEgUdJO5r4bwkU28xMu9HnOfjMc5A9s95HJubDzFPH/5O1qcnIfYrnih9we/EXMM94ELH6DfQd4da/t/POOCEqYxlq7EzMKszCKAcRZLE7ThGWD7dqKmS8MmQ/m8vNwfaAmwhca6tVGvmcOVS+pnu6l/BYLjSU77QbOXrTkqg40YCYJQ9HRieGKt49j/LrTfmZmtrCeKOE2id0bujbm7qd81kFVgogPOT2BJtH9MEMVPSfcXxfrn10Qr8xZ2Y1XgAenQV9CiuswjXw27kcyarlykOA9FthCZfRwkFcPfT1iBHjkZ1n2DuE2VNOoQvsIC3Z3WyjC2gS8SuNHxruPT13mQLx3bPsnGP3sPQbGsHyNZOFrQ0+fU/wU9TDfCLT53PyQsTpFkdhB6s5UQrA7Wr2ZR+3vFJLXQ/gNuLxHr8TCpiYtNxV+HUyYKUxtMc2cYVyjebpGmdU9zH3HVXYBaDujt3FgLU1h9v7Cg42TE/X2s7bIgc8uBHfJ+t1FoeDHG3sLYRnokk3KHZmHepBLdOvtvnkE2V0w7qgHR0cgLcWcXBtQq8gduyVhljY5WU/EhHrXCUOJTTg6OB50d1yO/qIygmd3FRXoXNZskE3wzyWQZ5/vfOBXWIoBiHaix9ZB9wMUWle41Bla26/WhzfDE0x/nOyCUg/CTYXpr69d1/BMVduAXPXD7Dwnw5kNqKcY1sIEC+9nsLfyEulRnNn+Fskop873uazMbaBKNuxXt8QaRu2jW3ov9R4TekUu/UAsk8R+DYB9BEZUR7Ws/Ql5jyIYoKTl86LlPyJWThAHwEkZh87lKroMuahPWI+p6ofj8I6VGKh3IqPY8SZwH9c8NTXb2tatr51wZt9SnZTPopo2WATMQY7JXFRTnofGI4chMOqYrY2IN9XPi6LAryc5JeWiGml6/ZOvbAirPYmglhh0cuB6WFo5hNHbZ1Fr55Q0xVIfcG0n3Sg2ldAxvAFMY/ZdF2gh0pMgkotmHYYjqDlD7Kw2VAUoHdYNFkJ0qA9w47F+sm55FPMkIyCZwaO0081EufJ/KX8yq1OG651yEh+f0L830DJ4E7CeoXrPtxVgNb2eydHnead67v8WUHHxjw0w0d+rDVERvXBdHW8vbbwQemrWAJ+gINQLRqmP3puCoG0dtV0WNq4i/efOfZ2kkaNy21oUBZn40egI2+gfncKvlyyin1fJq1V//iFbahjZzqrbwoMHFE/37l3LN66YKhFbQhMW5ebf97bjnbso4xGOOo/GGFosDqf80TuABIJujjaunx2Qzivsyc3CIwbgRVtrL/vURjdpUK1cIyukg7SZY463FpE8C8K/iVqnrvniHlqsaQWN3Cry7w5md13l9geqvlSRiT6/IoARpU9pKax+6Ie5LxbA2PIC/o5mtDMezddrvWZXsVsS+uFzesw2WYUi72BL6wrRqZoS0XJMDhNYeM1fRCB3y0Fq1rAKji8sx/F1d/5NCJSjAn7TpLUzzXrw7Z0uiGl7oRkzPxx1lCeyuJ+wSwiQl8srB4DO0SxOaiqxYxcEep/knaT5SnnVCX8MhXMWcWGM2bCR6DlTTGEMyJh7ExUlIuCpq+4KgqptsO/g/3Q8IARtP0nOqaKn5faMZ16X6RH27M3epIH7cZG9LntE8zM7Bi6b1jNbH2yli6H55B6SWyHwVnkiNvqRAWD8oo5ok/R7OX1Ry1BGyqmhWOdfGqT04lzzWK3RowActzpR1V0F2UMDLEWX4yJ3RukqC9KkZqzG11dKh70FBs3nIu1BU6dcJMsWNiqcF0hoPrKBHPT6F8AkGn5B1RPXCaF02bcFAxbfM3r8Q570S+leOG6bMPHZmbWDi+kQzUEI6kEEUESXdQsV9Tu+cmTf346SluCYFbt6HvUQ6iIgXm4DOaKhmMktxEjElPumEohWL7pVogXDdNEOyyXTZWKWZwbQ3qO5VIcshvaKIEfdWx/GR6pWdlew2agANE9s2nzLhZPM7INQbbrRWXEuKpzA8Xjco6OF+c/RCkxjHOXVW82NBo6061d9ip9ooeGn+m4A59golmzgmaoM599sc+9MYGpCSoQ7+Ec2/Mipzwq07sTwc+PVONB+WAaMC8JZD1KlAyUX933X6GrVh/IkLVe4RlrMIyTCUemqJ2sMH6F6+6KTTMawvRWcb/vTR0k/71YXZLOFeTkA9zRzYyBGSXcriFYRclUa54EtpIQTdPpYQ+y0QzTi7AXAm661G8muwqC2Xuv0Geih/lxx/FCmQAsdzY2Wn6uvHpHBloERT0HD1IemGhnOpET2HU8JWdcTjHslVGtnffEjPIrwwfAk2XmsnlQt1QUDd/ntXw+C4uR1tYBVtjDTgfM9+9NjEYAw==",
          "page_age": "3 days ago"
        },
        {
          "type": "web_search_result",
          "title": "Press Overview | Cloudflare",
          "url": "https://www.cloudflare.com/press/press-releases/",
          "encrypted_content": "Ev4JCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDIMhEWfWbvn1KKce8RoMA9O3uHxom90oTQMHIjCL+Gd0gOkY2Y3zf229H6BjgH3ftiUTknd58m80Dul62qAo+DCWuKCU2HUhEqz4PBMqgQnNNxSMyHuTzvaDp5Q3xaBI8pYDa22l/oLBb3YNuahzkYpSCSj6r1MFYnN0k3NR0EN9fpwcv3xD2AcFhd5QSazRQ9CpiPvtUOVmTWvTeIHpjD5IvqindGgVCtkxjlhUcuIRwyT+9wdKyfp3vsQtQ8zbCt/TZ4efNhDuB07LGHx7/dVk6+ph4dOpLXnTDXDhsapF7vBWfp6n59K9Le2eDH7mo5PdgSArTWhsUS55QmyzxdFIYlwr5FW88HowIOlJjY4L2oqqGwGi4LmlXSC3H5vktbm+Y1euiuOUIvUXThTOI/+6JE7XJWDgp25M2Xas4oKP1zOC4atGe0qbNebd86DZmwUCI4vJr+eDzn8SUhHz5cJ2thOm/NWRjhRv/FrNlTyno0NFxOb+C/GfngASYRfZ/dgHcTRb01ERcQBtOSjw8Obtcr/W8ZalMBSrGIy56LKcrmXrf9XC102c5IHThCWfmUAQVksj/T0ocFCSylW2Woygp1MRJH2szxUG9VBAd2lD9X+JQ2yhlvmHMG57hzCnhcJj3fbwN4B2BK8wbsSQIUHhX0gbd5sqgpkBI1oZhIhJhq2aAU3d6QrsIo5KCoDFuzj5hFIAISs2KyGYLf+mcMOuisY7cIe8dKXncM/2lQbILjxRJXdxPhSdMuNNuaX6ekEpTXAm26T2ccdMS3wi05UtuOMJ77imPzDfANrBQ4mwk05Ur5XrwAAoqZ2LCUzx4ThGFRvwhVR6OagpL/Ds7WYFGvPLOJ9B2oaDrRXWofofeAPPfPzkOTYLzzdWZzVxai0Y/Br5gD3Lr6D2Ck7BinMLQ8x1UIkw+INlBjTGjycDK0VNOoyXVEAxK1cI/56T2hVSCoTO8iZTjIh2Fw3RUJR0s3B6UNxmbvbeCnAC23zzw/KkpjxD1t0CdI4udNurIKV2Q00v860jss+OPAnSgeOPRxxg7zSpOuek8DaiMFb1GfE4ty5fvzXmFvjqgwHhsjlba0t/Xj8iECDqjbPij7r6U/C3y8Zv/XMQfL67ojifJn63BnrzmcSePYOXA5vUY5jZ9H8zzsVO7OwhmRf1C7VwXnjwOtcZkKtULOhoF7Mpc0+InZFbkYFqHBIbi7NTg3jN0M/vQnqWMTzPrcIhXuS5x4oyy0x5xFP0QA/F/oOA5375NtB+ppjH4uGi0c9k4lXvw+5Z3Pud+wMZ5R71tXIpTqcgxE1kFSnNoFkgDyOqVfEoaUTcVmZd6RS1qo6dAjEAZCbI3PsGQ/y4QcQT2WcG18OG8Pn+mDci/6PWWuTcUU83VawGKv0abAsocJ4aBjZXS7LjUP1NR4Brwd6OaKuPdZXdI2ppSwFkHxFRz4+bC+D0KhQ9O02gKaqFF
... response truncated ...
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

temperature

`number`minimum: 0maximum: 1

top\_p

`number`minimum: 0maximum: 1

top\_k

`number`exclusiveMinimum: 0

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.5/#page","headline":"Claude Opus 4.5","description":"Claude Opus 4.5 brings further reasoning, coding, and agentic improvements over Opus 4.1, with stronger tool use and tighter instruction following.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Opus 4.6 is Anthropic's flagship language model built for complex, multi-step work in coding, financial analysis, and legal reasoning. It uses extended thinking to work through complex problems carefully and features a one million token context window.
title: Claude Opus 4.6
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Opus 4.6

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.6/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-opus-4.6`

- Third-party
- Zero data retention

Claude Opus 4.6 is Anthropic's flagship language model built for complex, multi-step work in coding, financial analysis, and legal reasoning. It uses extended thinking to work through complex problems carefully and features a one million token context window.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://www.anthropic.com/claude/opus) |
| Zero data retention | Yes |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$5.00</li><li>Output (per 1M tokens)$25.00</li><li>Cached input (per 1M tokens)$0.50</li><li>Cache creation (per 1M tokens)$6.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.6',
  {
    max_tokens: 1024,
    messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.6",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
# The Laws of Thermodynamics

Here are the three main laws (along with the "zeroth" law often included):

## Zeroth Law
If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. (This establishes the concept of temperature.)

## First Law
Energy cannot be created or destroyed, only transferred or converted from one form to another. In essence, this is the **conservation of energy**. The change in a system's internal energy equals the heat added minus the work done by the system.

## Second Law
The total **entropy** (disorder) of an isolated system can never decrease over time. Heat naturally flows from hotter to cooler objects, not the reverse. This means no process is perfectly efficient, and it establishes the "arrow of time."

## Third Law
As a system's temperature approaches **absolute zero** (0 Kelvin / −273.15°C), its entropy approaches a minimum value. It is impossible to reach absolute zero in a finite number of steps.

---

Together, these laws govern how energy behaves in all physical and chemical processes, from engines to stars to biological systems.
```

```json
{
  "content": [
    {
      "text": "# The Laws of Thermodynamics\n\nHere are the three main laws (along with the \"zeroth\" law often included):\n\n## Zeroth Law\nIf two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. (This establishes the concept of temperature.)\n\n## First Law\nEnergy cannot be created or destroyed, only transferred or converted from one form to another. In essence, this is the **conservation of energy**. The change in a system's internal energy equals the heat added minus the work done by the system.\n\n## Second Law\nThe total **entropy** (disorder) of an isolated system can never decrease over time. Heat naturally flows from hotter to cooler objects, not the reverse. This means no process is perfectly efficient, and it establishes the \"arrow of time.\"\n\n## Third Law\nAs a system's temperature approaches **absolute zero** (0 Kelvin / −273.15°C), its entropy approaches a minimum value. It is impossible to reach absolute zero in a finite number of steps.\n\n---\n\nTogether, these laws govern how energy behaves in all physical and chemical processes, from engines to stars to biological systems.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01Ss13EYxkyh29CJXYkdhHk4",
  "model": "claude-opus-4-6",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 17,
    "output_tokens": 257
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.6',
  {
    max_tokens: 1024,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
    temperature: 0.3,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.6",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python.",
  "temperature": 0.3
}'
```

````
# Reading a JSON File in Python

Python has a built-in `json` module that makes it easy to read JSON files. Here are the most common approaches:

## Basic Example

```python
import json

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

print(data)
```

## Step-by-Step Breakdown

| Step | Code | Description |
|------|------|-------------|
| 1 | `import json` | Import the built-in JSON module |
| 2 | `open('data.json', 'r')` | Open the file in **read** mode |
| 3 | `json.load(file)` | Parse the JSON into a Python object |

## Common Scenarios

### Reading into a Dictionary
```python
import json

with open('config.json', 'r') as file:
    config = json.load(file)

# Access values like a normal dictionary
print(config['name'])
print(config['settings']['theme'])
```

### Reading a JSON String (not a file)
```python
import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)  # Note: loads() with an 's'

print(data['name'])  # Output: Alice
```

### Handling Errors
```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found!")
except json.JSONDecodeError:
    print("Invalid JSON format!")
```

### Specifying Encoding
```python
import json

with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
```

## Key Differences

| Method | Input | Use Case |
|--------|-------|----------|
| `json.load(file)` | **File object** | Reading from a `.json` file |
| `json.loads(string)` | **String** | Parsing a JSON-formatted string |

## JSON → Python Type Mapping

| JSON Type | Python Type |
|-----------|-------------|
| `object`  | `dict`      |
| `array`   | `list`      |
| `string`  | `str`       |
| `number`  | `int`/`float` |
| `true/false` | `True`/`False` |
| `null`    | `None`      |

> **Tip:** Always use the `with` statement when opening files — it ensures the file is properly closed, even if an error occurs.
````

```json
{
  "content": [
    {
      "text": "# Reading a JSON File in Python\n\nPython has a built-in `json` module that makes it easy to read JSON files. Here are the most common approaches:\n\n## Basic Example\n\n```python\nimport json\n\n# Open and read the JSON file\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n## Step-by-Step Breakdown\n\n| Step | Code | Description |\n|------|------|-------------|\n| 1 | `import json` | Import the built-in JSON module |\n| 2 | `open('data.json', 'r')` | Open the file in **read** mode |\n| 3 | `json.load(file)` | Parse the JSON into a Python object |\n\n## Common Scenarios\n\n### Reading into a Dictionary\n```python\nimport json\n\nwith open('config.json', 'r') as file:\n    config = json.load(file)\n\n# Access values like a normal dictionary\nprint(config['name'])\nprint(config['settings']['theme'])\n```\n\n### Reading a JSON String (not a file)\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)  # Note: loads() with an 's'\n\nprint(data['name'])  # Output: Alice\n```\n\n### Handling Errors\n```python\nimport json\n\ntry:\n    with open('data.json', 'r') as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"File not found!\")\nexcept json.JSONDecodeError:\n    print(\"Invalid JSON format!\")\n```\n\n### Specifying Encoding\n```python\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as file:\n    data = json.load(file)\n```\n\n## Key Differences\n\n| Method | Input | Use Case |\n|--------|-------|----------|\n| `json.load(file)` | **File object** | Reading from a `.json` file |\n| `json.loads(string)` | **String** | Parsing a JSON-formatted string |\n\n## JSON → Python Type Mapping\n\n| JSON Type | Python Type |\n|-----------|-------------|\n| `object`  | `dict`      |\n| `array`   | `list`      |\n| `string`  | `str`       |\n| `number`  | `int`/`float` |\n| `true/false` | `True`/`False` |\n| `null`    | `None`      |\n\n> **Tip:** Always use the `with` statement when opening files — it ensures the file is properly closed, even if an error occurs.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01XBD4XMEahrUEnEVbu4gPwV",
  "model": "claude-opus-4-6",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 29,
    "output_tokens": 643
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.6',
  {
    max_tokens: 1024,
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.6",
  "max_tokens": 1024,
  "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"
    }
  ]
}'
```

```
# Great Stops Between SF & LA

Here are some popular options depending on your route:

## Coastal Route (Highway 1) 🌊
This is the scenic route (~8-10 hours with stops):
- **Half Moon Bay** – Beautiful coastal town, great seafood
- **Santa Cruz** – Boardwalk, surfing, laid-back vibe
- **Monterey/Carmel** – Monterey Bay Aquarium, 17-Mile Drive
- **Big Sur** – Stunning cliffs, Bixby Bridge, McWay Falls
- **San Simeon** – Hearst Castle, elephant seal colony
- **San Luis Obispo** – Charming college town, great food
- **Santa Barbara** – "American Riviera," wine country, beaches
- **Solvang** – Danish-style village with bakeries & windmills

## Inland Route (I-5) 🚗
This is the fastest route (~5-6 hours):
- **Harris Ranch** – Popular rest stop with a restaurant
- **Bakersfield** – Buck Owens' Crystal Palace (country music)
- Not as scenic, but efficient!

## Tips:
- ⛽ Fill up before Big Sur (limited gas stations)
- 📸 Start early for the best light on Highway 1
- 🏨 Consider an overnight stop if taking the coastal route

**Which route interests you more – scenic or fast?**
```

```json
{
  "content": [
    {
      "text": "# Great Stops Between SF & LA\n\nHere are some popular options depending on your route:\n\n## Coastal Route (Highway 1) 🌊\nThis is the scenic route (~8-10 hours with stops):\n- **Half Moon Bay** – Beautiful coastal town, great seafood\n- **Santa Cruz** – Boardwalk, surfing, laid-back vibe\n- **Monterey/Carmel** – Monterey Bay Aquarium, 17-Mile Drive\n- **Big Sur** – Stunning cliffs, Bixby Bridge, McWay Falls\n- **San Simeon** – Hearst Castle, elephant seal colony\n- **San Luis Obispo** – Charming college town, great food\n- **Santa Barbara** – \"American Riviera,\" wine country, beaches\n- **Solvang** – Danish-style village with bakeries & windmills\n\n## Inland Route (I-5) 🚗\nThis is the fastest route (~5-6 hours):\n- **Harris Ranch** – Popular rest stop with a restaurant\n- **Bakersfield** – Buck Owens' Crystal Palace (country music)\n- Not as scenic, but efficient!\n\n## Tips:\n- ⛽ Fill up before Big Sur (limited gas stations)\n- 📸 Start early for the best light on Highway 1\n- 🏨 Consider an overnight stop if taking the coastal route\n\n**Which route interests you more – scenic or fast?**",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_019VVbDba57acjUFWYzMdWQV",
  "model": "claude-opus-4-6",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 76,
    "output_tokens": 340
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.6',
  {
    max_tokens: 512,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    temperature: 0.8,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.6",
  "max_tokens": 512,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "temperature": 0.8
}'
```

```
# The Orchid on the Windowsill

Detective Mara Solis had seen her share of crime scenes—enough to know when something didn't belong.

The apartment was almost aggressively ordinary. Beige carpet, IKEA furniture, a stack of unopened mail on the kitchen counter. The victim, Gerald Pryce, age fifty-two, accountant, had lived the kind of life that left barely a thumbprint on the world. Even in death, slumped against his recliner with a single stab wound beneath the ribs, he seemed to be trying not to make a fuss.

But there, on the windowsill above the kitchen sink, sat a black orchid.

Not dark purple. Not deep burgundy masquerading as black under bad lighting. Mara leaned closer, pulling on a fresh glove, and tilted the pot toward the gray morning light filtering through the blinds. The petals were the pure, liquid black of a moonless lake—a color that shouldn't exist in nature.

And as far as the department's botanist would confirm six hours later, it didn't.

"No soil," Mara murmured, peering into the ceramic pot. The orchid's roots wrapped around nothing but a small, folded piece of vellum paper, yellowed at the edges. She extracted it with tweezers and opened it carefully.

A single line, handwritten in red ink:

*He was not the first, and you already know me.*

Mara set the note down. Her hands were steady. Her pulse was not.

She read it again—not because she needed to, but because some part of her recognized the handwriting.
```

```json
{
  "content": [
    {
      "text": "# The Orchid on the Windowsill\n\nDetective Mara Solis had seen her share of crime scenes—enough to know when something didn't belong.\n\nThe apartment was almost aggressively ordinary. Beige carpet, IKEA furniture, a stack of unopened mail on the kitchen counter. The victim, Gerald Pryce, age fifty-two, accountant, had lived the kind of life that left barely a thumbprint on the world. Even in death, slumped against his recliner with a single stab wound beneath the ribs, he seemed to be trying not to make a fuss.\n\nBut there, on the windowsill above the kitchen sink, sat a black orchid.\n\nNot dark purple. Not deep burgundy masquerading as black under bad lighting. Mara leaned closer, pulling on a fresh glove, and tilted the pot toward the gray morning light filtering through the blinds. The petals were the pure, liquid black of a moonless lake—a color that shouldn't exist in nature.\n\nAnd as far as the department's botanist would confirm six hours later, it didn't.\n\n\"No soil,\" Mara murmured, peering into the ceramic pot. The orchid's roots wrapped around nothing but a small, folded piece of vellum paper, yellowed at the edges. She extracted it with tweezers and opened it carefully.\n\nA single line, handwritten in red ink:\n\n*He was not the first, and you already know me.*\n\nMara set the note down. Her hands were steady. Her pulse was not.\n\nShe read it again—not because she needed to, but because some part of her recognized the handwriting.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01Q6DJ95CWj3L7QbCZ7onQHq",
  "model": "claude-opus-4-6",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 21,
    "output_tokens": 374
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.6',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.6",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
# Understanding Recursion

## The Concept

**Recursion** is a programming technique where a **function calls itself** to solve a problem by breaking it down into smaller, simpler sub-problems. Every recursive function needs:

1. **Base Case** – A condition that stops the recursion (prevents infinite loops).
2. **Recursive Case** – The function calling itself with a *smaller* or *simpler* input.

> **Think of it like Russian nesting dolls** 🪆 — you keep opening a smaller doll until you reach the tiniest one (the base case).

---

## Simple Example: Factorial

The factorial of `n` (written `n!`) is:
`5! = 5 × 4 × 3 × 2 × 1 = 120`

```python
def factorial(n):
    # Base case: stop when n is 0 or 1
    if n <= 1:
        return 1

    # Recursive case: n * factorial of (n-1)
    return n * factorial(n - 1)

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

---

## How It Works (Call Stack)

```
factorial(5)
│
├─ 5 * factorial(4)
│      ├─ 4 * factorial(3)
│      │      ├─ 3 * factorial(2)
│      │      │      ├─ 2 * factorial(1)
│      │      │      │      └─ returns 1  ← Base case hit!
│      │      │      └─ returns 2 × 1 = 2
│      │      └─ returns 3 × 2 = 6
│      └─ returns 4 × 6 = 24
└─ returns 5 × 24 = 120 ✅
```

---

## Key Takeaways

| Aspect | Description |
|---|---|
| **Base Case** | `if n <= 1: return 1` — stops the recursion |
| **Recursive Case** | `n * factorial(n - 1)` — moves toward the base case |
| **Risk** | Missing a base case → **infinite loop** (stack overflow 💥) |
| **Alternative** | Most recursive solutions can also be written as **loops** (iteration) |

> **Rule of thumb:** If a problem can be defined in terms of a *smaller version of itself*, recursion is a natural fit (e.g., tree traversal, searching, sorting, mathematical sequences).
````

```json
[
  {
    "message": {
      "content": [],
      "id": "msg_01LArxxRsu9fHtfj6gJafVbZ",
      "model": "claude-opus-4-6",
      "role": "assistant",
      "stop_details": null,
      "stop_reason": null,
      "stop_sequence": null,
      "type": "message",
      "usage": {
        "cache_creation": {
          "ephemeral_1h_input_tokens": 0,
          "ephemeral_5m_input_tokens": 0
        },
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "inference_geo": "global",
        "input_tokens": 19,
        "output_tokens": 1,
        "service_tier": "standard"
      }
    },
    "type": "message_start"
  },
  {
    "content_block": {
      "text": "",
      "type": "text"
    },
    "index": 0,
    "type": "content_block_start"
  },
  "... 25 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting Claude use Anthropic's server-side web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.6',
  {
    max_tokens: 4096,
    messages: [
      {
        content:
          'What were the top news stories about Cloudflare this week? Summarise in three bullets.',
        role: 'user',
      },
    ],
    tools: [{ max_uses: 3, name: 'web_search', type: 'web_search_20250305' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.6",
  "max_tokens": 4096,
  "messages": [
    {
      "content": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
      "role": "user"
    }
  ],
  "tools": [
    {
      "max_uses": 3,
      "name": "web_search",
      "type": "web_search_20250305"
    }
  ]
}'
```

```
Here are the top Cloudflare stories from this week:

- **Stock sell-off after hitting all-time highs:**
```

```json
{
  "id": "msg_0124yvsiaRLxSucPPhVpHMyp",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01HJTfCwJbChdHyNG7e9uyMB",
      "name": "web_search",
      "input": {
        "query": "Cloudflare news this week June 2026"
      }
    },
    {
      "type": "web_search_tool_result",
      "tool_use_id": "srvtoolu_01HJTfCwJbChdHyNG7e9uyMB",
      "content": [
        {
          "type": "web_search_result",
          "title": "Cloudflare Status",
          "url": "https://www.cloudflarestatus.com/",
          "encrypted_content": "EvMZCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDDjjKdyL5Ab/6fUtRxoMXhDU69Ff82RQJhIaIjASlWZZI/KAn0OPduSzbmeecKpiqKEKvfz0FalDTVCPrLwuRKiP4hxLkwI0DZtngPwq9hiQRJQ4Xya+Jx2wjTZnUxELAK4lsqWxwO063ch6yaSuVasHhU209pktawAHlv2/LTKboE84PN+E5HftwgsFttmWMXY5hF0DncZOMGOHXmsy2Lu8lCLJ9NwqygZeSaxdQaiXIBXYoc/2u7ewUv3wOV7GbAQHv1QUmgFKLikuz6fyDqDQopMrRKDQlThiC43DNaMJzD30v2S/UIPQVjNjFCLPEX9ba/E+VhP0rRVXd4ZSoKlM9TUc9Vmbl6X49AZ9xyA2/LuEB2JtimNjqxbwbMbk9PkObsit8CY9ECw9qYZkGp9gnoJJLb2RtPbWTo/K2HujGmjhdISogIMcyQ/zDfQtJSq5XzfGN5IJ7jTsmNEkzUKlmc8oa3/UsnmihQ1YQ5PFn9ECKvmvjgqoKxDM4NpNtnJ25LES0NM4Tu0AxfRAjKhkYqNcZGxjyZnqklUFtl5mND4auu5P6mSk+BTPGiD+8g+DwLS31uSiRdiD3r25Yatt5N8Lds+7EVxDTG2fMnFC+QMvKIG/TpxzOE8NJsdPJzqdr18YZDKIct8ylC76HgmOj8HS3pxhFNQFvn0SM0tMX8keySMUkS9G2P6QKsDjIbOgjMD7qtkYyy+ZkdoNM7vI3ZkQiKIqxrxp/wphnGXeHdZ6b/pq8KccKFUgZTq7H3k5SHV8c4/IE0v3buV+TwEstW7aiutjT081hmUNHYff54HRdxDitr7ZsOZua3ZMlDQ95isIT4BlQDruMU6ueijlaQvE+VeA58X+Uoo6bQhPeGq7OdngqxjOLFQJQO7++ZMfmEJyO35zcR00dev6oMX+TPIeaE/wEQpDiczLGsyvcpltl//maBuFP8H1FM5Ss3ivEHDpXl6qCHccdo166lFFDfCPxmkGFN4CZHF1xL2+nd5GVTE6i3dwgTkvRuLeIq9/zTZBQwpXiU0GfKFigFnLjRr0QYQVRwr1WNAopw4drSGNLPd9pYZT+O29UkeLngPwTCdgUFSqj9uNeufqKfjNbZVffyY1kiFT6/EzXoPO8fiS61TDTiEN7SZZkWD1whOWAJspON3DgANkSE5ezhER5gUeydi26Pa/c2n23axHCxAKG6754uQHlIt0AY6D3KumMI1M6dJhvqT5h12uH6BulZIHYB+j7VCWJGMlDfDPLpI9w4TJIjblpTE6M9vSIilcEPtJ9M8O5/qlrhLjFl4EOxvUTGnJ/3xIj1AwiC9osdhNmh+KPF3wWowGiFcH8p6CHF3GgQr8Zm8QU3rXorIhhXRFNr98sNsJWwt1wGeP279lSUaPE4CLap5H1Ro3kU7L27OmmhrwdJ9QfQwSfEF9PGoJ0bHG5SIv79rTaMEZIuMs7C69waxU1Ut3wNiVtCI6HuWE2smxrD50/vadQnVst2YXVUjb4lXJhkxU2FF0cdQstPO9agV/xdNrbwePSdM7XULPJpUpyKodKgJbq6O3G91QDmr8hxlz2phEYnDv/RU2WYw75S2o5a59CkQ55ARzTZ9ot69H8sm9MektrBH8jgggYi+gf4ho+CEK73IJO63/kkTYvnPGeCSgrovU1d+FISUlwRZ2fQID6BAbyqLb42mcwo9wq6QtNP5QYe3DIb3bvBCLI3fXF7RldKf0U81DxB9/ILEjRrwfVh3NJq7nS1wuSc4u76vy64m+XB6vZHiUUyI/EZVqQcPYCYWLMqBwhwE/1vj2IJ7+VAJqmaAl0k2WgouNTeJxbQL2Z/wmAuP7Wp7BKAZxDZ2XUCrLeqFRDbuh0SzfC+NM5YHTDGZCh92Udv016VbeFNOG4Ijy7qPNqN+dpTpRudxfbidi6Yc2A0UVyI/ETHC34sLE3Gu6hAKz/dovq/DVjAy+b7GwFm5B9FXXGnIDEndkKoxRRDVRWqZOZ7hY1j3+6jnQy7ikCWBzzNYAZ+JL0zYfJrfFp80UpnS9Uew9KyvTsEZmzRR/EfDIjgmGdnfbf4AIj5Ptq9yJu8GngaExNKlovNqBQ/PrvQTQ8hT3RyV5e1kxk1ua396Kjd531q0bMDfwdkRDvbSf30tpgBmoxawoINdWU7uOC/5kyGz0Q0FjgkRL25PFhyH9cNqcdoe4AYlhyTQtpVRyQkAZzDvNlTZ2u2XCnjcRYl893gubcvtEgbZZonQbfHsM0PRoqMkhDuHYE6MwbCwDRPui9FVfITU/HZZDTrQLI7gJKexR8NcdmStZJ/tAFPRt++wOHaNHn4Xbf8ObJTjuQWBQDFJNSAQXh7AsYi56hMcfgYu+1q726puKO0cbrRPFE5c0i6R5TKr139aecDxxsSBOk8gysSaNPFtEY7WqWRUxz/+8y0qBweImz5mTqbtAQ4r/coR2boEtV1VyDcJ4GG0Q6Vjt+BuNIH2rHmAG1VYR29kB4FNEFhfF4GdhEhXh8LYZTgZWdJ4OzOOJdp0C8J19Ux+6jkhKVZtwDZmsvAVr0rGot8qQ7Gd6mv8VLWTLZA/UUeVvf7CTc+D/Dl7GmDgtwN1TaoEVidq7I7QgrPJhlszFbM0YiJlEf86cVTl9ZYR43ihAPws52KdZF+3Y7GeudrT5Rs5Tuf/jCBKLhmn2lZPwp6GFXQpi1cyWDHGtCjVhl3Wiwtu2ww+ZmQsZP8egnIuFYtIo68Q5nSpfMvbdYOzBqt/G4flWvo+zWArOpxT5nZBzWMqOiRuEO9tasXrUhoz1eQn0qE1U3XZCFZhSuRZsQplQsgyjftEj/HhTpvnIcPBlXQ3ohBG3t8g1NAHFoIpFT9LVmX8DAIqCNHBpPutoayJfkzeQZRp0wMzcBkcfCkZP3+3vLQ5XV8RklgpUexkGRE7nKCIns6ER8P99yiaFhdLs+5KMR9AIgvrxCst+4WBk10D+Dv1HHgDYcmQeNO9WNdVLDM989UNVpbFI6iV791Vp80rGCJg8NGsmyBk+fbmD1UpGu2KOzqG91OI7m1ABdB/hTsdU4zj6ArsPCy+WlCdBKlZAj9ebAFoGMT1Z+0Lc+xAItu/ZW9zlOi3zCefYG2uMydsU8IF9OY+1xHah3lKUp/GJocRGNdQUFfbckdNnglNkfK+1QIEeP04jMzJfkqbv3zIeexT7kcGXSdnwjzQGDjiCfpTW/gEq5oPf27Xw9qw2+6JB+q7GTJNF6FCpVROneLjDywTqa7iDBmmHUp4Z651wuNZgCMsl2RWHqpoOPuaVzv7r7IpuX7FaWXjwYz+WcC4fGG9j+rDbBrAjxkoi4sy8RS5906sI91bxhX2KsmMVQrmrH5vjvmciF2E2HivBfqb5ZfDJG5XxVg/pC58r7hEXzXqmgPV45hON3drr12UgAX5zeF0wuY9zgnNVEiTMcKppB2GowbFgHSNfWk7xOaZgGqOAe30267ZyOHBz9ASlov90KAaFm510azeZqSS49u4h4L+fz6pnTbbW+hkcdHLjMjFTFbPXkKQq20YesbvMJnK+uU8b0krSvNDKrR9W+c2cVSzKkm3basL1nV4hZxCCTp4lCxb6LUqdx6u5PidyzZIxn6tleTVTqiAUIHRWRpR6PCWuFiQqUYoY6m0oxf7NsPfOVDOTDafwmJ9IjWg88ibkxfA2YozsTBa8PIudZmUQG5x5nZk2ZWnkX4SSUQPrsyGcsCQ5qKV64OxBW/P5ob2BGz2hX2ANi0DkPWb4WYZu0Po6oxSekFbsaWJF9ksMXGTTCgHb03txFLI0KDHvcV1o/t6fOTG4uWKp1YZYGm2iFNiVY7JFPeC5Td9Iiw4KCHjVfq/JA8c0xxxq1WZeuJfIpUZGmoRuD0rM1H0bjSb3gRGe6+j7VXREhWF6x+/J29lSjSPzYF6qQ3q65SUHrM5zx1ZyagBVLLmYnTEVwUvWLLpyVNtbSy7LurTiPdfws76Vkkec++YjM06MPEblfazyUrUermDTTYKvMwnRJiVIiK2CMYNmXlAIeLqWIzeZ0NBukoSYK+AcKAukciVZMFs7unktUX41xfNbS2EPmdvca8mTA4AxQYN3eVHDajlMPbYye9vFw6LUJpQsqRbFVvohfhDs73bmXgV6YjEn6DPRjdIAsouMGD+HUOX11ZbVM4I4L5SbVrh9YMes2UjX52tmEU2uE7zvDywkcSP6K1T1W11O6pnfqZhysx58/j5bLi91A4rIeUVMly/bX7ZbLpNwdkjpCrCjnQh6l9C34E0yskBsLH5qtuGDFvJISoTqsLd0ylmLaFFWZCiq0Dut4FRP7u0Az7QFYcNPub0arV3Xb/G4XIe/a7XGoG0jCIzHSBsSl1HIGAM=",
          "page_age": "2 hours ago"
        },
        {
          "type": "web_search_result",
          "title": "Cloudflare Release Notes - June 2026 Latest Updates - Releasebot",
          "url": "https://releasebot.io/updates/cloudflare",
          "encrypted_content": "EswgCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDPcRa1wq+J1voL95DxoMyXNJsxqC48mJ03nPIjDedKLdipqDZPcnHKaLQZS1C3UEuKAN3KH439LLJ/dgsGjb7wCy7btkvLBRtBdQ53gqzx8+hS+sUgtBJcThyCXbNrCxuZm4Q0NDXEQ4cihQCRRUHIyTZYMm02PqI+dzRGjIDOsC21qBDgJepm7wAkFSRR5xPTa8FTPOGl82BL3X2VQJSfbGJrsp0JD0mcfQ3Fva8r+Hx3GeXUHFHk5bXVnGLKvGSM1BsQSg+xF5q/LUGZJjKP3bWNg27izuWyArPL/5mrxV4nCCHOcvSM2bbL2wepzH/GXmm/eyqHsE7qopJQiLbUnkn69BeWlu4ljnP3hYhyZ7WsXW3dSdFyARlrIdDQXPV4O3BjrJX/oQsAUeprYNiINDI5v5jPpP5AwEvvoNospgKTAD52XV3bLgdXcf98+H7ewz8xrQhN1LlqhbrZVEPbLcAQ7jxmQFohDdIOzZ9yHuyJc7E4CN7EQBknBIkJoPzghR+qFjIoh1Q0Eyt4TwHQRDuNt5ot1nmGLro4fY7Ar5QPzm+AikYEp/xDoEZG5S7v0zqU+XUS+/uHEL2qJkKU0Jp6Co72L/oj/yI7oOvfnEFHLbdZtKWQmezbnOwxdIYOV370ZT1RZ3pKy+D6bAGdVYmLz25PQV92J8C4JHWBlnU/PX1WFXoP2uOZVMObDOTqADJuLsQ/S9f9vE+AkhGd6M3KHpv0DZgFh/vDVuqCwRgg6VbRVa2+V5tibL//TpL6Jq/kbesLSB2QJ8f+T3WG8XHmCfvkoJpqHgU6cw2nd5+UUpF4vphUu1XiJPxEpXfKJx1+gadepdVUrTlr4NA+1HCB6syPVaeq6/ZzXpRo5g1qGRb6O7Y5oQogPVDOkTwW366BNvD7unAV4/6ZCDWwYqr/Kslixf5/UZJVdc6HXx/LdWiSLGbQx/kRBykkEgBQdOf/opEbN/aQ2w0YJ+reg4o5t1wI5roccBr7mbyTb/alpClzEJ4vWTkM4NktukRjEKZpfVioSKmhg503GQEjn30eNkLwWJvRkRbKtAgJLI43CbBfSMjl8BG5WzUGflygzFtDN3GzyeEbwxf0oulT77/xuxpWHpug8yTzYDvxmwropyrXRoNghZqE5JgsveP5eL9hsQ6p+VWDkMBRAJi9kSGiMQosUT4UqJjmvK5EIlCpJG+93iJSsbmdk1dxF3yJ6O1Go1uJCCE5Wv7nOirecP7m0+vQkWOfYpi27hpvgXBrrWUPxhqEfVNJOQ8xXLb7x0Ou5RkMJs3rG2mZELGi/8YKFUsZPKoy7kPlpiaxeyVIO+1uy+KCN9DmLne0Qtd5ghiEsy5n+KCRsTeEvKgjBzZa2uqjdPgUZSU5vpjACFEA6XeHFV8yP56c8fZryvc4ZPqeOLW4lxJVwkM/cf1g1cxEvoq6AweCJ5PjmFHfpegG4G7LC+T1rDn3mwXNQ5/bX0RVJWEiJmYhPUKIAFgB+ZCGqg6ClTXS9QT7EAufNMDYvdyXqxtg6s6hBOPZtsUmXGvotUwQE2Q4e/zIpvBJ8yn77ivL/HalJbqVMMEWj2lWJQ5K0AuFwBjUZFYPiKGb1/C+fneC66KCcAfyCE1i1TS2Pk4GNnJswt9zxt/J//zb8//gnJKvXt5E/EivLrI0uCYMRjOMFhQyV5Is04AaUoKamxeNwWiP+DF03al479+ssR/vuaPaJ5hSJkAT/CxNe575Cnyuy6MO1QGiL9syMZFqpzClH2QVJ5Q2pncMIC3+jXJ87epmQl1erUYPp0AvNcoZALNRyPm3dlCBzUQznRDhMdt9AbrHSel/ZezOpLmv81jnNWa2JUJLdaHjBh+oa9y96ZOTWSrI9MtULlnquM+XRCkCLRWENJrnroukeKI5yl4gO0GzeFw8toUl6W7RP4O21FhgSLS4g+iJuudJvPx0i8YUDfhTdBejY+kkuczXX3YY4/uQrjrGVWGCTcX6SVQfepoOkyJFVXdQ4kgmjvOntWjuMtFnNgMM9sV3Hi4wHOdbzLxoI0miiHI3zlXzwtj7yI+rt5XFU16662DwPBphNj7R1DsD7/QoboLdVk4Ges4XqsHCbAbKYGTGHS4PudTzlr7g7cOqrVj65xVnVxiySKwpxM9VGxPTa08CQoassZP+k1mmTUnsBt+dDT33ITXJ6S15FgJ0h0qLx0C6EW3wvpew6YcaXd1W1XXvfaY13MOTYUsjmgedYT5OlrqtE2T+koesMOJM09s/a+LV3k8H+3LxMeZ3xEZgVYSvVbHFkhvuiRRgiLsqX++7DJywdrG7i7lmoJfv09+BdQhVkqtfPGdbwbq3nkvs+QBEjTFPs2IvW5ZDy1mb25wG/cXg1v1VZd+W40nGLUbNx1VW2VZ1o6+NxJpgxuxA0lVdEpZYBv5qGva5zJDx8FL2CIBNi7K8QndNhWvHarklRonts/+AH2eFZgSsBU1jYpRbSC5fZjMoEiXlkNh9/socs7RgR+oBF2IsjOXlNjGnWhh1NDPhW1AYY9kiNyCCDkGCwk5/aqUoja4/1j0SiGouuDqm/Z1JMS/wKYvKHniUEAl0J824eBfjhJVABlLV7VqMIEjTnerTSItauxzX3rZ6pl+Vc
... response truncated ...
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

temperature

`number`minimum: 0maximum: 1

top\_p

`number`minimum: 0maximum: 1

top\_k

`number`exclusiveMinimum: 0

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.6/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.6/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.6/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.6/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.6/#page","headline":"Claude Opus 4.6","description":"Claude Opus 4.6 is Anthropic's flagship language model built for complex, multi-step work in coding, financial analysis, and legal reasoning. It uses extended thinking to work through complex problems carefully and features a one million token context window.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.6/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Opus 4.7 is Anthropic's most capable generally available model, with a step-change improvement in agentic coding over Claude Opus 4.6. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing.
title: Claude Opus 4.7
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Opus 4.7

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.7/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-opus-4.7`

- Third-party
- Zero data retention

Claude Opus 4.7 is Anthropic's most capable generally available model, with a step-change improvement in agentic coding over Claude Opus 4.6. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://www.anthropic.com/claude/opus) |
| Zero data retention | Yes |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$5.00</li><li>Output (per 1M tokens)$25.00</li><li>Cached input (per 1M tokens)$0.50</li><li>Cache creation (per 1M tokens)$6.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.7',
  {
    max_tokens: 1024,
    messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.7",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
# The Three Laws of Thermodynamics

**First Law (Conservation of Energy):**
Energy cannot be created or destroyed, only transformed from one form to another. The total energy of an isolated system remains constant.
- Often expressed as: ΔU = Q − W (change in internal energy equals heat added minus work done by the system)

**Second Law (Entropy):**
The total entropy (disorder) of an isolated system always increases over time, or remains constant in ideal reversible processes. Heat naturally flows from hot to cold, never the reverse without external work.
- This law explains why perpetual motion machines are impossible and why processes have a preferred direction.

**Third Law (Absolute Zero):**
As a system approaches absolute zero (0 Kelvin or −273.15°C), its entropy approaches a minimum constant value. It's impossible to reach absolute zero in a finite number of steps.
- A perfect crystal at absolute zero would have zero entropy.

**Bonus — Zeroth Law:**
Often mentioned alongside these: if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This is the basis for temperature measurement.
```

```json
{
  "content": [
    {
      "text": "# The Three Laws of Thermodynamics\n\n**First Law (Conservation of Energy):**\nEnergy cannot be created or destroyed, only transformed from one form to another. The total energy of an isolated system remains constant.\n- Often expressed as: ΔU = Q − W (change in internal energy equals heat added minus work done by the system)\n\n**Second Law (Entropy):**\nThe total entropy (disorder) of an isolated system always increases over time, or remains constant in ideal reversible processes. Heat naturally flows from hot to cold, never the reverse without external work.\n- This law explains why perpetual motion machines are impossible and why processes have a preferred direction.\n\n**Third Law (Absolute Zero):**\nAs a system approaches absolute zero (0 Kelvin or −273.15°C), its entropy approaches a minimum constant value. It's impossible to reach absolute zero in a finite number of steps.\n- A perfect crystal at absolute zero would have zero entropy.\n\n**Bonus — Zeroth Law:**\nOften mentioned alongside these: if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This is the basis for temperature measurement.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_013pmj6hy6QcjydL7goWQBZ7",
  "model": "claude-opus-4-7",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 25,
    "output_tokens": 399
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.7',
  {
    max_tokens: 1024,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.7",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python."
}'
```

````
# Reading a JSON File in Python

Python has a built-in `json` module that makes reading JSON files straightforward.

## Basic Example

```python
import json

with open('data.json', 'r') as file:
    data = json.load(file)

print(data)
```

## Key Points

- **`json.load()`** reads from a file object and parses JSON into Python objects
- **`json.loads()`** (with an "s") parses JSON from a string
- JSON objects become Python **dictionaries**, and JSON arrays become **lists**

## Complete Example

Suppose you have `data.json`:
```json
{
    "name": "Alice",
    "age": 30,
    "hobbies": ["reading", "hiking"]
}
```

You can read and access it like this:

```python
import json

with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)

print(data['name'])        # Alice
print(data['age'])         # 30
print(data['hobbies'][0])  # reading
```

## Handling Errors

It's good practice to handle potential errors:

```python
import json

try:
    with open('data.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found")
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")
```

## Bonus: Writing JSON

To write data back to a JSON file:

```python
import json

data = {"name": "Bob", "age": 25}

with open('output.json', 'w', encoding='utf-8') as file:
    json.dump(data, file, indent=4)
```

The `indent=4` argument makes the output nicely formatted. Let me know if you'd like help with a specific JSON structure!
````

```json
{
  "content": [
    {
      "text": "# Reading a JSON File in Python\n\nPython has a built-in `json` module that makes reading JSON files straightforward.\n\n## Basic Example\n\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n## Key Points\n\n- **`json.load()`** reads from a file object and parses JSON into Python objects\n- **`json.loads()`** (with an \"s\") parses JSON from a string\n- JSON objects become Python **dictionaries**, and JSON arrays become **lists**\n\n## Complete Example\n\nSuppose you have `data.json`:\n```json\n{\n    \"name\": \"Alice\",\n    \"age\": 30,\n    \"hobbies\": [\"reading\", \"hiking\"]\n}\n```\n\nYou can read and access it like this:\n\n```python\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as file:\n    data = json.load(file)\n\nprint(data['name'])        # Alice\nprint(data['age'])         # 30\nprint(data['hobbies'][0])  # reading\n```\n\n## Handling Errors\n\nIt's good practice to handle potential errors:\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r', encoding='utf-8') as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"File not found\")\nexcept json.JSONDecodeError as e:\n    print(f\"Invalid JSON: {e}\")\n```\n\n## Bonus: Writing JSON\n\nTo write data back to a JSON file:\n\n```python\nimport json\n\ndata = {\"name\": \"Bob\", \"age\": 25}\n\nwith open('output.json', 'w', encoding='utf-8') as file:\n    json.dump(data, file, indent=4)\n```\n\nThe `indent=4` argument makes the output nicely formatted. Let me know if you'd like help with a specific JSON structure!",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_013KNtXimWjxydHNC1qfHzwP",
  "model": "claude-opus-4-7",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 43,
    "output_tokens": 587
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.7',
  {
    max_tokens: 1024,
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.7",
  "max_tokens": 1024,
  "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"
    }
  ]
}'
```

```
Great choice to explore along the way! Here are some popular stops, organized by route:

## If Taking Highway 1 / Pacific Coast Highway (scenic, ~9-10 hours driving)

- **Half Moon Bay** – Charming coastal town, great for breakfast
- **Santa Cruz** – Boardwalk, beaches, and redwoods
- **Monterey** – Famous aquarium and Cannery Row
- **Carmel-by-the-Sea** – Quaint village with art galleries
- **Big Sur** – Stunning cliffs, Bixby Bridge, McWay Falls
- **Hearst Castle** (San Simeon) – Historic mansion tours
- **Morro Bay** – Iconic Morro Rock and sea otters
- **Pismo Beach** – Sand dunes and beach town vibes
- **Santa Barbara** – "American Riviera," wine, and Spanish architecture

## If Taking I-5 (fastest, ~5-6 hours)

- **Harris Ranch** – Famous steakhouse and rest stop
- **Kettleman City** – Gas and snacks (not much else!)
- I-5 is efficient but pretty barren—mostly farmland

## If Taking US-101 (middle ground, ~6-7 hours)

- **Gilroy** – Garlic capital, outlet shopping
- **Paso Robles** – Excellent wine country
- **San Luis Obispo** – College town with great food
- **Solvang** – Charming Danish-themed village
- **Santa Barbara** – Worth visiting on this route too

## Questions to help narrow it down:
1. How many days do you have for the trip?
2. Are you more interested in nature, food, history, or beaches?
3. Traveling solo, with family, or friends?

Let me know and I can build a more detailed itinerary!
```

```json
{
  "content": [
    {
      "text": "Great choice to explore along the way! Here are some popular stops, organized by route:\n\n## If Taking Highway 1 / Pacific Coast Highway (scenic, ~9-10 hours driving)\n\n- **Half Moon Bay** – Charming coastal town, great for breakfast\n- **Santa Cruz** – Boardwalk, beaches, and redwoods\n- **Monterey** – Famous aquarium and Cannery Row\n- **Carmel-by-the-Sea** – Quaint village with art galleries\n- **Big Sur** – Stunning cliffs, Bixby Bridge, McWay Falls\n- **Hearst Castle** (San Simeon) – Historic mansion tours\n- **Morro Bay** – Iconic Morro Rock and sea otters\n- **Pismo Beach** – Sand dunes and beach town vibes\n- **Santa Barbara** – \"American Riviera,\" wine, and Spanish architecture\n\n## If Taking I-5 (fastest, ~5-6 hours)\n\n- **Harris Ranch** – Famous steakhouse and rest stop\n- **Kettleman City** – Gas and snacks (not much else!)\n- I-5 is efficient but pretty barren—mostly farmland\n\n## If Taking US-101 (middle ground, ~6-7 hours)\n\n- **Gilroy** – Garlic capital, outlet shopping\n- **Paso Robles** – Excellent wine country\n- **San Luis Obispo** – College town with great food\n- **Solvang** – Charming Danish-themed village\n- **Santa Barbara** – Worth visiting on this route too\n\n## Questions to help narrow it down:\n1. How many days do you have for the trip?\n2. Are you more interested in nature, food, history, or beaches?\n3. Traveling solo, with family, or friends?\n\nLet me know and I can build a more detailed itinerary!",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01FmPy3fWFf7w6Sx6ECEdKnh",
  "model": "claude-opus-4-7",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 114,
    "output_tokens": 621
  }
}
```

</details>

<details>

<summary>**Creative Writing with Adaptive Thinking** — Use adaptive thinking with high effort to steer creative output -- the recommended replacement for the deprecated `temperature` parameter.</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.7',
  {
    max_tokens: 2048,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    output_config: { effort: 'high' },
    thinking: { type: 'adaptive' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.7",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "output_config": {
    "effort": "high"
  },
  "thinking": {
    "type": "adaptive"
  }
}'
```

```
# The Wrong Kind of Silence

Detective Mara Halloran had worked enough crime scenes to know that rooms had voices. A kitchen where someone had fled mid-breakfast hummed with interruption. A bedroom after a struggle kept the echo of it in the disarranged sheets, the lamp knocked just-so.

But the study at 14 Pearsmont Lane was quiet in a way she didn't recognize.

She stood in the doorway, coffee going cold in her hand, and tried to name it. The body had already been photographed and carried out—Gerald Finch, seventy-two, retired cartographer, found slumped over his desk by the housekeeper at half past six. No forced entry. No wound. The coroner was calling it natural until the tox screen said otherwise.

Mara stepped inside. Bookshelves. A globe. The smell of pipe tobacco clinging to the curtains like an old apology. Everything where a dead man's things ought to be.

Except.

On the desk, beside the blotter where Finch's forehead had rested, someone had laid out seven grains of rice in a perfect, deliberate row.

Not spilled. Not scattered. *Placed.*

She crouched until her eyes were level with the desktop. The grains were evenly spaced, each one turned so its seam faced the same direction—north, if she was reading the window light right. The housekeeper hadn't mentioned them. The first responders hadn't logged them. And Gerald Finch, according to three separate statements, hadn't eaten rice in forty years. Couldn't stand the stuff, his sister had said. Something about the war.

Mara straightened slowly, her knees protesting, and felt the quiet of the room press against her ears.

Seven grains. Facing north. On the desk of a man who drew maps for a living.

"Well, Gerald," she murmured, reaching for her notebook. "Who were you trying to tell?"
```

```json
{
  "content": [
    {
      "text": "# The Wrong Kind of Silence\n\nDetective Mara Halloran had worked enough crime scenes to know that rooms had voices. A kitchen where someone had fled mid-breakfast hummed with interruption. A bedroom after a struggle kept the echo of it in the disarranged sheets, the lamp knocked just-so.\n\nBut the study at 14 Pearsmont Lane was quiet in a way she didn't recognize.\n\nShe stood in the doorway, coffee going cold in her hand, and tried to name it. The body had already been photographed and carried out—Gerald Finch, seventy-two, retired cartographer, found slumped over his desk by the housekeeper at half past six. No forced entry. No wound. The coroner was calling it natural until the tox screen said otherwise.\n\nMara stepped inside. Bookshelves. A globe. The smell of pipe tobacco clinging to the curtains like an old apology. Everything where a dead man's things ought to be.\n\nExcept.\n\nOn the desk, beside the blotter where Finch's forehead had rested, someone had laid out seven grains of rice in a perfect, deliberate row.\n\nNot spilled. Not scattered. *Placed.*\n\nShe crouched until her eyes were level with the desktop. The grains were evenly spaced, each one turned so its seam faced the same direction—north, if she was reading the window light right. The housekeeper hadn't mentioned them. The first responders hadn't logged them. And Gerald Finch, according to three separate statements, hadn't eaten rice in forty years. Couldn't stand the stuff, his sister had said. Something about the war.\n\nMara straightened slowly, her knees protesting, and felt the quiet of the room press against her ears.\n\nSeven grains. Facing north. On the desk of a man who drew maps for a living.\n\n\"Well, Gerald,\" she murmured, reaching for her notebook. \"Who were you trying to tell?\"",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_019oiL5qvRdHBpPLrsS5x3Ux",
  "model": "claude-opus-4-7",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 31,
    "output_tokens": 628
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.7',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.7",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
# Recursion Explained

**Recursion** is a programming concept where a function calls itself to solve a smaller version of the same problem, until it reaches a simple case it can solve directly.

## Two Essential Parts

Every recursive function needs:

1. **Base case** — a condition that stops the recursion (prevents infinite loops)
2. **Recursive case** — the function calling itself with a smaller/simpler input

## Simple Example: Factorial

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

- `5! = 5 × 4 × 3 × 2 × 1 = 120`

Notice that `5! = 5 × 4!`, and `4! = 4 × 3!`, and so on. This self-similar pattern is perfect for recursion.

```python
def factorial(n):
    # Base case: stop when n is 0 or 1
    if n <= 1:
        return 1
    # Recursive case: n × factorial of (n-1)
    return n * factorial(n - 1)

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

## How It Works (Step by Step)

When you call `factorial(5)`:

```
factorial(5) = 5 × factorial(4)
             = 5 × (4 × factorial(3))
             = 5 × (4 × (3 × factorial(2)))
             = 5 × (4 × (3 × (2 × factorial(1))))
             = 5 × (4 × (3 × (2 × 1)))     ← base case hit!
             = 120
```

## Real-World Analogy

Think of **Russian nesting dolls** 🪆. To find the smallest doll, you open one, find another inside, open that, find another... until finally you reach the tiniest doll that doesn't open. That "tiniest doll" is your base case.

## Key Takeaway

Recursion is elegant for problems that can be broken into **smaller versions of themselves** — like traversing trees, navigating folders, or solving puzzles like the Tower of Hanoi. Just remember: **always include a base case**, or your program will crash with a stack overflow!
````

```json
[
  {
    "message": {
      "content": [],
      "id": "msg_018UiizftMy3k3UwQepmrFxq",
      "model": "claude-opus-4-7",
      "role": "assistant",
      "stop_details": null,
      "stop_reason": null,
      "stop_sequence": null,
      "type": "message",
      "usage": {
        "cache_creation": {
          "ephemeral_1h_input_tokens": 0,
          "ephemeral_5m_input_tokens": 0
        },
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "inference_geo": "global",
        "input_tokens": 27,
        "output_tokens": 6,
        "service_tier": "standard"
      }
    },
    "type": "message_start"
  },
  {
    "content_block": {
      "text": "",
      "type": "text"
    },
    "index": 0,
    "type": "content_block_start"
  },
  "... 27 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting Claude use Anthropic's server-side web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.7',
  {
    max_tokens: 4096,
    messages: [
      {
        content:
          'What were the top news stories about Cloudflare this week? Summarise in three bullets.',
        role: 'user',
      },
    ],
    tools: [{ max_uses: 3, name: 'web_search', type: 'web_search_20250305' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.7",
  "max_tokens": 4096,
  "messages": [
    {
      "content": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
      "role": "user"
    }
  ],
  "tools": [
    {
      "max_uses": 3,
      "name": "web_search",
      "type": "web_search_20250305"
    }
  ]
}'
```

```
I'll search for recent Cloudflare news from this week.
```

```json
{
  "id": "msg_01BWg8R9cfU4m8VTrQPMZdAd",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll search for recent Cloudflare news from this week."
    },
    {
      "type": "server_tool_use",
      "id": "srvtoolu_013S4aGzYgyxQ9sNuA6ALc9i",
      "name": "web_search",
      "input": {
        "query": "Cloudflare news this week"
      }
    },
    {
      "type": "web_search_tool_result",
      "tool_use_id": "srvtoolu_013S4aGzYgyxQ9sNuA6ALc9i",
      "content": [
        {
          "type": "web_search_result",
          "title": "Cloudflare Status",
          "url": "https://www.cloudflarestatus.com/",
          "encrypted_content": "EqYhCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDLs6yt+/C7NMzOOHuxoMfTrWTeKpYPg+/WbNIjCFn887ycJ9IIR83SGr7fQLeFOx5RyYkg4b2vu3Kxx5CJjqZq0iBUS8XDbIN0bRJrEqqSDFr1NwMDgiuLoIP5k0+NybFDI+GQtwOUBoMimnyOJJOSXC5ANC4ub/VgsHGe7C2TGmbHlQmMpq9DpsM2A3Y3rXZPImB/HQOl5Fmq2h6cOK8FyYn3cJzxPcfQoRli5gZKGRuTzA6LnSDu5SdnjIEVsmsIWU+Ua+4S/xPFSM2BtJJhMZ8dLwFgUX6IJk1UB5uGEBQXNGa+QG1w/WyOtkLKAzguXxaxPKuHUpki2gX9oQ2hTt/zn/xfssQs00Tkpy1aFnsW5MPnwhEN07CDp3lO2RtjXDRXiQ8ctOHuzLbf5hGALkQvRkMsHqN6smzg1dj1mBb6DMtPZNOn/AZUfHmzRsDksbH2XvCu5Jr/HWjBq/NFUc8bcw5hzUTEHGKagdoyUJee6BKVpB0psAvrTw8gR53Im3CYmJE9nqkBJLdEptMGM/DHJ4t9ad0Wv9uSBUTaf+7njuBQI/tEX31pFHco0hSqN59o2cr9Va6V4phUH7gZtqhZXLzNdZ50r4L/+becTwHs3te6tiLNiE4MAGuzK+7+icPfS30W0ycHrO9l3bszUItc6ngs6I5G0DugXxSZibu9rIOW9xRrEIHMhmm3X3ftvMr2dyGxzlvLSxkZ74haaxywGe3nqmfUZo9h1uo94NxEA/Ye6+keKnQil09zZDsuWG+DxDQLXSJ+zDfpESmyizBtx68eC42ZyzmdM3mpjgo1txe6HegJt5W1mpJ/GETXtKXtMTryaocI2MagG7CYBvzc4mvBnBzR3T6XT+kvc0teo1uuERonRKqBqXtWHQGiyCdYdbMdISW/AOFhHJbBwm95oHED7omyJ4Y3SU0j/EYm13rRWcwsDkTbK7U6HVOO6lCek1yOFKX4dcsSoM+6XU7/dFONstzrRkBl0D1kV+mHK2+urcq5UNzXXZUPZKYKleEVdNQVOys0eGEWN6/q/yLnrindtPd1I4/h4fO+GSCjmjrIJKJxOH3BGyG8WUuNvgq3K/FWn8f+xRDf2U6cqHaZNr6EGDWH5ZajCKBrmqlrc5gmHdzIlTL+2U4qrJwh4Vp/TIvo7f9l0a2J00Fawlsud0NH86gMB6R5L1meDNq8Acm6c6vz4KLJ8Hlo9kv061EQEmkK0MdydHXjrnGw14WUmnr0IZBqTpphAbP4AFOPJNGsiMzB3MlxX8As4Irpp8U9CB+y6p7JVmLHABp4Ilsq3co+xjcplx1dHNtM0OsMPd9K8/AnMSBcOg+pfvkZF12t5du1cO9vVAaUTsA6rdPL2UE1l+MgHSAKM8vxEWi0LOJEHtn+yo34Bcjzv1SyWvV63l1vI5oK+3BOM7cQfFipJXqEiQJjLk2YjUmFTT0fwwMPdmRwKMrSpwetdokvwtAZHWfHLCvpduCjek4UzM9Gknww/Lf0YeIFtZtWQJYwnTobwKlqH18eOs+GCDHsOfc3wLwycKsxzOppX1m8JHEl9AOekjXUpU6AYo/tuHkSV6VtqOiL+zNfrAHeAGZrHSesaoKEnK2wFVVysnZjR4qry34J6LLY3cpy1ErBC0na6ix3XhzDlrk7TnfHsVKDdj2Hx96lK99ZelqMXJRs0VUSD2R/zRWVpIqGXL3JjCEXqgKITdkuLcr0GdWlmRLDRjd3poNsVRX1wALK6Ue2rlyRqoKbhinSGQp7hhnHLR7BApf4LtrsHhiryNOOZmEYhBZ4xpEaFh5962NX8Yno4EmxoU6lRxxySSlGWa1+Lm5OmTQ8iDHMGrFgpvWu6Zqcaq2z8b9eoe9T53LS+icRao09aIltgfOz/CV3PfoDP9ssy8jmkWOCDxLZiRpugDYRJb2PT040i5eiRiS7Gsbo3VS8Bq05EynUp8hq9bs1McmDTvaWLtlhUD2imk69kE/5/T65/FbypwXeWCPYHsRT0n4V1M3ljWP7HLHPKpuOnMN7KWStDZaTNN/KcZNGF2W1l76o4G6Nqz/K8tmF08Zhxr6SKGmW9eZw0sN4KsDc/sqYf1KYmV4Q/oO7a0uyIHtAYkVAg2UyxPLQiCp4ScZ+vtWmZEH46GtbEIeEJ2OJhlwCyYoHpPB6ZNa/Bx+5EfUUbp3IzjkA/mfNcUOXsCS5WTi9XMGKfskR6EQsCYTg3wQgavqUV1I2cK29GDhMZtOUmn2OIQUNDBbopKddWwmATnT8wQSiugTovwsQuQT9ml751oYugkhZVhDYaqjjQGRX6F/+qMDCtNZw59GJzMARIrnDCymcL9NkkjNxPt7hmoNq5qd0V00wt+q4InD3DHejDhac+UzW/rUMTQj8WNmXmnCZz0IoZbTS5wHAGsOmYUCZePExSG1ep4MHK7pJKr9XLB+KZ4oxGSmYXPC1QggSl+Ddbugb88nDPvyTfHnBYpoQ7z+jpTbwEMtDJ+I2Ig2pPdY4KnzouKvNb1P5GscjXu2MnYly63nxOTWK/+ccIxw69dpuzBOsTzfeN9ecf9s8WIrzwkANOxfILXPXJoEY3pTMFJAFqFgyA/NsIBYftukw+lIr4qlLJSDOD6bc0jR/+eWH+rgJaC0SS+Pd1uT9VkSTBx2ivtr//RCamH7OPxazBj4Hzplx+1PT45YABe3/a4Rtgb19H8mJcvU31NdYHveHWd4OFcqL9MqlKaE/O3Pr+dbhsjIm+HNN6QUD89CERXtP4H4MXNBj0vgHiVe6HizPov8Ll2UHNf0d/Nb/dgI5tfP2cfh3o5/sMPviRmU34E4ntRmdyz+e9Bq3ga6h8PcykxijuMJl3sdvlqUt3KcKWEPCioSxA4HgTKmy0bmhaOAWnC3CKzZ9jP8UXnbNIygMDmoXx8IcmZBCMKLAf38jXKGdb07QivO6fOsvizygl///TeKvwEpH/ylI8QgI8/Cnj9yRqbcclsno03E60JdUWQtuIUMfCYukgH4TNhlEAR2IEYyjigRktwHvgam11vCQdA+yD/9ztQ3pqcks0sAjzXHi8QM4dahW1sE6zNpIxV45Dc0fcA9p1dWyn2tQ36rawrmEGrUA7z67XrM+tbHHYSCU0lHDEiGqa3AqiXwFggSddMpRT7+XK1RQfIHA1IGPanvJLltjLek6XvkKfeULpIra21/N9z7FyRTI+RKG1IJxJLkejOfj3iZgQHVb+kKqJcRjGRmAWNgcrU9Ojl8f6/0CSylqA6QjwZkyA1wlF1BRu5u1eoNKf6eRZBalsFuuDapeZaYWSyBwo+GOGSNqd57JZGj67eQMyE3pC3CHINyeoFlrBom0adlAb2yktQJ88TKjS/7eO5jaMfkwuCOtpgjwkfxmcvX332pO9vnn3vO9YEdB6Ixw4NrKjfgMpVSLaDtXI6qgJSjLBl0aunS/gm77radNk2IpDBmqeM+FPTsntujJ1EZK2EPrUUru86CGk5PS+B2Y/e/04jMR9lbg4S7fsYVESlWXrAdJF8MQpxoFsAsOBPD3PcFtAMcPcl6BqpaLyWmz04AyY8ge6hhLA5Vfb9pH614LQ2FCZSRqL1SQJMSwaCACMQ9+w++v6j6U7OkW/XbyU0oM8YYIquizyLeya2Ocsf8fNwg8CTIsLYax9pwWNUB8MGJXF9BlaUx4U9u3yhvCm6p4/0WI0c0e7M5zGjUUluqPdLsv/5A/RkXsv5sPo/4HJzJygYTKFstb46ACuRw7roTYGUqHXHYvq78g/9vLIZ2i05SeX+/GTZOGSsKDO1ImCORhPoPtcoR7p1K+i7vsjIGY2XYoPsdIgHi+005o5tsnYp9ln3VjZpo5cpKs/3QrxZ7zFUbNYQrSxrGpKeaSsCVAj+ZemOoXNoNDrwMa7GfgqXePbVV5f9vaLBUisfzcR0N/HN3ZOrOGzpALyHZcIhloWEAUXEvGfODXQoO4T5ZEnL0DBzP8XFZ1eH6Jkn6uI9OM7ejxs3+uyEaMx27h5fF7h7+5ZbnEgt9z3wq9LLvpWyyosZn7qSwRzIZ5dDu2L/bnqd0VS1YchLquzL6LLu+OUpn9j4QQiPH10wjzaLa2cB2oo/DefRQsP86vHc/zuhbYy7u3BvkKOqtQFA5y1kgBsY+mx4gH+K13e8ZM53WNKC1wGX2nEgMt0/BHN0xlT4MRr3VyXpicepp19oMbXVnjKOKifyzCCH2hRgPEVd9nSROvX9662tGtHFpkyxwWev/NKvovBTUOTRiFEK2AuK4SVNkfBBACYiWTrjoF+xCt1w/IAUhuuSpe3yj8BEht0qbGf8MsSmidhsxMEcAYNmGS/1Y2tWT5lCezQaMoFTB9wDMky2OuDnhJb4cV5HdroACZND6pgTqsT2k32YCD/+wW1MDjYCem/Y/kIisVdgTkm9lUpINREocShZ9z+Zhy6SfDzLvq1mGWk4tqqIcWbokZo539DcSppBNOX9Rx1tn/s3PlbVqaSmU3wjxQEKZJw//9mRL7qyFaEDkslkNqWUA2G4QCqvATWCswoj1V50HApoIR/Cy4um9UXKIZIyJpF/iMH2y6OkhRgKVKC2SMygGqDr9Ng6Yznwb+UJMxgZZX4De2RS/et6uPYBApf51irpxoWUZDU9lam5rArP5ONOca9dgdhPZppgEWzQsfD8gLvGeDuFSBFXXtznVJTrsfS4C3vWAYkgtjdYSi8PiuKpPj5IrQ0c5b/ftWS6i3Cfp1l4jvDWiQGOO1qD6C0XENaemJQl7kZ/aTMVxrLky6RWDaQcWMSCOkS4+ch30vQuI8dR1++KlBVA/UpTpimh9y8hCswN+AC6b/hhTQne/yyQucfeqidssmI5lQghLl6B+qbZhnA1/jyt0CHB+Xao0MxEY7WMcq+Ro8JeqPw5N+Cft0NLUlqTyhXivh1U3mDIHSrfzYMB8SNLiw5h3ybuUuc54Ug0LJNv+OgekArzKE2oAx9+vm1HTr/qp/tm0kYgOBT+mBn8AXpKTui4ygqDcisrcW6indctb7gmdPfUHgolVW556qcG2eVEmBxajx6fwJ2TCK/XGXy31fidf4hMTfZMAyq/FN788bZg7c+XEk5SHoPAXhMrSjK8JjDxyBHF56sy0lPwPvb6enZwqpwtZBQdgDBZgO26CT/gXB4LLIPHgkop1lScelSuN0o/KAxTedV6vqylwpVGwyUw0tE/7D2FgtAGt5QX42x0ufEVvtQY6EAXbbrsY2YTKFw0mv53YyIbEQtHG6ZQL8MIfSQ8tJuR/jllpPoPe26K75OrFnaEkAadVP4dfefnLJ2eJhLki5QHj0a6vmoGJ6n9RrmRlqLouqh91/AT5biWjM/YGuO0yTHdq7on/KAb8hyDkfkXSfQO8/p8bdgCWOd2yoKaBR2J1W0VFOrUUtAhy8hh9yxlQ22FKVaZzieR2d5W1vqxK65C9ZIpHF3Fsqu0OgnoX4BRstIzEoTnvaa44XvfiLMFfYH3PUZD2jebAAgBusIU7drs7DlWrd2H6Yk/XLK2SxhpBjkNtLJznagZSELhjNSx6+yPDjbZszyM1ubBfOYYLjTV41QDDDeWz70G+ysSppwY+nCLz1s6x6cfBQHNGsgfGWPdFrPmjtWQLOw+MAoYAw==",
          "page_age": "2 hours ago"
        },
        {
          "type": "web_search_result",
          "title": "The Cloudflare Blog: Product News",
          "url": "https://blog.cloudflare.com/tag/product-news/",
          "encrypted_content": "Eq4RCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDMOia1KDnEAH6YOevhoM/n5JLAXIcCPYQUntIjAcreSbXVbIEBZ6wML6d5qHBiTW/YkxJE1sENIYaoVcijt0HiWuN123Vk3tyTfulFAqsRDV9Cez6XIUaUNEG6jLYDyFl3s9rG0jWvTdQsh0qpeL4GdE6z8Mw+3gVNRDgDwXGB7URA66VLON7JKg51WKMhjC+UrlUwS1yXd0so65XfczRpxhWKxSJgGwCD8Gx5RHO2aPV4x4fOO5wT/Q2Clsw3xVRaRfcMLPh7bqIS71NYhTVsF/jTPj5iA5elgeeA2EvFZXcSobGpyPjbbeAj/ZeLpOd2j2ftPZ2wt4B66T2tKnFkBywz2dKuI+VqpjQD/XpvwHmVthHuGj3Jac0gcmsXi3PuiTuaPNYM9EZILXpIRW1R6+ZKAvc1rqa6gcNIEnS3mBGe5s7DSyYMgQQLi8gSyGJNpn+0HdYXDe5aBmL/gVOz4bjBUSfT5LpglG+gbk1NnNVVy13ETbPnA9pgZkzhNmIeaa3F891lSGC3xzsyA31FIejMLKuECWUt5JWEIc4A/rJUVASx76/YQVrVHngyIsQqHHE89U0SHkBEpub4S9widPpZwRCbzGnIs3iYWsr9e8jG6OOk+OGNnvmVX2I7q3Jsr6Gd9muh1A8uC13OMdadNlN5lrfXYIdUvxdDE647F0d6tyUjIfBMvDCIYBwOpvC727GsLS8bLGDVa6qNYXj/1S6zYUefjLAQa6kui/XtCUuAloCYp3WznON2vKjZ4FQxu+xi2Xp5mUdMMJ4jR46gz+if9GVjYbcQfJtrzR4rCJAA+MM4I3nSQBMnk2mT6bDhjcYPbRHDbuKkbToda13O/HVJ0WZ30/l8SNkklA/d4XUQzjU50SwASiNEQ01cB93LutVyK8g2PEKesJFJb1VtqFkardOt+WmMyqqmNe3QnOnlSR6UKhnGzjYmVhOmOsgqPQ9XElxbkRPWL6MLRl6lmQge8OzYYmYw58bQcResej8/GGrk6OvIEpAOH+9UJ2cDGr8TAlSY0KiBLtNx43p2VHn23jpwm/3z4UTR9grzNaeBYg0CRKsIemUKoYphcrtsZml2raQDzVVDBSOYdt/zcZWr6RdDITlIkPwszDJt8XkjIKzReTILfeIRp41/0NVLJGw3shElB+LRI/xJR661Sc4XvwGn5iZbFOzehItFvOKfyFNIp7BxCU50NudkvfnSdG443E4dv369Ak5iNr7IS/iTzzHaHSkEkqC4c+iAOPfSgA57xt8PF85I4wOFiEWjEi4ckpFLY0k
... response truncated ...
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.7/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.7/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.7/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.7/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.7/#page","headline":"Claude Opus 4.7","description":"Claude Opus 4.7 is Anthropic's most capable generally available model, with a step-change improvement in agentic coding over Claude Opus 4.6. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.7/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Opus 4.8 is Anthropic's most capable generally available model, with a step-change improvement in agentic coding over Claude Opus 4.7. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing.
title: Claude Opus 4.8
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Opus 4.8

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.8/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-opus-4.8`

- Third-party
- Zero data retention

Claude Opus 4.8 is Anthropic's most capable generally available model, with a step-change improvement in agentic coding over Claude Opus 4.7. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://www.anthropic.com/claude/opus) |
| Zero data retention | Yes |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$5.00</li><li>Output (per 1M tokens)$25.00</li><li>Cached input (per 1M tokens)$0.50</li><li>Cache creation (per 1M tokens)$6.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.8',
  {
    max_tokens: 1024,
    messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.8",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
# The Three Laws of Thermodynamics

## First Law (Conservation of Energy)
Energy cannot be created or destroyed, only transferred or converted from one form to another. The total energy of an isolated system remains constant.

**Common expression:** ΔU = Q − W
- ΔU = change in internal energy
- Q = heat added to the system
- W = work done by the system

## Second Law (Entropy)
The total entropy (disorder) of an isolated system always increases over time, or remains constant in ideal reversible processes. Heat naturally flows from hot to cold, never spontaneously the reverse.

**Key implications:**
- No process is 100% efficient
- Perpetual motion machines are impossible
- The universe tends toward greater disorder

## Third Law (Absolute Zero)
As a system approaches absolute zero (0 Kelvin, −273.15°C), its entropy approaches a minimum constant value. It's impossible to reach absolute zero in a finite number of steps.

---

**A popular informal summary:**
1. You can't win (you can't get more energy out than you put in)
2. You can't break even (you'll always lose some energy to entropy)
3. You can't quit the game (you can't reach absolute zero)

*Note:* There's also a **Zeroth Law**, which states that if two systems are each in thermal equilibrium with a third system, they are in equilibrium with each other—this establishes the concept of temperature.

Would you like a deeper explanation of any particular law?
```

```json
{
  "id": "msg_01UPuL7ZtkoyKHmCsNtxyamj",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "# The Three Laws of Thermodynamics\n\n## First Law (Conservation of Energy)\nEnergy cannot be created or destroyed, only transferred or converted from one form to another. The total energy of an isolated system remains constant.\n\n**Common expression:** ΔU = Q − W\n- ΔU = change in internal energy\n- Q = heat added to the system\n- W = work done by the system\n\n## Second Law (Entropy)\nThe total entropy (disorder) of an isolated system always increases over time, or remains constant in ideal reversible processes. Heat naturally flows from hot to cold, never spontaneously the reverse.\n\n**Key implications:**\n- No process is 100% efficient\n- Perpetual motion machines are impossible\n- The universe tends toward greater disorder\n\n## Third Law (Absolute Zero)\nAs a system approaches absolute zero (0 Kelvin, −273.15°C), its entropy approaches a minimum constant value. It's impossible to reach absolute zero in a finite number of steps.\n\n---\n\n**A popular informal summary:**\n1. You can't win (you can't get more energy out than you put in)\n2. You can't break even (you'll always lose some energy to entropy)\n3. You can't quit the game (you can't reach absolute zero)\n\n*Note:* There's also a **Zeroth Law**, which states that if two systems are each in thermal equilibrium with a third system, they are in equilibrium with each other—this establishes the concept of temperature.\n\nWould you like a deeper explanation of any particular law?"
    }
  ],
  "model": "claude-opus-4-8",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 20,
    "output_tokens": 493
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.8',
  {
    max_tokens: 1024,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.8",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python."
}'
```

````
# Reading a JSON File in Python

Python's built-in `json` module makes this straightforward.

## Basic Method

```python
import json

with open('data.json', 'r') as file:
    data = json.load(file)

print(data)
```

- `json.load()` reads from a **file object**
- The `with` statement automatically closes the file

## Reading from a JSON String

If you have JSON as a string (not a file), use `json.loads()` (note the "s" for "string"):

```python
import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)

print(data['name'])  # Alice
```

## Example with Error Handling

```python
import json

try:
    with open('data.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
        print(data)
except FileNotFoundError:
    print("The file was not found.")
except json.JSONDecodeError:
    print("The file contains invalid JSON.")
```

## How JSON Maps to Python

| JSON          | Python   |
|---------------|----------|
| object        | `dict`   |
| array         | `list`   |
| string        | `str`    |
| number (int)  | `int`    |
| number (real) | `float`  |
| true / false  | `True` / `False` |
| null          | `None`   |

## Accessing the Data

```python
# Given: {"users": [{"name": "Alice"}, {"name": "Bob"}]}

print(data['users'][0]['name'])  # Alice

# Loop through items
for user in data['users']:
    print(user['name'])
```

Let me know if you'd like help with **writing** JSON files or handling more complex structures!
````

```json
{
  "id": "msg_01Vo4yZSkvQT8zgudnTpsjtt",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "# Reading a JSON File in Python\n\nPython's built-in `json` module makes this straightforward.\n\n## Basic Method\n\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n- `json.load()` reads from a **file object**\n- The `with` statement automatically closes the file\n\n## Reading from a JSON String\n\nIf you have JSON as a string (not a file), use `json.loads()` (note the \"s\" for \"string\"):\n\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)\n\nprint(data['name'])  # Alice\n```\n\n## Example with Error Handling\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r', encoding='utf-8') as file:\n        data = json.load(file)\n        print(data)\nexcept FileNotFoundError:\n    print(\"The file was not found.\")\nexcept json.JSONDecodeError:\n    print(\"The file contains invalid JSON.\")\n```\n\n## How JSON Maps to Python\n\n| JSON          | Python   |\n|---------------|----------|\n| object        | `dict`   |\n| array         | `list`   |\n| string        | `str`    |\n| number (int)  | `int`    |\n| number (real) | `float`  |\n| true / false  | `True` / `False` |\n| null          | `None`   |\n\n## Accessing the Data\n\n```python\n# Given: {\"users\": [{\"name\": \"Alice\"}, {\"name\": \"Bob\"}]}\n\nprint(data['users'][0]['name'])  # Alice\n\n# Loop through items\nfor user in data['users']:\n    print(user['name'])\n```\n\nLet me know if you'd like help with **writing** JSON files or handling more complex structures!"
    }
  ],
  "model": "claude-opus-4-8",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 38,
    "output_tokens": 555
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.8',
  {
    max_tokens: 1024,
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.8",
  "max_tokens": 1024,
  "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"
    }
  ]
}'
```

```
Here are some great stops along the way, depending on which route you take:

## Coastal Route (Highway 1 / Pacific Coast Highway)
*More scenic but slower—adds a few hours*

- **Santa Cruz** – Beach boardwalk and classic seaside vibes
- **Monterey** – Famous aquarium and Cannery Row
- **Carmel-by-the-Sea** – Charming village with art galleries
- **Big Sur** – Stunning coastline, Bixby Bridge, McWay Falls
- **Hearst Castle** (San Simeon) – Historic mansion tours
- **Pismo Beach** – Sand dunes and laid-back beach town

## Inland Route (I-5)
*Fastest but less scenic*

- **Not many highlights**—mostly farmland, but quick gas/food stops
- Good if you're short on time

## Middle Route (Highway 101)
*A nice balance of speed and scenery*

- **Gilroy** – Garlic capital, outlet shopping
- **Paso Robles** – Wine country with great tasting rooms
- **San Luis Obispo** – Cute college town, historic mission
- **Santa Barbara** – Beautiful "American Riviera," beaches and Spanish architecture
- **Solvang** – Quaint Danish-style village

## A Few Questions to Narrow It Down:
1. How much time do you have for the trip?
2. Are you more interested in nature, food/wine, or towns and attractions?
3. Are you doing it one-way or round-trip?

Let me know and I can help build a more detailed itinerary!
```

```json
{
  "id": "msg_01La2dbCTcjvDFxNBTcwH4B9",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Here are some great stops along the way, depending on which route you take:\n\n## Coastal Route (Highway 1 / Pacific Coast Highway)\n*More scenic but slower—adds a few hours*\n\n- **Santa Cruz** – Beach boardwalk and classic seaside vibes\n- **Monterey** – Famous aquarium and Cannery Row\n- **Carmel-by-the-Sea** – Charming village with art galleries\n- **Big Sur** – Stunning coastline, Bixby Bridge, McWay Falls\n- **Hearst Castle** (San Simeon) – Historic mansion tours\n- **Pismo Beach** – Sand dunes and laid-back beach town\n\n## Inland Route (I-5)\n*Fastest but less scenic*\n\n- **Not many highlights**—mostly farmland, but quick gas/food stops\n- Good if you're short on time\n\n## Middle Route (Highway 101)\n*A nice balance of speed and scenery*\n\n- **Gilroy** – Garlic capital, outlet shopping\n- **Paso Robles** – Wine country with great tasting rooms\n- **San Luis Obispo** – Cute college town, historic mission\n- **Santa Barbara** – Beautiful \"American Riviera,\" beaches and Spanish architecture\n- **Solvang** – Quaint Danish-style village\n\n## A Few Questions to Narrow It Down:\n1. How much time do you have for the trip?\n2. Are you more interested in nature, food/wine, or towns and attractions?\n3. Are you doing it one-way or round-trip?\n\nLet me know and I can help build a more detailed itinerary!"
    }
  ],
  "model": "claude-opus-4-8",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 103,
    "output_tokens": 537
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Creative Writing with Adaptive Thinking** — Use adaptive thinking with high effort to steer creative output -- the recommended replacement for the deprecated `temperature` parameter.</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.8',
  {
    max_tokens: 2048,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    output_config: { effort: 'high' },
    thinking: { type: 'adaptive' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.8",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "output_config": {
    "effort": "high"
  },
  "thinking": {
    "type": "adaptive"
  }
}'
```

```
Detective Mara Voss had seen a thousand crime scenes, but never one this tidy.

The apartment was immaculate—books aligned by height, not a dish in the sink, the dead man arranged on his sofa as if posing for a portrait. No signs of struggle. No forced entry. Just Walter Crane, sixty-three, eyes closed, hands folded across his chest like a man who'd decided to nap forever.

It was the chess set that stopped her.

She crouched beside the small table, careful not to touch. The board was mid-game, pieces scattered in the chaos of a real match—except for one. A black knight, removed from play, stood at the very center of the board where no square could hold it properly. Balanced on the dividing line between two squares, defying the geometry of the game.

Someone had placed it there. Deliberately. The angle was too perfect, the position too impossible to be an accident.

Mara pulled a pen from her jacket and leaned closer. There, etched into the felt base of the knight in letters so small she had to squint, was a single word.

*Soon.*

She felt the cold travel up her spine before her mind caught up to it.

"Detective?" Officer Reyes called from the doorway. "Coroner's saying natural causes. Heart gave out."

Mara didn't look away from the knight. "No," she said quietly. "Somebody wanted us to think that."

She straightened, scanning the too-perfect room with new eyes.

The game wasn't over. It had just begun.
```

```json
{
  "id": "msg_01D5U1NAjKU24Fq5Q1bsyG9a",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Detective Mara Voss had seen a thousand crime scenes, but never one this tidy.\n\nThe apartment was immaculate—books aligned by height, not a dish in the sink, the dead man arranged on his sofa as if posing for a portrait. No signs of struggle. No forced entry. Just Walter Crane, sixty-three, eyes closed, hands folded across his chest like a man who'd decided to nap forever.\n\nIt was the chess set that stopped her.\n\nShe crouched beside the small table, careful not to touch. The board was mid-game, pieces scattered in the chaos of a real match—except for one. A black knight, removed from play, stood at the very center of the board where no square could hold it properly. Balanced on the dividing line between two squares, defying the geometry of the game.\n\nSomeone had placed it there. Deliberately. The angle was too perfect, the position too impossible to be an accident.\n\nMara pulled a pen from her jacket and leaned closer. There, etched into the felt base of the knight in letters so small she had to squint, was a single word.\n\n*Soon.*\n\nShe felt the cold travel up her spine before her mind caught up to it.\n\n\"Detective?\" Officer Reyes called from the doorway. \"Coroner's saying natural causes. Heart gave out.\"\n\nMara didn't look away from the knight. \"No,\" she said quietly. \"Somebody wanted us to think that.\"\n\nShe straightened, scanning the too-perfect room with new eyes.\n\nThe game wasn't over. It had just begun."
    }
  ],
  "model": "claude-opus-4-8",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 26,
    "output_tokens": 483
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.8',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.8",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
# Understanding Recursion

**Recursion** is a programming technique where a function solves a problem by calling itself on a smaller version of the same problem.

## The Two Essential Parts

Every recursive function needs:

1. **Base case** — the condition that stops the recursion (prevents infinite loops)
2. **Recursive case** — where the function calls itself with a simpler input

---

## Simple Example: Factorial

The factorial of a number (written as `n!`) is the product of all numbers from 1 to n.

```
5! = 5 × 4 × 3 × 2 × 1 = 120
```

Notice that `5! = 5 × 4!`, which means we can define factorial **in terms of itself**.

### Code Example (Python)

```python
def factorial(n):
    # Base case: stop when we reach 1
    if n == 1:
        return 1
    # Recursive case: n × factorial of (n-1)
    else:
        return n * factorial(n - 1)

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

---

## How It Works (Step by Step)

When you call `factorial(5)`, it unfolds like this:

```
factorial(5) = 5 × factorial(4)
             = 5 × (4 × factorial(3))
             = 5 × (4 × (3 × factorial(2)))
             = 5 × (4 × (3 × (2 × factorial(1))))
             = 5 × (4 × (3 × (2 × 1)))      ← base case reached!
             = 120
```

The function keeps calling itself until it hits the **base case** (`n == 1`), then the results "bubble back up."

---

## A Helpful Analogy 🪆

Think of **Russian nesting dolls**:
- To open the biggest doll, you open the next smaller one, and so on.
- Eventually you reach the **smallest doll** that can't be opened (the base case).
- Then you put them all back together.

---

## Key Takeaway

> A recursive function breaks a big problem into smaller, identical sub-problems until it reaches a case simple enough to solve directly.

**⚠️ Warning:** Always include a base case! Without it, the function calls itself forever and crashes (a "stack overflow" error).

Would you like to see another example, like calculating a Fibonacci sequence?
````

```json
[
  {
    "type": "message_start",
    "message": {
      "model": "claude-opus-4-8",
      "id": "msg_01NE3P8zwFrzpbFfPc6mV1FW",
      "type": "message",
      "role": "assistant",
      "content": [],
      "stop_reason": null,
      "stop_sequence": null,
      "stop_details": null,
      "usage": {
        "input_tokens": 22,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "cache_creation": {
          "ephemeral_5m_input_tokens": 0,
          "ephemeral_1h_input_tokens": 0
        },
        "output_tokens": 3,
        "service_tier": "standard",
        "inference_geo": "global"
      }
    }
  },
  {
    "type": "content_block_start",
    "index": 0,
    "content_block": {
      "type": "text",
      "text": ""
    }
  },
  "... 21 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting Claude use Anthropic's server-side web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.8',
  {
    max_tokens: 4096,
    messages: [
      {
        content:
          'What were the top news stories about Cloudflare this week? Summarise in three bullets.',
        role: 'user',
      },
    ],
    tools: [{ max_uses: 3, name: 'web_search', type: 'web_search_20250305' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.8",
  "max_tokens": 4096,
  "messages": [
    {
      "content": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
      "role": "user"
    }
  ],
  "tools": [
    {
      "max_uses": 3,
      "name": "web_search",
      "type": "web_search_20250305"
    }
  ]
}'
```

```
I'll search for the latest Cloudflare news this week.
```

```json
{
  "id": "msg_012vbxhcf34JMoq7KydUt9vv",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll search for the latest Cloudflare news this week."
    },
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01KXV2jKHHeTwnHXEPh1Sj55",
      "name": "web_search",
      "input": {
        "query": "Cloudflare news this week"
      }
    },
    {
      "type": "server_tool_use",
      "id": "srvtoolu_0181PuVN9PJeTEyFBcyXfAJD",
      "name": "web_search",
      "input": {
        "query": "Cloudflare announcement June 2026"
      }
    },
    {
      "type": "web_search_tool_result",
      "tool_use_id": "srvtoolu_01KXV2jKHHeTwnHXEPh1Sj55",
      "content": [
        {
          "type": "web_search_result",
          "title": "Cloudflare Status",
          "url": "https://www.cloudflarestatus.com/",
          "encrypted_content": "EqYhCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDPUQZZAQBYFYQHPVMRoMx+TGkDvtKp1ZbBE3IjBkHPLhGbP3lkbf/frryFycVeo9opOqeGRjL88dh4HGjFejP9rTYfYFtB/lZz6a7o8qqSAXnmIdnnDOFgxetdt/W330V+nBWQ3wH3KM/6aJAEv6pRzgjDDdYBzT9KDnqCmU5G1BBWQILPfQL8XrUQLe8WrB8y5Mz88RwZhd8A0pM4i761NyDRmqU0imAtggduXFHY0mZSyocq0UynTtbwUZxfYPJv+z9vceMCAevTIvaDoIpLPEQiKC0ZBoqKLsQvO8D5QLpBBx2TDW2mK32rJAlhlw6tpt21vpLXewOyEuApOb/WUnw1EVgMroc+Id9tY/cH17tq8tQt7iq7c2s0jnrA/98aa/Czn/aWINUMvGSr+4dwSk1Z70jsk+7FHTI00ofkXQdxsUjceJYxU44RGJoF/jnIv95gHIcRRHjn6YtkrqF+dCJtYk4JDU4ogBDhYrZm68vPaIHcRztVtIxpd3awT4dd/cRJ/Nv5A7QAjds7x6Su9NGzl+10XVUEW8BHpObqy0UX+klA0ihQ4wDDRXaWs3AfPoFTU/pBUqCAq+Q96t0zSu1ZLc/MN/+I5l35z2cW5erOIYTzOHlzYMZ0IPWUki1Jwa9GFhAfDeL1xtHfO26zkhOA7+qlz6Vq/MDpCdNEbXBSwbziCx1dGL12pUVLqFqQUcS6tkOaJPmvvVfzEdQpv8wHsiL/wT7lJNGAHomXTlyXDEW1Ck9/awK+hxFq9IWHcuMGoxjvG8HQ+eNuMObPigaVAZS/h6Z7aihBZ1yNR1b/1RlWoaRGRrHJ/lw2PwJdam3QFpt1xXAUM3deRsWIQPdWOxuXAB/PBmK8NxZs+quc1Nvqq1N/SEGBRltqfsI0Tv63Gm7gbaylxPSoKZYZTo9lWSCPdjnfP1nEEBRJTiigLT6JEs6085dDGTQ0BHqcthgwsyxetXD3/cXksxHLToR0vrDytU6XlAw+TRLtsZkHav3nLk1DFcPaZJJvIxvjZr0LCh3dOL4D5xTb6MIuHwXNJOwak5qfdhpOTuBjZN1gyzKH3yGUZlLZ4qz4sDIB1NrkbvHu9aVvMrAyKpv2cQK1Fe6NcM9HJRfLSbTe3sbbvdK0Fy0W151R6cpMHYnhpymOLqHhtGnDiYs4vHXbw/uiTetUQEOFwIBxk+DpQKwGymi8iDuLZGnAqzo2qQMs01ZlC/x3kFyaFVqJZ7X6zq1QQ4EOMQqT+jTiO07kV3MhTEQYnzKQ0hF288LpKpSADl1XsEBbB5lxwzLwUpb7YIX7wS2rLTCwhIO75EVJcZ2v56aGsRdJpAQ4sf/puJhKoCCSiD9YHIwwyaftykeUkP1ItZ5iQ3wP6CKc6556xwzrvUuelmZEvbcbP8cv+GpVWN71MVSLyhkfmqOdDZuGDDQNtcLcCNXkKtFDrj385UzJ86dmnFncp0uYf/HRx+ftSXwhRachfI0RNXXLjiscnJoBgs48tM+92gwYgli6frqm1u/Z8oqZprA4WIrc4M0F996fEhCDZ2+H8h858h61eX7yvjCuTM9TcxC57CKUy/S8sRp+pf05RWCF/07Yd9kESAuFworCBD/8mL7BzOgvvoKzxVCj1bI/TQRnARWH37fvRSkNSVH+8p5rR1a/ymb6r8wgNR5Jjvo5Eu7AqYKagzZyPFqGkgAOtpTm9xomfZNwFxlEbWuhMxdumC86y/KlBrSJQZPph9phEJYAoWs+DSjf0/6JEpg6ZSzMt79cmPgJfpO2Uibm0WRACNZuRqMCSJZmN5zHHCss9XFNFAqIaRrda9cibmVLQmoTsaX+BD/g4w1oszOzEjdyQkERB/RGuxn9JtHTbX/Hqcxx4N7nNtn1UxLzIUhq9X35KSU2GGbf8sfL1ssQQ5bqTejchCI/pFiGOGdeUSoklcLNX+9TUeZvxnP+aaCxuM1OhmZvwA+34WQrKQIXfgDrTA6+HjgCSCgJ2xSU3Zl6I7WLj+Tei8O8GlP6J4jCqfyerVLWLSS/obZ3IOxPKKEqvqWln/yncWRt7Wm2Ff2Y70x+sJCryzmwxYf9yUSj73ZC3aPVl0VzJRSmNLlTFPxPZP1LN901puP4+GvYgThUHZS7ZrvQdYMi4K6cV72XdAc4DCIvXTBjQdecMcKLhcDZN1HpcohD7H10cwRZE0zl6bMA2eF9Jui1UDM1UlXIOSD2q7S5H0z2aevBnsSoq8QieaDHbyjYa+igEv3IZT/wSUXi+BLsIAG4eF+ZDwfIuGjS7nlM6xO/nNGLHrRcRfiNqTUZCWw/z/0b1QylQLgwnsom34vYdPa0uRoaNktqcKkeuOeuLkT+i26/+ry7FRojCXE5VOQwnzad1F9/lQpcGzB5mSq4nApnmVymtxsHPb+VGDpV1jq3T0r5l4lQCCjWjEkHAfQC2giKAq+5NzXwym5sFPYcAPzJ+Y2CXX/X0pwgnJjmjYuuovBN1+Y5RMNzxACdvgxceutdW05h4P7D/3M66NZEXlJYkwlrXFTaao1//o+qYuvJEETxLPSwf5qPoSUXushLSZH+jpqUbK9JP6bCAHKEg4uz24APfvDnGSq6uiKU9xIEPm4268+wcqgQFTkNazrrLI1nfFjHzFU0ZzLpXuIRh9iJV7czfO1w1XJ42r5BV14Lm/5OVjHoY/p4Pgcwhz7FF4Z09yjWy8H9ShDJJ+4UOTXcmF+h+Yb3JXGZe6ApoCyyjVTcgmvGo2+nsbyDaDT+xbCJIlCVi6PjCk3bVHlwW31/o798RZqKGi6jroFl5kBhRtmVvMPwvByc8FnKt3xrPMHuiioUEuW8ywU5CVmE040lx7FC4t31BSQKHiyo7Z10omEqauB9et9XU04b4QBC8VFASLXYBnY+U4EE8lFC535l1+IbihHBw+5LmtxDVcS4of5o6wCtZAfJ1qwrLiauyAcv3pb8uefIA2OUW08gK6o4SL33tF5j29bZTmx55qHU16rIxIDY0SizrOvGwCJoF26x8HnSWk095KQkzHDOGqIjCnUXbo0VGXHGdrgfEU59uon1adAawCTMMSSI/7Lx3m+1gcn825jOB50D2cqSqbfWU5eK9/eecujBAjYnfXnDiKMi9WkcuznIpKH4Zd1/m0NJdCT8oZ6xbXp4pDvwKlydnwIpMpvSy/Iindy/5P/6PZ8RAtBeQ1npRPuK4gAVdghCssdq7C6LzuKaOaCo4Z/Y/PWBhK8NV82mQ8oIu3a5AUAkLuku9oITV6wQ+qPopm4C274McmMd8/K5Ilp7g2Oc/AJJKnz1z7VAKp5ux24DjWcz204OKCg+8u/mBPtCdaqRvs8/z1rVdx8OeIK7gOCpl1cHSjssckHhJCbQNrb+kzVnxk9mm1E3yUY4ttI8HloX7gnoeL5EM+lvSvdBcuGiZE74fZG/9ycc0ABlgOTyRJu3by06EDoVekvE0KJoql4ZnZID4f401aZsbMc7Y4FvOUeu6RO6D5DAoKKczGZpsZN81wI7kOS/cIluFuxSPdeyyS5mhmU0gwlkyiQ0Iwl6cfh1e41/zkhQ03rc2dZvc/8QHYgkI77Kx/xk1QGgorHZ7XuqpsiGL21REI3I3RhuzP1ka9aAr9FBMAiiGMity0d9F61d85hig95zhIPJfEw5EX/S1mzGm2pUwZq5EIJKP8bLSumFa1eDRTvFXvOeHGkTCgsyqJZgujs1kfV+HDhotk4C5U7ayRHbnpMAw98SuntjRmchQh4Iy5U/aHYehmiC/b7J7Itmz/umIqYa2AHuki0l/sjrlvJyf1d7y+F9G8lcV0JcUPkFlFl542/aV68u2JsoqIYycKHzvdkn0j8WmF/Nk4RZRKLq69o/g8NF8spY256CuIcgQe1a4qoLM1tgf/oZHiL8XFm1O+9w0bQrN0q2n3snQoQzq8jwJXqN0ssAWUdWajVRbRLLHt/Ow5pqtvWf41R9aHKMOSTIIYzN4+SnxpLgfs5Sg+xNngp6cGxM2KM2D2MRXSLRBulJL7pdWhJdG1KOuTD2DkPJwwsYBsbxywgYeSNdrWFW8VIfPvP2iNRCY7M8yuyvk0AgBdQI7FdiIHZf5hi59eC9CtX0Phi8CMPw61H5ySAV5dLj/JvetTL0DswAQ81E22B6/OfiPA2Q84YD8DymCul+0psvdn67uStGL0EkG82pDY8ZxOxuVMSk01uD/BY60yyjlp9HIBiOemPt8Bgvv25y1dWeH/uBL3Jenmy1NyroLVIrDOFowza00BI/e6blEkHSwP8X4+e4BYPjXBxhGlrpcqJzY6BCFDXx2AlFgFwh/ubhDww0yvZPpNlp6ioaJMQssEA10xwo2i1D+5272gAwmNpdpbB106sFuwZ7nRpYPAea3Kot49ioMGd2DLcjm8sqT/p2LXQQoeCa0jo1te/N+sKIzyCdJkSCcXT+pf/jRg4fWeJ3wQKEUwu/Y20sdqwfj8eNQWGeCwb24FeIs8pGuDscLmbVTVqm93MOefVISQw8stOpeNTl91Z4ad5Nqwzv9D5J2HHd4sfBfSZPLPO1cs5gocoXJUrYSF9ZpNE+uIJxPetlHS0oe+839XVebBrZ1deNh7YoDzUj4BQoG6N70mwxSAXtkAOvKMTk73qANtD0/WgjaG8Tufsswmf31M8n6rEYGFwj93A2G3BEUE/ZoMexRqN9Ilc5G6mfOcaqHaO9ao1W0eGyEIT+gUSgHq1DLaco+rTK6Z1hy6dUnrNwweLDI9cw+oMYwNrTe5DBMOPp30I+85RkIV5ckfLMDVc+HYefmoEA02DIJ40uvEC6pxTwMLDpXgiy/b+u6TyxpnuunHvjKM0WnK++BRIaqLgxoi+Y4Et37bnFH20WKrYoyKTZDKPaxNOZY40VkumQdxBNAla9MlbrHcdQ2r3cOuPbwzlRFmeLgANIeaaRN/U0xTrXkO2TmUcU3waYzcNCrzoAYcyuT6XfEVYgPpEXmMBkCjM6zyte/UDQlDl4Q+o7TYx1SRefvd+vEgrdl8j7lfhxiXuru095lj/Cq9m/8+SWtMGCBFsL1VXnMtcBMQN1tQ06OV8wgf52ls1q2xn3V2lP+mMGcPVGlY5K+iTFCnLis5lMbYY8sJ6fm0tCXtAGTNsjGSL3ilma6NY8Wm+/cdAM/WCH0rmJUrAlmiug3vEElO0CYWvqDrAgZv8zetOhNwUIHKYFe+T8Umt7trUqhePHFB8vXolgA/U3SPXH0JGTIcXKhQGSjJgKCnaiLHCP0OUvrq/7Hp3xRUPz2nHEouTOylzOY5jfAWOAu5dMewn2IzIkIGbneFqofyeRwK/X7pSvwtb+r328Zl6RDwJNcv9pjyb/3g/FKU5WwKiTTKeqlCsIKr2G5LWevvdz37YLl4GadbZK9GcmKJ228AUJmzI7AkcsSGVUSNMoSB6AtJBNKC/KAk+xmo1P6r2w3sIIP1Rz57+pnAeGhlwoxr/BcGpXi3f66gmBopLBXzzU1qxPqzQrav6uSRX7bFmJvWWVG/2TqhnaaigKPfmVpchPDNkau0yBwE9TXux25GlH/6DQvH33ehLpZG0U5tLwYEEIE8Zxq/zvT1vVQTgjch0AiP6EXkYkw2aT3MZIWFbHSBtnPQYbDXrvMYAw==",
          "page_age": "2 hours ago"
        },
        {
          "type": "web_search_result",
          "title": "The Cloudflare Blog: Product News",
          "url": "https://blog.cloudflare.com/tag/product-news/",
          "encrypted_content": "Eq4RCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDL7fvmvRH9GbeuRYyhoM/SYgq0DCI+CESMxFIjCfJU4dcQ7bs7GDuRqUB2u1rEpw7net+ZkOtJRZhHyPZSr63F6Hv9b4wtZZDnguc4QqsRDDSU9bMyRIwv9WRoKYbgCMetfonTaAfMRPzzu597mtTBt7S+qU6peGPVYp50J+IIVKf89xxYglCD1gLAcCsVcL8UywUB/BbtvnSYFycV+EtwjxKbcko4uV2YwKN+2b8fWaXz2Rif7l8X09mQSbSKRFhT5qabDq2bFPev6mWN6PTvdGdIMlyes3dpWkXfs7K69W7z2z0qq+kkY1gPqBSYXtUQLOpN38fv9ATS720LsTI7EXo35O4jm9xd+zBJamG6rJRRto8Z7qU6JELej6QQKQTUDe7nnxYqNR2ujjmc1B6ZbuewzhnVmZLjRGDhEeHXsXKqcZEZiNntlgyDM6+9GxcRWdBtjS367dosiWzj3ROfUpJLiiYx4nRwQ7JQ+wVMAdj67An39pDlcHm34ffkMo3ywOqsFTKqNom5HeIlYwO97gv4iyT2uAe4vqXWY4IXOqdvMMA/uvy0UWrO902AxCoQkpz3W5HzvTYQyBgknrIHxXxLwJqYwj5G2RHWf8wcMv8aV1drMNHTCy0iqAaHGNQ3FLE8PIjnWNRnriEfdJweV0KwQbrVaweOd8qmdoHGMgAv54Mj8keXXq70p7/+tHF7aHqFWho8e/zdEdWah35P5mAEumMGVwgYVtXdAvwmheBF3sbZKiqi4V9mtLi3GPoI5k+z3gDTNYqBaWlDmgNqRcMonMYaPuUoaPM3N9dZfxSAKJ7E+Nx+i2n/yAsP6poUcBH8uDYESnJODgKvrXgF/b5+LJG+cnCIe3UtdLEO/XjmxdlMoNGX/QlMwfjuRd6e7SqnFOMd56oQvC/J8VNEksnFkrDyYfWo26lFfGJ5RYKgvkxLWMTmbaxNmsB7gX7xbxic6vR+CeuphKK6JXMozNgKylJDcrX3LC8pvZt6oBkmb448KEdTkfnFy7MNMntq8sWkjfHQC3rasrngsb9QuOJjRrzkcsBRXjGZy95gSZuKO9z7dn8+kcmU1jfNuN22f+9
... response truncated ...
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.8/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.8/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.8/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.8/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.8/#page","headline":"Claude Opus 4.8","description":"Claude Opus 4.8 is Anthropic's most capable generally available model, with a step-change improvement in agentic coding over Claude Opus 4.7. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-4.8/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Opus 5 is Anthropic's model for complex agentic coding and enterprise work, delivering intelligence close to Claude Fable 5 at half the price. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing. Unlike Fable 5, Opus 5 has no data retention requirements for general access.
title: Claude Opus 5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Opus 5

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-opus-5`

- Third-party

Claude Opus 5 is Anthropic's model for complex agentic coding and enterprise work, delivering intelligence close to Claude Fable 5 at half the price. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing. Unlike Fable 5, Opus 5 has no data retention requirements for general access.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://www.anthropic.com/claude/opus) |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$5.00</li><li>Output (per 1M tokens)$25.00</li><li>Cached input (per 1M tokens)$0.50</li><li>Cache creation (per 1M tokens)$6.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-opus-5',
  {
    max_tokens: 1024,
    messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The laws of thermodynamics describe how energy and heat behave in physical systems. Here are the three (plus a bonus fourth that was added later but numbered "zeroth").

**First Law — Conservation of Energy**
Energy cannot be created or destroyed, only transferred or converted between forms. For a closed system, the change in internal energy equals the heat added minus the work done by the system:

ΔU = Q − W

Practical implication: there's no such thing as a perpetual motion machine that produces energy from nothing.

**Second Law — Entropy Increases**
The total entropy (disorder, or more precisely the number of accessible microscopic states) of an isolated system never decreases over time. Equivalent formulations:

- Heat flows spontaneously from hot to cold, never the reverse
- No heat engine can convert heat entirely into work — some is always lost to a cold reservoir
- Processes have a preferred direction in time

This law is why engines have efficiency limits (the Carnot limit) and why it's often described as giving time its "arrow."

**Third Law — Absolute Zero is Unreachable**
As a system's temperature approaches absolute zero (0 K, −273.15 °C), its entropy approaches a constant minimum — zero for a perfect crystal. A consequence is that no finite number of steps can cool something all the way to absolute zero; you can only get asymptotically closer.

**Zeroth Law — Thermal Equilibrium**
If system A is in thermal equilibrium with system C, and B is also in equilibrium with C, then A and B are in equilibrium with each other. This is what makes temperature a meaningful, measurable property — it's the basis for thermometers. It was formalized after the other three, hence the odd numbering.

A common informal summary: *you can't win (1st), you can't break even (2nd), and you can't get out of the game (3rd).*
```

```json
{
  "id": "msg_011CdMcWsWTt6YQBsVgBJKET",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAIS+wkKhwEIEBgCKkCQkqK6v16N37+5nxwsLhxrzfCzIPF8EtZFUMp15QDBKBAUGSIu2rqp+X6/Hi8Ul8I6R5cRA5sW1cubAR0uFsttMg1jbGF1ZGUtb3B1cy01OAFCCHRoaW5raW5nWiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDBjGGGXscwelkjSVsRoM76EmL+Pl2dtvcTfkIjBy2Ayh9NZsLWod+geEtrv0CZx22kjdWmRHFED/zy3kvHn4eM1OJrP3lhPjNTckDU0qoAh+2jG1EqZNl6grp923Shc5W4S3srKv4zy7w4z6n150KajRAZSSpC/BYrGJb6lq6nVEsgjvnrOHIeF3mq1Y3/3rPJ346UB5iJRwP+rpm6lA4LkUVQZZGYeKqUhplIEMOdQdajx2iPjmTMTV0DjdiB0bHWA776a1SXuK5VjTpcnn77iwz8okVSbhqL6annDIiWET5Z9kHhjuqHhxdAXMeGkmYWbD2i0ttDdpaHgmrvW0FRYHDEDSQr/zUT6sXgke+AIG/jWwe5SmqZIIlHhOHufoW549PnXx/W6fkiiu/sNwYL85/3toWXePQkDKnD4GEFClcdCHVOEdOh45aC7XxtRwSMTBtRDz5DeAQvHwosoZoM/dJYru0s00EkG9pAq7I15ED7XTtJkUCE61wMdqifXkOSsAHbKxH6nJemHfSpS+14jaAZdWydahPq1j8wJVppQ1KC73HJZJ1wgKHT2ZCT1WlV9FuE+hmqp13NUirZRe+o7DEJiNSenND0L1GZ13FWFXiFFSXMQiAwDJTk4yWk8cLCGt45dFtAW/m8QoKKxcx+JctfpE21IMKnOG9mPJjvUdNsP3s5bk3ZkD2dcpbv4jfdJsZdz7DqNnR0tQS0TGFAc+hBuYM0ftPJlfyhKlwpi227CIVmhlxKKAUkODCMrdjevZhyJ/JZKbAJ2yzGQ2TaLxlmkbhM4XH0RBaQ+ALv5tg+oNZ0vA9OA5uKwbN9u9yKDq7hYBQeSatyPoJ+pGxEoeGeFOP4bZHvOplm/5V67E90HzDf0k/EVvjkj0P5nqVHsUb9N6IYNkMPdsNAAenNWBNk3Z8kW1xGxRw/JXZGKUr1Ql6nD5dUMw3DIDKG1c1+8QPaata4WzR/zMO8+btn3VObUDjekjC72bKMfsAjMMkX7dWYojE94Hg2rAFRQ20hmbjYDAwt8x/k8LD8bGBa/xw5WHY1Fa64r5YvJgK98sCtJbo68axk6/Tf8AgnzwVzjDugI+pQJ2oAoC22iqQQVzTwmsoLnqi9i3F/fe9wHqITf+jGytEfT0AG73R9dFD73mac0QVIbWXkm8Weld3twIvtzC3W0IPb2v1rhQkRCCJM/s6IBvRP2N0PIwCE2oexDeW+rw59vL8d/tsZ1Woogo1+76ldngoeLF4rEV4VjfP22rTN6ZLcfnerdYbF1lDXfQhTHgs+4LvMuHfYX8lMIq/wJssPyIpnXhXtmxgd9/ce2OInU3dUHXqISUHXIeiHeDxglxblzSK9B0rAzk1UaVJn4PMNGF3M1wguw6i9AAx8s+1AU5hLOinfZ166Az9HUYz/uHkQ6d0JYRx5L6xHXaWXF51ZifLRtfoeNqLdHGKxrfjSNQK8Ouuce7SzLMGi4YH5W2rED1XmpwI69xXnssHuQKHqt7ggSV5P26e5EYAQ=="
    },
    {
      "type": "text",
      "text": "The laws of thermodynamics describe how energy and heat behave in physical systems. Here are the three (plus a bonus fourth that was added later but numbered \"zeroth\").\n\n**First Law — Conservation of Energy**\nEnergy cannot be created or destroyed, only transferred or converted between forms. For a closed system, the change in internal energy equals the heat added minus the work done by the system:\n\nΔU = Q − W\n\nPractical implication: there's no such thing as a perpetual motion machine that produces energy from nothing.\n\n**Second Law — Entropy Increases**\nThe total entropy (disorder, or more precisely the number of accessible microscopic states) of an isolated system never decreases over time. Equivalent formulations:\n\n- Heat flows spontaneously from hot to cold, never the reverse\n- No heat engine can convert heat entirely into work — some is always lost to a cold reservoir\n- Processes have a preferred direction in time\n\nThis law is why engines have efficiency limits (the Carnot limit) and why it's often described as giving time its \"arrow.\"\n\n**Third Law — Absolute Zero is Unreachable**\nAs a system's temperature approaches absolute zero (0 K, −273.15 °C), its entropy approaches a constant minimum — zero for a perfect crystal. A consequence is that no finite number of steps can cool something all the way to absolute zero; you can only get asymptotically closer.\n\n**Zeroth Law — Thermal Equilibrium**\nIf system A is in thermal equilibrium with system C, and B is also in equilibrium with C, then A and B are in equilibrium with each other. This is what makes temperature a meaningful, measurable property — it's the basis for thermometers. It was formalized after the other three, hence the odd numbering.\n\nA common informal summary: *you can't win (1st), you can't break even (2nd), and you can't get out of the game (3rd).*"
    }
  ],
  "model": "claude-opus-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 20,
    "output_tokens": 969,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-5',
  {
    max_tokens: 2048,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-5",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python."
}'
```

````
# Reading JSON Files in Python

Python's built-in `json` module handles this. The key function is `json.load()`.

## The basic pattern

```python
import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(data)
```

That's it. `json.load()` reads from a file object; the `with` statement ensures the file gets closed even if something goes wrong.

## `load()` vs `loads()`

This trips people up constantly:

| Function | Input | Use when |
|---|---|---|
| `json.load(f)` | file object | reading from a file |
| `json.loads(s)` | string (or bytes) | you already have JSON text |

```python
# From a string
text = '{"name": "Ada", "age": 36}'
data = json.loads(text)

# Equivalent to the file version
with open("data.json", encoding="utf-8") as f:
    data = json.loads(f.read())   # works, but load(f) is cleaner
```

## What you get back

JSON types map to Python types like this:

```
object  -> dict
array   -> list
string  -> str
number  -> int / float
true    -> True
false   -> False
null    -> None
```

So access it like any nested dict/list:

```python
# data.json: {"users": [{"name": "Ada", "roles": ["admin"]}]}
data["users"][0]["name"]        # "Ada"
data["users"][0]["roles"][0]    # "admin"
```

Use `.get()` for keys that might be missing:

```python
email = data["users"][0].get("email", "unknown")
```

## Handling errors properly

Real-world files are messy. Catch the two things that actually go wrong:

```python
import json
from pathlib import Path

def read_json(path):
    try:
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"No such file: {path}")
    except json.JSONDecodeError as e:
        print(f"Invalid JSON in {path} at line {e.lineno}, column {e.colno}: {e.msg}")
    return None

data = read_json("data.json")
```

`JSONDecodeError` is a subclass of `ValueError`, and it carries `lineno`, `colno`, and `pos` — genuinely useful for pinpointing a bad comma.

## Using `pathlib` (slightly tidier)

```python
import json
from pathlib import Path

data = json.loads(Path("data.json").read_text(encoding="utf-8"))
```

## Common gotchas

**Always specify `encoding="utf-8"`.** Without it, Python uses the platform default, which on some Windows setups is cp1252 and will blow up on non-ASCII characters. JSON is UTF-8 by spec.

**JSON Lines (`.jsonl`) is a different format.** One JSON object per line — `json.load()` will fail. Parse line by line:

```python
with open("data.jsonl", encoding="utf-8") as f:
    records = [json.loads(line) for line in f if line.strip()]
```

**Trailing commas and comments aren't valid JSON.** `{"a": 1,}` or `// comment` will raise `JSONDecodeError`. If you're stuck with such files, use the `json5` or `commentjson` package.

**Huge files:** `json.load()` builds the whole structure in memory. For files that don't fit, use a streaming parser like [`ijson`](https://pypi.org/project/ijson/):

```python
import ijson

with open("huge.json", "rb") as f:
    for record in ijson.items(f, "users.item"):
        process(record)
```

## Writing it back out

For completeness:

```python
with open("out.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)
```

`indent=2` makes it human-readable; `ensure_ascii=False` keeps non-ASCII characters as-is instead of escaping them to `\uXXXX`.
````

```json
{
  "id": "msg_011CdMcXtLbe6orhyjErTMK4",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAISlgMKhwEIEBgCKkAMw2x29hUCKlXqNB76pH+D/yqNHzKCZSWl13/1q5MvcRHqGBsMYVt5OPNJRBpoK96H4yBdLeYFynRrC3brOl8VMg1jbGF1ZGUtb3B1cy01OAFCCHRoaW5raW5nWiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDPHl470mvTSS/VVloBoMjuO0rbloh1ffzl7/IjCQVDk88te+JO4ShyaKbxvx7tByViz6N6zO3AnWMoRShuVZmByIC9M123krmAR3d0squwH0oba6v809aPGBRis6zXZjjkxj9xUPeK9bIiAs2F4LqShktrO0enUaJGxlcocxt2tmwdkC5SF7XOy5lKpcBDf6XvOTeaV0bYyxgAQ6L2FkiOU9NtnSGiZZ0VmKz2v8RZ9nVisaD6kA15+UOqX8SO5ZYny+Ttrgue6Cx5DJ7MfBcRcE6SsSsuyLnrRFY1S7XNsCcd0lY1rv1CzkYOnItoxD6fDWab8uxQGGXWBhUnSy4XxtZ0+TR/2fRTuXGAE="
    },
    {
      "type": "text",
      "text": "# Reading JSON Files in Python\n\nPython's built-in `json` module handles this. The key function is `json.load()`.\n\n## The basic pattern\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n\nprint(data)\n```\n\nThat's it. `json.load()` reads from a file object; the `with` statement ensures the file gets closed even if something goes wrong.\n\n## `load()` vs `loads()`\n\nThis trips people up constantly:\n\n| Function | Input | Use when |\n|---|---|---|\n| `json.load(f)` | file object | reading from a file |\n| `json.loads(s)` | string (or bytes) | you already have JSON text |\n\n```python\n# From a string\ntext = '{\"name\": \"Ada\", \"age\": 36}'\ndata = json.loads(text)\n\n# Equivalent to the file version\nwith open(\"data.json\", encoding=\"utf-8\") as f:\n    data = json.loads(f.read())   # works, but load(f) is cleaner\n```\n\n## What you get back\n\nJSON types map to Python types like this:\n\n```\nobject  -> dict\narray   -> list\nstring  -> str\nnumber  -> int / float\ntrue    -> True\nfalse   -> False\nnull    -> None\n```\n\nSo access it like any nested dict/list:\n\n```python\n# data.json: {\"users\": [{\"name\": \"Ada\", \"roles\": [\"admin\"]}]}\ndata[\"users\"][0][\"name\"]        # \"Ada\"\ndata[\"users\"][0][\"roles\"][0]    # \"admin\"\n```\n\nUse `.get()` for keys that might be missing:\n\n```python\nemail = data[\"users\"][0].get(\"email\", \"unknown\")\n```\n\n## Handling errors properly\n\nReal-world files are messy. Catch the two things that actually go wrong:\n\n```python\nimport json\nfrom pathlib import Path\n\ndef read_json(path):\n    try:\n        with open(path, \"r\", encoding=\"utf-8\") as f:\n            return json.load(f)\n    except FileNotFoundError:\n        print(f\"No such file: {path}\")\n    except json.JSONDecodeError as e:\n        print(f\"Invalid JSON in {path} at line {e.lineno}, column {e.colno}: {e.msg}\")\n    return None\n\ndata = read_json(\"data.json\")\n```\n\n`JSONDecodeError` is a subclass of `ValueError`, and it carries `lineno`, `colno`, and `pos` — genuinely useful for pinpointing a bad comma.\n\n## Using `pathlib` (slightly tidier)\n\n```python\nimport json\nfrom pathlib import Path\n\ndata = json.loads(Path(\"data.json\").read_text(encoding=\"utf-8\"))\n```\n\n## Common gotchas\n\n**Always specify `encoding=\"utf-8\"`.** Without it, Python uses the platform default, which on some Windows setups is cp1252 and will blow up on non-ASCII characters. JSON is UTF-8 by spec.\n\n**JSON Lines (`.jsonl`) is a different format.** One JSON object per line — `json.load()` will fail. Parse line by line:\n\n```python\nwith open(\"data.jsonl\", encoding=\"utf-8\") as f:\n    records = [json.loads(line) for line in f if line.strip()]\n```\n\n**Trailing commas and comments aren't valid JSON.** `{\"a\": 1,}` or `// comment` will raise `JSONDecodeError`. If you're stuck with such files, use the `json5` or `commentjson` package.\n\n**Huge files:** `json.load()` builds the whole structure in memory. For files that don't fit, use a streaming parser like [`ijson`](https://pypi.org/project/ijson/):\n\n```python\nimport ijson\n\nwith open(\"huge.json\", \"rb\") as f:\n    for record in ijson.items(f, \"users.item\"):\n        process(record)\n```\n\n## Writing it back out\n\nFor completeness:\n\n```python\nwith open(\"out.json\", \"w\", encoding=\"utf-8\") as f:\n    json.dump(data, f, indent=2, ensure_ascii=False)\n```\n\n`indent=2` makes it human-readable; `ensure_ascii=False` keeps non-ASCII characters as-is instead of escaping them to `\\uXXXX`."
    }
  ],
  "model": "claude-opus-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 38,
    "output_tokens": 1398,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5/#page","headline":"Claude Opus 5","description":"Claude Opus 5 is Anthropic's model for complex agentic coding and enterprise work, delivering intelligence close to Claude Fable 5 at half the price. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing. Unlike Fable 5, Opus 5 has no data retention requirements for general access.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Opus 5.5 is Anthropic's model for long-running agentic coding and knowledge work. It combines a one million token context window with adaptive thinking that is always on, a 128K token maximum output, and a medium default effort level.
title: Claude Opus 5.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Opus 5.5

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-opus-5.5`

- Third-party

Claude Opus 5.5 is Anthropic's model for long-running agentic coding and knowledge work. It combines a one million token context window with adaptive thinking that is always on, a 128K token maximum output, and a medium default effort level.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://platform.claude.com/docs/en/models/opus-5-5/overview) |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$4.00</li><li>Output (per 1M tokens)$20.00</li><li>Cached input (per 1M tokens)$0.20</li><li>Cache creation (per 1M tokens)$5.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-opus-5.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-5.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
Thermodynamics is usually described by **three main laws**, plus a "zeroth" law that was added later because it underpins the others.

**Zeroth Law: Thermal equilibrium**
If two systems are each in thermal equilibrium with a third system, they are in equilibrium with each other. This is what makes temperature a meaningful, measurable quantity, and it is why thermometers work.

**First Law: Conservation of energy**
Energy cannot be created or destroyed, only transformed from one form to another.
- Written as: **ΔU = Q − W**, where ΔU is the change in a system's internal energy, Q is the heat added to the system, and W is the work done by the system.
- Implication: no machine can produce more energy than it takes in, so a "perpetual motion machine of the first kind" is impossible.

**Second Law: Entropy increases**
In an isolated system, total entropy (roughly, disorder or the spreading out of energy) never decreases over time.
- Heat flows spontaneously from hot to cold, never the reverse without outside work.
- No heat engine can be 100% efficient. Some energy is always lost as waste heat.
- This law gives time its "direction" (the arrow of time).

**Third Law: Absolute zero**
As a system approaches absolute zero (0 K, or −273.15 °C), its entropy approaches a minimum constant value. For a perfect crystal, that value is zero.
- Implication: absolute zero cannot be reached in a finite number of steps.

**A popular informal summary:**
1. You can't win (you can't get out more energy than you put in).
2. You can't break even (you'll always lose some energy as heat).
3. You can't quit the game (you can't reach absolute zero).
```

```json
{
  "model": "claude-opus-5-5",
  "id": "msg_011CfJq2fgVPNWUne9rV4Tiv",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAQSmwUKEAgSGAI4AUIIdGhpbmtpbmcSDFVkpHQKiUqmYYqLgBoM8wyoXxEXn4HFcl0CIjCevXuqxkDavToC7S4gH/QFNscgJxQuyQfgg5lrBctKdBWSqysQvLawgvmsCshEmpYquAQDK/xJ80Z7b+/HtCuw4EYkFeLBS9DgqtPWUbd5GSCI9aC9YXFhzp1f9qW1kUyMIBgoUhiQWi2N4LVQnFFuE+3T5DzegFjfCEsU9WLjw3LL4uUemJb+B7Y7wWJ7USzBIgdytRa3Ta/NePqTWHWMR3csyGHh+avsBoZ+GLsgFOs4HQ0AFW1qfnGuNRivh3947vZ1SWFaROOoYZK6LGV856aez1mjiHdr3+yzOBNHGL4nWM+EFG7CtjxcBfqI7qU3nK4atAjAweIFAHarEIApWCRodUVyDcSNpMnS4EuquJs7JPju7+0jxj+sLP/6faYmzH+thOy3YT/aBzlGOxVT2ns6TOFsMEcxRYBjwkj3f579LZ1VpE/GVT7ZJzGXq3puXvJhFdMvxYEgOnr2ih6S6cJHhB4FAGEjvvLMJ33MpGI92egyVFhJXTZfYz90W4vqIYpGLuRzERPLHjexXGwzAjZu8K1a/MvZcekX3mSNzoyhHO8B3ALp7p6aKYJ0PVTfGLD/p7IRuMRBf/sHauAiOy8RuUojVCbRkhcfzYLA+zpYs9AAe+HOv4hOS+yUq/dRZC2xpj8YWfhNwHVoIrqs0j5kGkjl33QX9X9BS1urhkAuUojh864FFNKb9z2uREt2kYglcrUz6fQQZ9iWvJ4iyO0cGKEyy53Tgehmf/lzNZlNWAPnGs05dH+t72Knf4gtepuZ1fDSTimg60NrIJvF9+7GrBjbJBY2rwAcgLM8g/8E8BbzSCruZqGaGAE="
    },
    {
      "type": "text",
      "text": "Thermodynamics is usually described by **three main laws**, plus a \"zeroth\" law that was added later because it underpins the others.\n\n**Zeroth Law: Thermal equilibrium**\nIf two systems are each in thermal equilibrium with a third system, they are in equilibrium with each other. This is what makes temperature a meaningful, measurable quantity, and it is why thermometers work.\n\n**First Law: Conservation of energy**\nEnergy cannot be created or destroyed, only transformed from one form to another.\n- Written as: **ΔU = Q − W**, where ΔU is the change in a system's internal energy, Q is the heat added to the system, and W is the work done by the system.\n- Implication: no machine can produce more energy than it takes in, so a \"perpetual motion machine of the first kind\" is impossible.\n\n**Second Law: Entropy increases**\nIn an isolated system, total entropy (roughly, disorder or the spreading out of energy) never decreases over time.\n- Heat flows spontaneously from hot to cold, never the reverse without outside work.\n- No heat engine can be 100% efficient. Some energy is always lost as waste heat.\n- This law gives time its \"direction\" (the arrow of time).\n\n**Third Law: Absolute zero**\nAs a system approaches absolute zero (0 K, or −273.15 °C), its entropy approaches a minimum constant value. For a perfect crystal, that value is zero.\n- Implication: absolute zero cannot be reached in a finite number of steps.\n\n**A popular informal summary:**\n1. You can't win (you can't get out more energy than you put in).\n2. You can't break even (you'll always lose some energy as heat).\n3. You can't quit the game (you can't reach absolute zero)."
    }
  ],
  "container": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "stop_details": null,
  "usage": {
    "input_tokens": 22,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0,
    "cache_creation": {
      "ephemeral_5m_input_tokens": 0,
      "ephemeral_1h_input_tokens": 0
    },
    "output_tokens": 597,
    "output_tokens_details": {
      "thinking_tokens": 30
    },
    "service_tier": "standard",
    "inference_geo": "global"
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-5.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-5.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python."
}'
```

````
Use Python's built-in `json` module:

```python
import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(data)
```

`json.load()` parses the file into Python objects:

| JSON | Python |
|------|--------|
| object `{}` | `dict` |
| array `[]` | `list` |
| string | `str` |
| number | `int` / `float` |
| `true` / `false` | `True` / `False` |
| `null` | `None` |

### Accessing the data

Given this `data.json`:

```json
{
  "name": "Alice",
  "age": 30,
  "skills": ["Python", "SQL"]
}
```

```python
print(data["name"])       # Alice
print(data["skills"][0])  # Python
print(data.get("email", "N/A"))  # N/A (safe access with a default)
```

### Handling errors

```python
import json

try:
    with open("data.json", "r", encoding="utf-8") as f:
        data = json.load(f)
except FileNotFoundError:
    print("File not found.")
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")
```

### Related tips

- **Parsing a JSON string** (not a file): use `json.loads()` (the "s" stands for string).
  ```python
  data = json.loads('{"key": "value"}')
  ```
- **Using `pathlib`**:
  ```python
  from pathlib import Path
  data = json.loads(Path("data.json").read_text(encoding="utf-8"))
  ```
- **Writing JSON back to a file**:
  ```python
  with open("output.json", "w", encoding="utf-8") as f:
      json.dump(data, f, indent=4)
  ```
````

```json
{
  "model": "claude-opus-5-5",
  "id": "msg_011CfJq38YmJ38ymFcT5DTY1",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAQS2gQKEAgSGAI4AUIIdGhpbmtpbmcSDFxQnE4f+jiYlyFgJRoMSio6ozq/nrk03OjnIjBVW7CpYGDuYX0b4SOpKqPYvUWec6ECWFTyOTlkKzvsGwcS1cN+YxcSbrCn9Gas++Uq9wO+i2aTJH/h1Sp0FqfRJDDBYWHuhH/1E26gBxzSBMAf+a6H86MyyhWgenqOfkqey4JJT10Sw9Y3aPrXOdBiVVrDk+r74fWA+tGK/tEVawYJIQPKlZrH8OPSpvOoetWEGF/fCtDIJkjTL/YmT4GK+grY1UJJ/vkRrvX0hPOc5wD1y+Wk7WV4MtJMEioXohlQ93b7jO9Il9TVp1s5Pyt6SjQNal/VfnLa4zUfsKymng8D0c+o9BrfEtffPovv/PslRUv5XHKLTRYqIyJ9o3K3iTtoUMgAl+CyFE8/i48CC2ATgpfrnF60aXRqTYOHBs6h1C62pgfRGHsD7Xxcg0k7JNnyMw4PXml9i4//7MNzUW0ZHRN5K8u5aZoTo52x3LwyIO2bc7se+oISb8CcjTYRzWGLwE/ra4WW3LiR6i3uObzoEHWVwolPEgcJQU0HgYWpTSqCr4FugcxGoTtU1Nklly31MJzeYUcdATSJxOGw1rz0QfZmGN81uRYbS5DF2jiQ82t3b9K9XdZWFm7nguV5jb/Hl68hDoSrm4KCv40xZwe34cXp4FdQSAnEsMikuoP+odCbrUpdrCycGws8xwKkatEq2MBCZ0Y5U2HlSWEHJo8WqHYNuuC4sIgXWKdtZlZJZWzTqeZ//nq/57ON0Z02DNVTd4yjoMfF0BgB"
    },
    {
      "type": "text",
      "text": "Use Python's built-in `json` module:\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n\nprint(data)\n```\n\n`json.load()` parses the file into Python objects:\n\n| JSON | Python |\n|------|--------|\n| object `{}` | `dict` |\n| array `[]` | `list` |\n| string | `str` |\n| number | `int` / `float` |\n| `true` / `false` | `True` / `False` |\n| `null` | `None` |\n\n### Accessing the data\n\nGiven this `data.json`:\n\n```json\n{\n  \"name\": \"Alice\",\n  \"age\": 30,\n  \"skills\": [\"Python\", \"SQL\"]\n}\n```\n\n```python\nprint(data[\"name\"])       # Alice\nprint(data[\"skills\"][0])  # Python\nprint(data.get(\"email\", \"N/A\"))  # N/A (safe access with a default)\n```\n\n### Handling errors\n\n```python\nimport json\n\ntry:\n    with open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n        data = json.load(f)\nexcept FileNotFoundError:\n    print(\"File not found.\")\nexcept json.JSONDecodeError as e:\n    print(f\"Invalid JSON: {e}\")\n```\n\n### Related tips\n\n- **Parsing a JSON string** (not a file): use `json.loads()` (the \"s\" stands for string).\n  ```python\n  data = json.loads('{\"key\": \"value\"}')\n  ```\n- **Using `pathlib`**:\n  ```python\n  from pathlib import Path\n  data = json.loads(Path(\"data.json\").read_text(encoding=\"utf-8\"))\n  ```\n- **Writing JSON back to a file**:\n  ```python\n  with open(\"output.json\", \"w\", encoding=\"utf-8\") as f:\n      json.dump(data, f, indent=4)\n  ```"
    }
  ],
  "container": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "stop_details": null,
  "usage": {
    "input_tokens": 40,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0,
    "cache_creation": {
      "ephemeral_5m_input_tokens": 0,
      "ephemeral_1h_input_tokens": 0
    },
    "output_tokens": 600,
    "output_tokens_details": {
      "thinking_tokens": 10
    },
    "service_tier": "standard",
    "inference_geo": "global"
  }
}
```

</details>

<details>

<summary>**Creative Writing with High Effort** — Use adaptive thinking with high effort for deeper reasoning.</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-5.5',
  {
    max_tokens: 2048,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    output_config: { effort: 'high' },
    thinking: { type: 'adaptive' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-5.5",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "output_config": {
    "effort": "high"
  },
  "thinking": {
    "type": "adaptive"
  }
}'
```

```
# The Missing Page

The dead man had been arranged with the kind of care people usually reserve for sleeping children. Hands folded over his sternum. Shoes placed side by side at the foot of the bed, laces tucked in. Someone had even drawn the curtains halfway, as if the morning light might disturb him.

Detective Inez Halloran stood in the doorway longer than she needed to, letting the room tell her what it wanted to tell her. Rooms always talked, if you let them. This one was saying *nothing happened here*, and it was saying it far too politely.

"Neighbor found him," said Patrolman Deaks, hovering at her elbow. "Door was unlocked. No sign of forced entry, no sign of a struggle. Coroner's thinking heart, maybe. Guy was sixty-one."

"Guys who die of heart attacks don't usually take their shoes off first and line them up."

"Maybe he was tidy."

Inez didn't answer. She crossed the room, snapped on a pair of gloves, and crouched beside the shoes. Brown oxfords, recently polished, heels worn unevenly in a way that suggested a bad left knee. She picked up the right shoe, then the left, and felt something shift inside the toe.

A folded square of paper, pale blue, lined.

She knew the paper before she'd even opened it. It was the same shade of blue as the cheap spiral notebook she'd bought from the pharmacy on Calder Street that morning, because her old one had gotten coffee-soaked in the car. She'd grabbed it off the rack without thinking, paid with exact change, and written exactly one thing in it: the address of this apartment.

She unfolded the paper.

Four words, written in blue ballpoint:

*He wasn't the first.*

The handwriting was slanted, cramped, the *t*s crossed low and hard, the way her father had taught her when she was seven because he said it looked more decisive. Nobody else crossed their *t*s like that. She'd never seen anyone else do it.

It was her handwriting.

"Detective?" Deaks leaned in. "You got something?"

Inez folded the paper back along its creases and slipped it into an evidence bag, keeping her face very still. Then, as casually as she could manage, she reached into her coat pocket and pulled out her new notebook. She flipped it open to the first page, where the address sat in her own familiar scrawl.

Then she ran her thumb along the spiral binding and felt the small, ragged teeth of paper where the second page had been torn out.

"Detective?"

"Get me a list," she said quietly, "of every unattended death in this city for the past six months. Every single one where the coroner said *natural causes*."

"That's gonna be a lot of names."

Inez looked down at the dead man's folded hands, at the careful, tender way someone had placed them, and felt a cold certainty settle in her chest like a stone sinking to the bottom of a well.

"I know," she said. "That's what worries me."
```

```json
{
  "model": "claude-opus-5-5",
  "id": "msg_011CfJq3WeHfjsXNsyLj1M39",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAQShRMKEAgSGAI4AUIIdGhpbmtpbmcSDIDVDS0bZ7tPwidUBhoMJcIrOXoIrKeBZ736IjCiR9c1BYgFaV/KxfRZIfBPODzcDk/kotKaz5Woz9lPOpdHsl8lRRTVO76eFTnpg+sqohLBBcpO7QZvgesqX3d0RJSeflcA0UOhFW47+Z00C5loAtHYzKc9UlimVw4mqL+3P5i0twnlzuwymUtoIzC7qrOaJPwd3rTRY0irzUE5lfuDQrMeES5MZE8PHPUkI+Pr/VgrfSd1sW7F7gBZBNtaZO/mDlaHUhpghVVCs5F+zzaMzW+hJ/XZWUGMLWJbBaIWogx3eDiMNGeSb46TzU1r0tY/IwLv/jHJluH4NAljHZd5haivBeCEYNtHnfXSiI2X+feSLWIb0QaklSwFdjvR+wq8QSWqviCYHdjAOyMuPDiI3w+y58LQ6aqiiqcIg5rQWj4Adl+bAV6Yfy3w7UKjD5HZgrBDFbnMNzbBMYxdlnGQQT69LoauE2pPUSsy7IGlyEejbb693I/eH0xEP3o95CW6ImoJg3H6iTyDTU+dCOHn4lxmH6EMIrc9mmYGFy5tqzvMxn1UITB/HRdLWkSO4ZOAu9DQUa7PiIr26qXhY5zDfkZ+4WWf3urgy0p+bBjBaS37M8dBpDNIdILQkNqhw5WZ8CT/9Ehp2ONL2B1OQdOxBAbVnQBbQfnmCkB6nXnBcmaMQT+jZSDgWFVH9lgVIzuKro0At5qaW95fAktXGSD/Aan5kVW89KHqavzLGILyZsosgs2t5SDVas5zxx4p7hDOHKxzCTks1HVv1tA5IXoTpAYEYtunXTb4y47cz8kprIsY2czWjbVqtMmxv69jBzWvRipo6SLu/aYeAcOX/jc3BWcziK3uFEUBjGp2R01rQ5/GzknGpiYUqTMV3Kogb33PT8LJkHzYpoqwPSyooeNLm4yBQ+q7M3H2EEmoaelTM1bebTr6DB/4xhgCg6lca0Rd3qqyMm48rHS2SjjwLe4lxv1Gvhazb85aI2gTr8wR+Dns0TQbFrlgbxbWMH4FwIXIhofdPDCAXB4B6DSk6eDXMf4isRFfhmeYyrF5z0sP9CWvsTm2QqTWFKKBQRjRvlHZCQnu3xi7bjCmzuLp4EOTkC3inVTYt9GjDjwYl3QyCQ+bKTUA4OCbrq6Py/xkWtpOixWqOG5w95fVDKQVgAOlXYLxxN4/k6GJ/LaFpFcbvIFr3T248n+Ab8goJadR52C8dI39BLtWC+7lTxSdYWBaZm1uQiMi3Vmzc0PsECNpKdAgQJPlztFCafmu9wMQ9mPs2ZlevtcC55Swbli/kJYw6T9X4AeexxCxrIO6FY8JYW2HIh1vjTHJ1L83nZ1SytjAv/p4V97X0wWuNROa54pzDkaQL2BOBdmzZ+pi0yi+WMLGc/3zC2zGWOJQNpJLS1KGdjkx50QOc3c7LQL56SMxj4vWIviH8okPohDbErXaaET10VHyyrVxLr8UMP9FEzSmLZ99KyNQXJcHTtC1IGR0afb0rLkMKjDYCWW3valQNHynnBR4bZP22H6MlNZDZCAhtMSYF3IcLztURXlyKJ6wq2Fsf05CkRrjRAVHMNceAQQme4bKOilekVh/XP3hyi6piK3HAp+JcnzRWLyGYPfcfaiJ3c6GdCTAY/9cJAEf77YXGMdFmH4Tr5+0NQ3qs9Qoy4lDWPajXK1fJqFwo9rcfVk08/JNyD8fmJHFif6ikV1EWM1+651xbT5FQzJpzWihEqO/Bnfn9a/XiGEB/DssdO1J/Eb3iUZPGbetR3HdT7vNOWaSULq6ZjWvdkHYvwgFe+lhUQ5FBG5Yca3g6TRqJqPoNudPtiIaFUv2wwNr905OmTCi52+ucpMrWSNE4fmlypw0EhffOFd25HaoTpR51vNpl2Jv9B0hz22Olj9mZlroPxq/q1gyEwnWImeMgUzi7DEvk3ctA/B/MJ/92P4vg1X7A4tkxHRYvAIx62HlxLVCxfUwrz3AG7hsLJagdDKHdsYhyMr3P7wyrZg/Esv8+AptHfqv96IP/hveIsHHeSXHxLRgSB90asDt0GNk1FZUV7GTVMiWkRrkgF4+rEBs6TDpkgy+DEG6P59JllUZWL6H/uoFlCyFAQfdETeyl37CE8JHPHTTjK8rJWln+nOHLYljmHhSor42LcKXXqWl/v58Ji93T0wTrfIU66t+PzVPEeVtVhHF+Hoas7anUIoiM17+umzlzlpzycjRb+UyZFFYVb+Dp5Waxuki22mqFa+a6ZXy2OoBcfGeaj0WWZ4Z5eoNVvJ0Iqq4h1Sd0Iw4VISnARuyOyGPy7IVLKBy7OrDPkYtGmLMjkuyrkoxdiznbbOigkqZJsNDPTdD93jGhG0t1cR/PqBoNUOdIxsSPmfJipKrd0+gL6GYYfY0XQ27XhNM6iP/3/G+RNxBf6SlPmSOXNhsC4QaJzmy8COKweDW9Hi168r7AfAk++qEX8tLLM060/xIoqXOZ71zo3Kt0JeRbwqFkjMHq7ZCcYU1LTJBPbkZw7SGNTQdrOZz/GD9E3384VlYFo/18VtQFd6MEpKaDLIYjEdGuekeajA96S6h9k13n+auEzDBeHEQvXmJ5d8bf7KfL0qETTbptBGbesaZZEWtm6OdrR0GB80jHA6IbF0m5jkYDctL5gjjevpKtsW/UqHOVC4Pp+vF3EGTjSwnSTHie2appDRtjFbhOAzGjPotkQEePJyyCSKFB75yswzFZ9gZHlzBz078WOUQlelCPTsyQVbQFvEzvqTIxqhLimu5fpCNE4G+9pPnt7ptPYJj2SLdqw+JHSEMPPL8MsLL8FgyEOdAra4pL/RMRnfms7AmGtDSpbmaI4BsVGdXFa/OZNHJ2Hv/doMJgq5o9TqtgYQ++8uL/DOImkckj/cjcM7tpKGF0TqCbbqn6EFDt6jtIDzZjkUNNy+jpCJts1hCj1bs8SQH0bzw7rs5yHOzljbvz8N1g6jwBKcVStkFr9IdxTvxW3PejuGoc4CSh9zwEZ2CiedISd4OlcODmr7VZFqlXSv6gzteyhv6RjYj96qYLxWkQoeD4Py9+RQ1wuOFm/6KNjul2HYOOap+82RM/0A1kKcQhF+DAeOPpwzKZEVtbRwEZX2pCe4NXnpCZLia5oSol2IpGr/m4tKzr9AjDG1EB6PWUgO2gyYhWzrA2qt/wezIQ9tppnUkoAlfEH6kule0GbJMBiXmGpr+IESTnyoD4miyLiYxYB6T0T6/DbKOGAE="
    },
    {
      "type": "text",
      "text": "# The Missing Page\n\nThe dead man had been arranged with the kind of care people usually reserve for sleeping children. Hands folded over his sternum. Shoes placed side by side at the foot of the bed, laces tucked in. Someone had even drawn the curtains halfway, as if the morning light might disturb him.\n\nDetective Inez Halloran stood in the doorway longer than she needed to, letting the room tell her what it wanted to tell her. Rooms always talked, if you let them. This one was saying *nothing happened here*, and it was saying it far too politely.\n\n\"Neighbor found him,\" said Patrolman Deaks, hovering at her elbow. \"Door was unlocked. No sign of forced entry, no sign of a struggle. Coroner's thinking heart, maybe. Guy was sixty-one.\"\n\n\"Guys who die of heart attacks don't usually take their shoes off first and line them up.\"\n\n\"Maybe he was tidy.\"\n\nInez didn't answer. She crossed the room, snapped on a pair of gloves, and crouched beside the shoes. Brown oxfords, recently polished, heels worn unevenly in a way that suggested a bad left knee. She picked up the right shoe, then the left, and felt something shift inside the toe.\n\nA folded square of paper, pale blue, lined.\n\nShe knew the paper before she'd even opened it. It was the same shade of blue as the cheap spiral notebook she'd bought from the pharmacy on Calder Street that morning, because her old one had gotten coffee-soaked in the car. She'd grabbed it off the rack without thinking, paid with exact change, and written exactly one thing in it: the address of this apartment.\n\nShe unfolded the paper.\n\nFour words, written in blue ballpoint:\n\n*He wasn't the first.*\n\nThe handwriting was slanted, cramped, the *t*s crossed low and hard, the way her father had taught her when she was seven because he said it looked more decisive. Nobody else crossed their *t*s like that. She'd never seen anyone else do it.\n\nIt was her handwriting.\n\n\"Detective?\" Deaks leaned in. \"You got something?\"\n\nInez folded the paper back along its creases and slipped it into an evidence bag, keeping her face very still. Then, as casually as she could manage, she reached into her coat pocket and pulled out her new notebook. She flipped it open to the first page, where the address sat in her own familiar scrawl.\n\nThen she ran her thumb along the spiral binding and felt the small, ragged teeth of paper where the second page had been torn out.\n\n\"Detective?\"\n\n\"Get me a list,\" she said quietly, \"of every unattended death in this city for the past six months. Every single one where the coroner said *natural causes*.\"\n\n\"That's gonna be a lot of names.\"\n\nInez looked down at the dead man's folded hands, at the careful, tender way someone had placed them, and felt a cold certainty settle in her chest like a stone sinking to the bottom of a well.\n\n\"I know,\" she said. \"That's what worries me.\""
    }
  ],
  "container": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "stop_details": null,
  "usage": {
    "input_tokens": 28,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0,
    "cache_creation": {
      "ephemeral_5m_input_tokens": 0,
      "ephemeral_1h_input_tokens": 0
    },
    "output_tokens": 1633,
    "output_tokens_details": {
      "thinking_tokens": 656
    },
    "service_tier": "standard",
    "inference_geo": "global"
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-opus-5.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-5.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
# Recursion

**Recursion** is when a function solves a problem by **calling itself** on a smaller version of the same problem, until it reaches a case simple enough to answer directly.

Every recursive function needs two parts:

1. **Base case**: the simplest version of the problem, answered directly without recursion. This is what stops the function.
2. **Recursive case**: the function calls itself on a smaller input, moving closer to the base case.

## A Simple Example: Factorial

The factorial of a number `n` (written `n!`) is the product of all positive integers up to `n`:

```
5! = 5 × 4 × 3 × 2 × 1 = 120
```

Notice that `5! = 5 × 4!`, and `4! = 4 × 3!`, and so on. The problem contains a smaller copy of itself, which makes it a natural fit for recursion.

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

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

## How It Works Step by Step

When you call `factorial(5)`, the calls stack up until they reach the base case:

```
factorial(5) = 5 * factorial(4)
                   factorial(4) = 4 * factorial(3)
                                      factorial(3) = 3 * factorial(2)
                                                         factorial(2) = 2 * factorial(1)
                                                                            factorial(1) = 1   ← base case
```

Then the results are returned back up the chain:

```
factorial(1) = 1
factorial(2) = 2 * 1  = 2
factorial(3) = 3 * 2  = 6
factorial(4) = 4 * 6  = 24
factorial(5) = 5 * 24 = 120
```

## A Real-World Analogy

Imagine you're standing in a long line and want to know your position. You ask the person in front of you, "What's your position?" They ask the person in front of them, and so on. The person at the very front knows they're #1 (**base case**). Each person then answers the one behind them with "my position + 1," until the answer reaches you.

## Common Pitfall

If you forget the base case, or the input never gets closer to it, the function calls itself forever:

```python
def broken(n):
    return n * broken(n - 1)   # No base case!
```

In Python this raises a `RecursionError` (a "stack overflow") because each call takes up memory until the limit is hit.

## When to Use Recursion

Recursion works well for problems that naturally break into smaller, similar subproblems, such as:
- Traversing trees and folder structures
- Sorting algorithms like merge sort and quicksort
- Mathematical sequences (factorial, Fibonacci)
- Puzzles like the Tower of Hanoi

For simple repetitive tasks, a regular loop is often more efficient, but recursion can make certain problems much clearer and easier to write.
````

```json
[
  {
    "type": "message_start",
    "message": {
      "model": "claude-opus-5-5",
      "id": "msg_011CfJq56VHXzuR3jeXnycTD",
      "type": "message",
      "role": "assistant",
      "content": [],
      "container": null,
      "stop_reason": null,
      "stop_sequence": null,
      "stop_details": null,
      "usage": {
        "input_tokens": 24,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "cache_creation": {
          "ephemeral_5m_input_tokens": 0,
          "ephemeral_1h_input_tokens": 0
        },
        "output_tokens": 2,
        "service_tier": "standard",
        "inference_geo": "global"
      }
    }
  },
  {
    "type": "content_block_start",
    "index": 0,
    "content_block": {
      "type": "thinking",
      "thinking": "",
      "signature": ""
    }
  },
  "... 169 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

stream

`boolean`

▶metadata{}

`object`

▶thinking{}

`object`

▶output\_config{}

`object`

▶tool\_choice

`one of`

▶tools\[]

`array`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5.5/#page","headline":"Claude Opus 5.5","description":"Claude Opus 5.5 is Anthropic's model for long-running agentic coding and knowledge work. It combines a one million token context window with adaptive thinking that is always on, a 128K token maximum output, and a medium default effort level.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Sonnet 4.5 is the best coding model to date, with significant improvements across the entire development lifecycle.
title: Claude Sonnet 4.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Sonnet 4.5

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-sonnet-4.5`

- Third-party
- Zero data retention

Claude Sonnet 4.5 is the best coding model to date, with significant improvements across the entire development lifecycle.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 200,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://www.anthropic.com/claude/sonnet) |
| Zero data retention | Yes |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$3.00</li><li>Output (per 1M tokens)$15.00</li><li>Cached input (per 1M tokens)$0.30</li><li>Cache creation (per 1M tokens)$3.75</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
# The Three Laws of Thermodynamics

## **First Law: Conservation of Energy**
Energy cannot be created or destroyed, only converted from one form to another. The total energy of an isolated system remains constant.
- Also stated as: ΔU = Q - W (change in internal energy equals heat added minus work done)

## **Second Law: Entropy**
The entropy of an isolated system always increases over time. Heat naturally flows from hot to cold, and processes tend toward disorder.
- This law explains why certain processes are irreversible and why we can't have 100% efficient heat engines

## **Third Law: Absolute Zero**
As temperature approaches absolute zero (0 Kelvin or -273.15°C), the entropy of a perfect crystal approaches zero.
- Practically, this means absolute zero cannot be reached through any finite number of processes

**Note:** There's also a "Zeroth Law" (named later): If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This establishes the concept of temperature.
```

```json
{
  "content": [
    {
      "text": "# The Three Laws of Thermodynamics\n\n## **First Law: Conservation of Energy**\nEnergy cannot be created or destroyed, only converted from one form to another. The total energy of an isolated system remains constant.\n- Also stated as: ΔU = Q - W (change in internal energy equals heat added minus work done)\n\n## **Second Law: Entropy**\nThe entropy of an isolated system always increases over time. Heat naturally flows from hot to cold, and processes tend toward disorder.\n- This law explains why certain processes are irreversible and why we can't have 100% efficient heat engines\n\n## **Third Law: Absolute Zero**\nAs temperature approaches absolute zero (0 Kelvin or -273.15°C), the entropy of a perfect crystal approaches zero.\n- Practically, this means absolute zero cannot be reached through any finite number of processes\n\n**Note:** There's also a \"Zeroth Law\" (named later): If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This establishes the concept of temperature.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01GZMN4RKsBb5RHXUJYBgBdG",
  "model": "claude-sonnet-4-5-20250929",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 17,
    "output_tokens": 240
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
    temperature: 0.3,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python.",
  "temperature": 0.3
}'
```

````
# Reading a JSON File in Python

You can read a JSON file using Python's built-in `json` module. Here are the common methods:

## Basic Method

```python
import json

# Read JSON file
with open('data.json', 'r') as file:
    data = json.load(file)

print(data)
```

## Complete Example

```python
import json

# Reading JSON file
with open('data.json', 'r') as file:
    data = json.load(file)
    
# Access the data
print(data)
print(type(data))  # Usually dict or list
```

## With Error Handling

```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
    print(data)
except FileNotFoundError:
    print("File not found!")
except json.JSONDecodeError:
    print("Invalid JSON format!")
```

## Reading JSON String (not file)

If you have a JSON string instead of a file:

```python
import json

json_string = '{"name": "John", "age": 30}'
data = json.loads(json_string)  # Note: loads() not load()
print(data)
```

## Key Points

- **`json.load()`** - reads from a **file object**
- **`json.loads()`** - reads from a **string**
- Always use `with open()` to ensure the file is properly closed
- JSON objects become Python dictionaries
- JSON arrays become Python lists
````

```json
{
  "content": [
    {
      "text": "# Reading a JSON File in Python\n\nYou can read a JSON file using Python's built-in `json` module. Here are the common methods:\n\n## Basic Method\n\n```python\nimport json\n\n# Read JSON file\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n## Complete Example\n\n```python\nimport json\n\n# Reading JSON file\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n    \n# Access the data\nprint(data)\nprint(type(data))  # Usually dict or list\n```\n\n## With Error Handling\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r') as file:\n        data = json.load(file)\n    print(data)\nexcept FileNotFoundError:\n    print(\"File not found!\")\nexcept json.JSONDecodeError:\n    print(\"Invalid JSON format!\")\n```\n\n## Reading JSON String (not file)\n\nIf you have a JSON string instead of a file:\n\n```python\nimport json\n\njson_string = '{\"name\": \"John\", \"age\": 30}'\ndata = json.loads(json_string)  # Note: loads() not load()\nprint(data)\n```\n\n## Key Points\n\n- **`json.load()`** - reads from a **file object**\n- **`json.loads()`** - reads from a **string**\n- Always use `with open()` to ensure the file is properly closed\n- JSON objects become Python dictionaries\n- JSON arrays become Python lists",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01KF2gMfuUeqNjxZytqgkfGd",
  "model": "claude-sonnet-4-5-20250929",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 28,
    "output_tokens": 371
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.5',
  {
    max_tokens: 1024,
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.5",
  "max_tokens": 1024,
  "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"
    }
  ]
}'
```

```
Here are some great stops between San Francisco and Los Angeles:

**Scenic Route (Highway 1/PCH - about 10 hours driving):**
- **Monterey & Carmel** - Monterey Bay Aquarium, 17-Mile Drive, charming downtown Carmel
- **Big Sur** - McWay Falls, Bixby Bridge, stunning coastal views
- **Hearst Castle** - Historic mansion tours in San Simeon
- **Morro Bay** - Iconic Morro Rock and waterfront
- **San Luis Obispo** - Downtown shopping, Madonna Inn
- **Santa Barbara** - Spanish architecture, beaches, wine country
- **Solvang** - Danish-themed village (short detour)

**Faster Route (Highway 101 - about 6 hours):**
- **Gilroy** - Famous garlic capital
- **San Luis Obispo** - Bubblegum Alley, Mission
- **Pismo Beach** - Classic beach town
- **Santa Barbara** - Mission, State Street

**Tips:**
- Big Sur has limited cell service and few gas stations
- Book Hearst Castle tickets in advance
- Consider splitting into 2-3 days to enjoy stops

What interests you most - beaches, nature, food, or historic sites? I can refine recommendations based on your preferences!
```

```json
{
  "content": [
    {
      "text": "Here are some great stops between San Francisco and Los Angeles:\n\n**Scenic Route (Highway 1/PCH - about 10 hours driving):**\n- **Monterey & Carmel** - Monterey Bay Aquarium, 17-Mile Drive, charming downtown Carmel\n- **Big Sur** - McWay Falls, Bixby Bridge, stunning coastal views\n- **Hearst Castle** - Historic mansion tours in San Simeon\n- **Morro Bay** - Iconic Morro Rock and waterfront\n- **San Luis Obispo** - Downtown shopping, Madonna Inn\n- **Santa Barbara** - Spanish architecture, beaches, wine country\n- **Solvang** - Danish-themed village (short detour)\n\n**Faster Route (Highway 101 - about 6 hours):**\n- **Gilroy** - Famous garlic capital\n- **San Luis Obispo** - Bubblegum Alley, Mission\n- **Pismo Beach** - Classic beach town\n- **Santa Barbara** - Mission, State Street\n\n**Tips:**\n- Big Sur has limited cell service and few gas stations\n- Book Hearst Castle tickets in advance\n- Consider splitting into 2-3 days to enjoy stops\n\nWhat interests you most - beaches, nature, food, or historic sites? I can refine recommendations based on your preferences!",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_013M3Nhg1ApNNGZf1GWxRHUj",
  "model": "claude-sonnet-4-5-20250929",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 76,
    "output_tokens": 310
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.5',
  {
    max_tokens: 512,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    temperature: 0.8,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.5",
  "max_tokens": 512,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "temperature": 0.8
}'
```

```
# The Blue Feather

Detective Sarah Chen had seen plenty of strange things at crime scenes over her fifteen years on the force, but she'd never seen anything quite like this.

The penthouse apartment was pristine—too pristine for a place where someone had allegedly been murdered just hours ago. No blood spatter. No signs of struggle. No body, for that matter, despite three separate witnesses reporting screams and a gunshot at 2:47 AM.

She was about to call it in as a false alarm when the morning sun shifted through the floor-to-ceiling windows, catching something wedged between the marble tiles near the balcony door.

Sarah knelt down and pulled out her tweezers. The object was impossibly delicate: a single feather, no longer than her thumb, glowing an electric blue that seemed to pulse with its own light. She'd never seen a bird with plumage this color—not naturally, anyway.

But it was what happened when she picked it up that made her breath catch.

The feather was warm. And getting warmer.

Then it started to hum.
```

```json
{
  "content": [
    {
      "text": "# The Blue Feather\n\nDetective Sarah Chen had seen plenty of strange things at crime scenes over her fifteen years on the force, but she'd never seen anything quite like this.\n\nThe penthouse apartment was pristine—too pristine for a place where someone had allegedly been murdered just hours ago. No blood spatter. No signs of struggle. No body, for that matter, despite three separate witnesses reporting screams and a gunshot at 2:47 AM.\n\nShe was about to call it in as a false alarm when the morning sun shifted through the floor-to-ceiling windows, catching something wedged between the marble tiles near the balcony door.\n\nSarah knelt down and pulled out her tweezers. The object was impossibly delicate: a single feather, no longer than her thumb, glowing an electric blue that seemed to pulse with its own light. She'd never seen a bird with plumage this color—not naturally, anyway.\n\nBut it was what happened when she picked it up that made her breath catch.\n\nThe feather was warm. And getting warmer.\n\nThen it started to hum.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01Qf12B9uws6JAnfRfQ6WgBe",
  "model": "claude-sonnet-4-5-20250929",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 21,
    "output_tokens": 243
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
# Recursion Explained

**Recursion** is when a function calls itself to solve a problem by breaking it down into smaller, similar subproblems.

## Key Components

1. **Base case**: A condition that stops the recursion
2. **Recursive case**: The function calling itself with a simpler input

## Simple Example: Countdown

```python
def countdown(n):
    # Base case: stop when we reach 0
    if n <= 0:
        print("Done!")
    else:
        # Recursive case
        print(n)
        countdown(n - 1)  # Call itself with smaller number

countdown(3)
```

**Output:**
```
3
2
1
Done!
```

**How it works:**
1. `countdown(3)` prints 3, then calls `countdown(2)`
2. `countdown(2)` prints 2, then calls `countdown(1)`
3. `countdown(1)` prints 1, then calls `countdown(0)`
4. `countdown(0)` hits the base case and prints "Done!"

## Real-World Analogy

Think of Russian nesting dolls:
- Opening one doll reveals a smaller doll inside
- You keep opening dolls (recursion) until you find the smallest one (base case)
- Then you're done!

## Common Use Cases
- Calculating factorials
- Tree/graph traversal
- Sorting algorithms (quicksort, mergesort)
- Processing nested structures
````

```json
[
  {
    "message": {
      "content": [],
      "id": "msg_01UgonW6EAQVn2dqA3yEGcj6",
      "model": "claude-sonnet-4-5-20250929",
      "role": "assistant",
      "stop_details": null,
      "stop_reason": null,
      "stop_sequence": null,
      "type": "message",
      "usage": {
        "cache_creation": {
          "ephemeral_1h_input_tokens": 0,
          "ephemeral_5m_input_tokens": 0
        },
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "inference_geo": "not_available",
        "input_tokens": 19,
        "output_tokens": 1,
        "service_tier": "standard"
      }
    },
    "type": "message_start"
  },
  {
    "content_block": {
      "text": "",
      "type": "text"
    },
    "index": 0,
    "type": "content_block_start"
  },
  "... 15 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting Claude use Anthropic's server-side web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.5',
  {
    max_tokens: 4096,
    messages: [
      {
        content:
          'What were the top news stories about Cloudflare this week? Summarise in three bullets.',
        role: 'user',
      },
    ],
    tools: [{ max_uses: 3, name: 'web_search', type: 'web_search_20250305' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.5",
  "max_tokens": 4096,
  "messages": [
    {
      "content": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
      "role": "user"
    }
  ],
  "tools": [
    {
      "max_uses": 3,
      "name": "web_search",
      "type": "web_search_20250305"
    }
  ]
}'
```

```
Based on the search results, here are the top news stories about Cloudflare this week:

• **Ongoing Network Outage**:
```

```json
{
  "id": "msg_018Y4VGmTsaUk4xzCg2SNi29",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "server_tool_use",
      "id": "srvtoolu_014NoiMmSbNDc3u27gXvxmcd",
      "name": "web_search",
      "input": {
        "query": "Cloudflare news this week"
      }
    },
    {
      "type": "web_search_tool_result",
      "tool_use_id": "srvtoolu_014NoiMmSbNDc3u27gXvxmcd",
      "content": [
        {
          "type": "web_search_result",
          "title": "Cloudflare Status",
          "url": "https://www.cloudflarestatus.com/",
          "encrypted_content": "EqYhCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDIyAkytV6t9Xl4wlaRoMgJc4jF6mibU06qMIIjDLvos/nKAejFRM24UKRnihBKgGSxKzJFa1UFAFriwrG1BVJ+p3Jt2stDiOuSRO1tkqqSDO4PSQBXN024Zt27cMULUq7bDfQpQqUEK9s5wX5cSku6Atq7liMUZQAF2M72T1QODwCnWw4mTeZccj5fGm4Kz945HcgrWcMIYFmzcCnEaYMztL1Y+aupeGNk7JfQ4704Dq2vs8gvB5rOkcF28WOsm64SeU0wsMOqf0f/AHxZisMIojY8UVqBHkaNHUJeFbVbYJVTcalkhxbEfLBBrtyn5MXcYeFxJGt/1FHQ3GtDwsx6bIAQjuwmxAiw5E8odcIHAygsHmDq295u/a2zLYZ6nHD9ubDONFRoehj3jQlKd1ap8+6Lu1fAHUQqPvkQvTSaghKlZy0UboNZtqBDcIBvsAqOBa2KQF9d/mvsQm8om/31aqDPP3G6tPv+9Uk5pLfX8hbjltMk1cf9PUTqAt8WOviYTF5enJ5c70me8PUfaYJlkXVRB66XTEjAQHsCWA3kTFQTyEnM4MQAW7uoXgLZfskM9pSJYw5x7t2fXeATjSlPoeoubebxXivK6w3qlhSbJA5Kt0d1yHbj25jCA0HCHN6OwJHq7eyG+sbyeNDsxR5t35PvrfAonZ0O61lkUVJfa4DNwrWQDm2FAfpsnvY8tw7N07J7Bf2OjdFs5QDonB51l+70WQsg56ChgxXWinu/SOAvX4Hujr6NLlgvbjTXuHvCnBMxkF5Wp+2t2abU3JUkULlBmqqW0Drzq0MRsIRyK1P6JjUyA5Lk54BOI8Pj6RRGMxhQGjqUff42dy5RJW8MdqlPpnRjoK9fffvBqY/zFWlfp1rkS/k4WV1uDgk8Ktxant10iIGev9Aoam4x5jQPRstrV8nImqLvaag7Dkzgho5/XDgk3oafBfvSy4jdNmVj9NgwG4IuDbJW42ll3C2gxeIzvhsqv37R9dXS/usG1w7aFHg4kSELxFV2Ch7w4oYeVJmagOZaCXuZwHONyTJfgd45YIi0E8FuJYFi/RGuZeYxOGCzrCVsy1Rj6e34mGE3Kip8fRiPR7mv8TzFIXHGgBE1KNJHwhZvXC9TiJBcfLnUyKLOP+aveNTdbLCK/d881UwetWT1UPPg+o5v+OYR3yJUL/NODy6jMiZSkdWeXuH2fYsI/cRbsrQDVO6dUOzZn6mfAYc43AJvJ38UfWYjpYdJbXGfgw4fKOk5IWhtXCJK0veclgMAgR6MZvjaMq025bnEKEZmNIR6yxdCm3HaIbv+vwU0gr4Y6ASk6cxJdlckCeBc86OmeycjMnd/u+fn5rkWvuhnInedzMH5LspKru7FVY5IvC8MvyQ391gYG8r4/gh3LQ/giUTNdmAZyeAEwsLrOfn6ckvfdWNyWcZAoVEQm5LTnUDh/tRtzsv1sUDe3PPBXuck6OhlzVBiS4zO+j9pXJkC8yWjz6S+ovY1bp2GNI088lJdKl4FUK3LUjhS3QYg3ph6gIytC12YWbXimyqKG7ItomZMTEOwXf2O5yCwK5J+4LrmOapkRcixqo9D31RMsqX1bxfIv3SY9jfix5SPmSQX7UEcbq8z+KZzOyiCsOsy4xNojaKNyMlm0lXt1P/nGo0jqmKbB5joJZmkqSqcnbh8fSDfsrs3HxL9dEZLBenyh/F+MVu0Om+GBClJe6RWlQ0LKrbxvqF9+EepFBOTZHEAnuzNYIG1rJn7D8l9LiOoNBubKbolUAvU42Its32+qn+rYjS32pYErMAClSi8Ax/6NgKOkAYRoB81SqBaNe611nnNIGNJY5XI1z27mt/CZuVgQ+ZC04DXJKcwaksJTkMcZoq7TGiP0/Rr3vE0IFQGT5DboKGTR+uyMAkHCPStQAnV6wUIG0BDt0UyG4DWgO6lGM/GTnDduNqFGy15aXpDsuHUQH+yiCRHmdB19LI6uR6PAQTbAAHo/5Zez6A3GRdfIDpBDsb8BgfVyNAKmC1hBLwlZCTBQm7VO6CmcAsTkApBQWX3kqUaofdvpPSuIbpy4gcP6FBXOlUGUuiC8f9gnZpSz+Y+/Vu6+ViKtUtlw6XVf8M2TjYXxLqttIb5aCreXpMLPbwhn6Xa/k7gA2d9xGHeRtW76npUBcisBMQg92ndiilcQccxW/oCRRh8YsdgCVg4Lm30XiLKLwzVTrNbq2wYIw5kOHFmqfydUQ2k1wetvlZvDJYjWXF8A/LzpgM20pNck7HMl8drBurJymTQvJM46zWjblH1oprUcRi4DtMKZQ9kbE930zZGb9aL5s33EE/GddvAsQpreXCwT56F6xqoBqlX3bJexaCH+yaSO3X5V/Wbkd2ylSHVEwmTfnqR71rhsO9zFn+K5L9X06+qa4nOWJ6kSoeOhptXgfP0820ZBscbyBGiaNyz0gFcxG04lXR1cHFBPHkjp9WBgorgQfVrQHbzprHpSXvetPSUz00q+kLveuf4Vn/PdymtblKUuxT3wuaGFlAfJIcVum3QYOPddF1/zcLLC1BTsHA/gL/zbhHnKrAMSeNF9ax9fZeJ+cwgYwxx+MjnETZE5hsbhWHzdhvJOU6sfgYQWcVhgdcq4yil1/kPwZhja+eeaxdMzQW2KSaP4i15m3Y0H8FM9wvIT7oVRRmQzhj+gM7sZgkEDrvqfGvNARPphABTZMbSrNNs5Kq58isD2kYbZ/62o+GiotpCe24CFXobWvS1J5V/12II0BBQr5GiIDWquEEnNarbfCDF46kDbiXDNhQ5Lh9hQcx5aNCQh9Ho9HhOoVDstZruKAlXq++JnLUDnA15qsw6+6FYW9vu/m9Bt4gAx+FuDI1olJ4op0Xlp6Mj9HyXIZ88FtwZYt4bEkVy6vgYvEi7Nt809R4fyGEtjqbcXhmYc+sKfNob0Oi6gt7g9E6teZRM+SIyawLlnbsCKf4jxzw1tPcodi7kzh4KI+JASfwkMnWL4SxIxfE7A7Moi9I5l1U9ssEH2K9+9ckij2+mngTm1hCyr3FC8CZ1IRAmIdR4zdIcB2Cis/TEEPpar9zt/VF2pMMl5o82zDFJ2hg/9xwpnnkTg9+Cj5cU8kxWbAEK1RPLqMP0Zr8jctw2Q3Vt292K/dQHh6lRnWer6VuwpCtrYzW0pVJtdwahqBU2LwW/fCzljD3SyLjMoEvVj1Yc/E8izA8UygEQFHXh2swy2WtiUhtgimDisZcgta2P0Yo9DYZ44dLvsmm1LcCSIgG8HakC+rokPGQTBYc9ES+vgY8mHb1s1PnVdnocifG6h7pHC0VtrVLbwajfv0sWAEwhww8I6NePQeBbB5Q4G9sJPfvsnG4Myza1SfcS17Z4bX52P5ad9DKEoeLHpBBHAwDNTm7Qxxz1bQ2e+0ry+CQr9We4dFKSxC3/IBZ/SzQp/5z+rCHkYK4F0pbg/iYJdOkcmI6PHtgxxqdEZ8w6ZPOLou000C70FHDAA4kcIpV6FbRVpIWpUEnNbnJ4bnOcOKtyRqN/zB48UlZaXyFyRpEyvlwJIhBAM26BSTv8Hu6j6JPP/pY/GTPCya0fQOksiDMiR9DMZnl3x6TgVinZmUshxbhYvydRaEYC3jzDT77jmr/RCDLJrmzBY8o6RnZH16ds5t/G7wDtPGIM7rp52RVkfjL21HdZ85DP02ThCR/gjjL+6yt/f636y8YSepJkHRtfFdUeqTNcF8m8A9W8AhC1FGCsdRPqYvlwMvJdOvbCM0ii5eewS9f8gkNqRky8D/EBpwBMj65WWSEmA1ifbYIDnGlrnD/XAd/FJ7wahtopfFZJwe4rk8FzPGWDQAg82HIKQRLpqA5tIm9xH/3ZUkWcV+u5xA1Btwg13AUrXtKNVkzlPD5iunfeNDzryNuZzaRylNZ0pXViZSyDpTX2c5SC1Sjrgsqn1AiyUal57Klg4i8yJUsWGy/Y0567uLLDPyMKmnIOUbNjk7wl68hr2ksEHIy842TDXcZk+lLoy/+/SDdh5twkXKu+U6qHj8CeDJEcYsBEaF1tKtFqcRu9ttWa7v+esymxy3wqsjfUJnElWGYyJwLeoScmPz5vkKRYXABkowrk8HQJGSUdFsvvHjpDMb/IP80DoAnF+JkHbzUb8YKjfXKVxPA4tIYL2mt5J+JH5uxUDFpSQwXzwjTxTB8sO2iMN029zd5Feob4yMb1DWGCFfam3WNlt7iSzx2gA7fJmRaBK6ReUNqxl788IPAblSib/s6yVeiJcghg4gHDbWc/0bX9rn8isaGgxJ1IjrsSxv3lnXrj/aHofRv+1aiT8CGdM6VAEqzLq5f1UOSXEuT2WS6fUuHijEQ5A6O/9aBQM4R4OBlQ0NcDRxDibHPsX09MD3r2R3/JV56LZ0+rUo2EMnyucHfOW2ucRlq2Co4yoIpx5gqEe2DZTlLtybBEqV6yu6uhIz/QBO4DTUShW9wCAQVAYPlNCQpkgasb5sqeu1tVsC7RkVm9D5ZH4P7ZmIrM3glEQqSuUBMkA0z+i72yZTISnUa6WR1BpBZPewJlzCQ42G2342Wczxsogv+9wsrPi1wswws6B4A51anBYls30jQbObh1Xm8G09eRcefHvNT995pzy35P0iuwmThTC3FUUbwwLOpi76SEZ2CmnjAC4zGCfkjxL557kphRRXDUplaUaRT45MGpXDmy4wYM1YfGzhuYKcPk19tfbU34kH6puuv0z4emDnMiVSF3qU4mj749kPdHtYt8d5YOmcP6ZYu84JylJUtT3wDapqEdCjA4/R+aHNuWVPDiV6IR45zDG8Bs0tYSdxNLbczSiKkDiY7dletufsgmi6ko3cGKrCAAqoilU4wHSjEtUQkaV5NddhfMAEx5n4h82ZqB32ZguFPbo67wnlmKDjtAoFoiLYEvpy3jRvVEy235eq/rVLSbjl7ND31XXBrBUBIBhH0B5r2wQRCxdBgq0RsTV8pJES3YIX+2xq9lI/M/eAMciMw9SI2WI4mL4HPQE6P3MuzS1al+D3lZhx32zJN6jVJgAFx+0wPfXCfAxRhXHAa7wVfWOVHhwk6aUp+bkJL0bjgu94qW1OAfQqXhrbuKc+QB1ywSKKlrMK9l4/q0SZPt1/4ZjeIatunWv0DawI0CcHceVlrtUbQ70DqUKYEWwbkGevJZEU19D4DlvyCXbrJIVKLhJJZ5nGbbFVejWQPHFN6+xojDxXZmuWq6HFqeK+Wx1/y792ITuzyreaA4NxkiJuzYStswBJ2AzSUK6uPUmUQED9q+lwMPFE3WCF+FZcBej+YnR4GuWLE5HXsYv81DqG7cghKYhyTzxa0H/klFQ2mc466FbOzPT+bqpmsZSSAvCpxZX/C8jrY4ZwJZANO9ybaIbcR4MBQY7XXnik/vTByIM6orbIzhEJdUhjw8wmQunPLzvXY2CuYgA6goLZM6yYaIy1qtkXU+hx6cYLjOEXOWQhALdEG0300LUPRzHLv27SZkI86GS0GfhQsDypnexZSS98Aodj56M4AXs6p2rXryTT3rjBlE+laidV1lW6DnPvcNx2b7AuiJ8yusmUPd30It1rxgWnfXvAsAl+J/dRQmV24DAKmKmAvh7tHlD7b6N79eEXzN3sLAeljampwUFHRzQYAw==",
          "page_age": "2 hours ago"
        },
        {
          "type": "web_search_result",
          "title": "The Cloudflare Blog: Product News",
          "url": "https://blog.cloudflare.com/tag/product-news/",
          "encrypted_content": "Eq4RCioIERgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDPxF37VWzvD0IwnS6xoMfestyfsaChUSVJSpIjCYuV32cdisnHf8bzAn4Fj13E6MmFIQmyyo6WnLAHWVDwisii7KAble8MguJTzCMOIqsRDAP9d02MbbbyD8Ewhhs2wnoh0QYHNnxGrZHXvLWDKInrCy6lhQygvLecfKEvvOXYrICCSNl+tyioICV1M7ktvUktJ2Efm5nLw0L1C1/vLQeQQ5LFKEXqhYz/W+Xds28/aH6udGZMBTduyytOsd1fDAcwIztMuZQtrESOpOZPVxblbxYFBY/4yUGmDh+7HRG86zdAuNCoipu6lykNIKOUsNTY+nxtJPgjdEj0/HhHRwf7REaerssFXgUw5WdQmRXAxP649+Cfjik0qrvNGgGTthdoH9nO/uK5udkIPErGU81Pasti6uSzAl8AeityGxKp9lpBpmRsPfTLi+YdLwDTO9FezP/+OGhw+nDsddcF7bCK+M43CbfSL6iHwUkuSXYrxN6vPyfX9Rk13SjaB+rnEQOjQMHtXsKxNPR7VIecaQiJ2TxRWWSZ7+S4qiFPNXDyKM/OW8rCv++JdC7YAKxiZva/LE2uS1sX2sr+LcuSlYg6QPy9rqoD7go3d6oxXTxFkEoKpWQHI8VCAAo0fo2W+yhgHOT2WewfynS8V0a7Y45suq3CDLWjJ6Pj2E66/E3ONz0A7xV77jszpRjEWbQWpXDocCh/Fflps/+xKqCOGInHGH477cXPq+g4yu1/4EIY0eZZavvQG9Xbr+KAkd4M0g+h2rSxE3pvQdEBzBbmGkzSHmxBnHecjJdoU04yWrSjZH7TYksQ/a8067BY2tcEKD7PQFftQQGlOSSq4XuwBS1Z+/R4i1BGo5KofazOfMDB33FSjPiih3nTS5lgJSC/YwVgTCqKcOlXOs0Ka9sRfYixXre0mZhrWSm4AAB7W/RZ0z1ujbQ//FoCFhd5dgnZOB7raAYIbrkPhZxw2EHMqBqsw+n98/4amJwoa7iQrfC0mpgJ/MLPVh6YNQepPimdLMxEVHBxdsjd/AamCVDEEdaLG2bgnXgy/DaJiq+dFdZb8JNIuvNh1tJxkOLO9RQXDIWF/Dfj1y+4wDRQaHVmIpj+VvCyg006+sUk7jIHvO9jhkj6f6vPWAHTkDJY0wHO+0qmEowvtCfmOohsAdVLj/0grqhNu9j05gdEmpEQvENrk3JiD41XgkKhpeC0DHe4xOt53o9oNwmMDKQ0Ixbc70uk+Mc/Of33stig8M9IA74hMur88SOFItY5bBRMEKoebjc7bLU0Hp20bqGmsfFAGXKDM/4FL/qrZ8BG/AKN73ilnXT0a6sP4gSGZq2gScAMo2v28t6jT0W0wzcjVDCP65R0FvoC7r9bj1PlJWq5PLgh6PH3PllUp/Jzu
... response truncated ...
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

temperature

`number`minimum: 0maximum: 1

top\_p

`number`minimum: 0maximum: 1

top\_k

`number`exclusiveMinimum: 0

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.5/#page","headline":"Claude Sonnet 4.5","description":"Claude Sonnet 4.5 is the best coding model to date, with significant improvements across the entire development lifecycle.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Sonnet 4.6 is Anthropic's latest balanced model offering strong coding, reasoning, and agentic capabilities with improved instruction following.
title: Claude Sonnet 4.6
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Sonnet 4.6

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.6/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-sonnet-4.6`

- Third-party
- Zero data retention

Claude Sonnet 4.6 is Anthropic's latest balanced model offering strong coding, reasoning, and agentic capabilities with improved instruction following.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 200,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://www.anthropic.com/claude/sonnet) |
| Zero data retention | Yes |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$3.00</li><li>Output (per 1M tokens)$15.00</li><li>Cached input (per 1M tokens)$0.30</li><li>Cache creation (per 1M tokens)$3.75</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.6',
  {
    max_tokens: 1024,
    messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.6",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
There are actually **four** laws of thermodynamics (including the Zeroth Law):

## The Laws of Thermodynamics

**Zeroth Law**
If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. (This establishes the concept of temperature.)

**First Law**
Energy cannot be created or destroyed, only converted from one form to another. (Conservation of energy)

**Second Law**
Entropy of an isolated system tends to increase over time. Heat naturally flows from hot to cold, not the reverse. (No perfectly efficient engine is possible.)

**Third Law**
As temperature approaches absolute zero, the entropy of a perfect crystal approaches zero. It is impossible to reach absolute zero in a finite number of steps.

---

The laws are often summarized humorously as:
- **You can't win** (can't get more energy out than you put in)
- **You can't break even** (you always lose some energy to entropy)
- **You can't quit the game** (you can never reach absolute zero)

Would you like more detail on any of these?
```

```json
{
  "id": "msg_015bDPjJ5vm4gY4EH7pALCsh",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "There are actually **four** laws of thermodynamics (including the Zeroth Law):\n\n## The Laws of Thermodynamics\n\n**Zeroth Law**\nIf two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. (This establishes the concept of temperature.)\n\n**First Law**\nEnergy cannot be created or destroyed, only converted from one form to another. (Conservation of energy)\n\n**Second Law**\nEntropy of an isolated system tends to increase over time. Heat naturally flows from hot to cold, not the reverse. (No perfectly efficient engine is possible.)\n\n**Third Law**\nAs temperature approaches absolute zero, the entropy of a perfect crystal approaches zero. It is impossible to reach absolute zero in a finite number of steps.\n\n---\n\nThe laws are often summarized humorously as:\n- **You can't win** (can't get more energy out than you put in)\n- **You can't break even** (you always lose some energy to entropy)\n- **You can't quit the game** (you can never reach absolute zero)\n\nWould you like more detail on any of these?"
    }
  ],
  "model": "claude-sonnet-4-6",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 17,
    "output_tokens": 252
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.6',
  {
    max_tokens: 1024,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
    temperature: 0.3,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.6",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python.",
  "temperature": 0.3
}'
```

````
## Reading a JSON File in Python

### Basic Method using `json` module

```python
import json

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

print(data)
```

### Common Approaches

**1. Read as a dictionary/list (most common)**
```python
import json

with open('data.json', 'r') as file:
    data = json.load(file)  # Returns a Python dict or list

# Access values
print(data['name'])
print(data['age'])
```

**2. Read JSON string manually**
```python
import json

with open('data.json', 'r') as file:
    content = file.read()          # Read as string
    data = json.loads(content)     # Parse the string (note the 's')
```

**3. Handle encoding (for special characters)**
```python
import json

with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
```

### Error Handling (Recommended)
```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found")
except json.JSONDecodeError:
    print("Invalid JSON format")
```

### Key Differences

| Function | Use Case |
|----------|----------|
| `json.load(file)` | Read directly from a **file object** |
| `json.loads(string)` | Parse a **JSON string** |

### Example JSON file (`data.json`)
```json
{
    "name": "Alice",
    "age": 30,
    "hobbies": ["reading", "coding"]
}
```

**Output:**
```python
data['name']    # → "Alice"
data['age']     # → 30
data['hobbies'] # → ["reading", "coding"]
```

> **Tip:** Use `with open()` to ensure the file is automatically closed after reading.
````

```json
{
  "id": "msg_015vWQKd15N4szFzUuNwum2W",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "## Reading a JSON File in Python\n\n### Basic Method using `json` module\n\n```python\nimport json\n\n# Open and read the JSON file\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n### Common Approaches\n\n**1. Read as a dictionary/list (most common)**\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n    data = json.load(file)  # Returns a Python dict or list\n\n# Access values\nprint(data['name'])\nprint(data['age'])\n```\n\n**2. Read JSON string manually**\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n    content = file.read()          # Read as string\n    data = json.loads(content)     # Parse the string (note the 's')\n```\n\n**3. Handle encoding (for special characters)**\n```python\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as file:\n    data = json.load(file)\n```\n\n### Error Handling (Recommended)\n```python\nimport json\n\ntry:\n    with open('data.json', 'r') as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"File not found\")\nexcept json.JSONDecodeError:\n    print(\"Invalid JSON format\")\n```\n\n### Key Differences\n\n| Function | Use Case |\n|----------|----------|\n| `json.load(file)` | Read directly from a **file object** |\n| `json.loads(string)` | Parse a **JSON string** |\n\n### Example JSON file (`data.json`)\n```json\n{\n    \"name\": \"Alice\",\n    \"age\": 30,\n    \"hobbies\": [\"reading\", \"coding\"]\n}\n```\n\n**Output:**\n```python\ndata['name']    # → \"Alice\"\ndata['age']     # → 30\ndata['hobbies'] # → [\"reading\", \"coding\"]\n```\n\n> **Tip:** Use `with open()` to ensure the file is automatically closed after reading."
    }
  ],
  "model": "claude-sonnet-4-6",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 29,
    "output_tokens": 508
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.6',
  {
    max_tokens: 1024,
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.6",
  "max_tokens": 1024,
  "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"
    }
  ]
}'
```

```
Here are some great stops depending on which route you take:

**Pacific Coast Highway (Highway 1) - Scenic Route**
- **Santa Cruz** - Fun boardwalk and beach town
- **Monterey** - Great aquarium and Cannery Row
- **Big Sur** - Stunning coastal views and hiking
- **San Simeon** - Hearst Castle tours
- **Morro Bay** - Charming harbor town
- **Santa Barbara** - Beautiful city with great food and beaches

**Highway 101 - Middle Route**
- **San Jose** - Tech museums and good food
- **Paso Robles** - Wine country and wineries
- **San Luis Obispo** - Charming college town
- **Santa Barbara** - connects with PCH route

**Interstate 5 - Fastest Route**
- This is the most direct but least scenic
- Good if you just want to get there quickly

**Some Tips:**
- The PCH route adds several hours but is worth it for the views
- Big Sur can have road closures, so check conditions ahead of time
- Santa Barbara is a great overnight stop
- Try to drive Big Sur during daylight for the best views

Would you like more details about any specific stop or help planning an overnight itinerary?
```

```json
{
  "id": "msg_015gJCs45CLVWFpG9swxLY1h",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Here are some great stops depending on which route you take:\n\n**Pacific Coast Highway (Highway 1) - Scenic Route**\n- **Santa Cruz** - Fun boardwalk and beach town\n- **Monterey** - Great aquarium and Cannery Row\n- **Big Sur** - Stunning coastal views and hiking\n- **San Simeon** - Hearst Castle tours\n- **Morro Bay** - Charming harbor town\n- **Santa Barbara** - Beautiful city with great food and beaches\n\n**Highway 101 - Middle Route**\n- **San Jose** - Tech museums and good food\n- **Paso Robles** - Wine country and wineries\n- **San Luis Obispo** - Charming college town\n- **Santa Barbara** - connects with PCH route\n\n**Interstate 5 - Fastest Route**\n- This is the most direct but least scenic\n- Good if you just want to get there quickly\n\n**Some Tips:**\n- The PCH route adds several hours but is worth it for the views\n- Big Sur can have road closures, so check conditions ahead of time\n- Santa Barbara is a great overnight stop\n- Try to drive Big Sur during daylight for the best views\n\nWould you like more details about any specific stop or help planning an overnight itinerary?"
    }
  ],
  "model": "claude-sonnet-4-6",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 76,
    "output_tokens": 290
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.6',
  {
    max_tokens: 512,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    temperature: 0.8,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.6",
  "max_tokens": 512,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "temperature": 0.8
}'
```

```
# The Weight of Paper

Detective Mara Osei had seen plenty of strange things in fourteen years on the job. She had once found a murder weapon wrapped in a birthday cake. She had once interviewed a parrot that knew the killer's name.

But this was different.

The victim's apartment was ordinary enough — takeout containers, a dying fern, furniture that looked purchased in a single defeated afternoon at a discount store. Nothing about Leonard Voss suggested a man with enemies. Nothing suggested a man with much of anything.

Except the paper.

Mara crouched beside the coffee table and studied it without touching it. A single sheet, handwritten, covered edge to edge in the same two words repeated hundreds of times in shrinking letters, spiraling inward like a drain.

*I remember. I remember. I remember.*

The handwriting started bold and confident at the outer edge. By the center, the letters were barely visible, scratched by what must have been a nearly dead pen — or a nearly dead hand.

The medical examiner appeared in the doorway. "No signs of struggle. No forced entry." He paused. "Honestly, Mara, it looks like he just *stopped*."

She stood up slowly, slipping her hands into her pockets.

"Then what," she said quietly, "was he trying so hard not to forget?"

---

*The fern, she noticed, had been recently watered.*
```

```json
{
  "id": "msg_01BfiLNfgBobjw33wuZDP9as",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "# The Weight of Paper\n\nDetective Mara Osei had seen plenty of strange things in fourteen years on the job. She had once found a murder weapon wrapped in a birthday cake. She had once interviewed a parrot that knew the killer's name.\n\nBut this was different.\n\nThe victim's apartment was ordinary enough — takeout containers, a dying fern, furniture that looked purchased in a single defeated afternoon at a discount store. Nothing about Leonard Voss suggested a man with enemies. Nothing suggested a man with much of anything.\n\nExcept the paper.\n\nMara crouched beside the coffee table and studied it without touching it. A single sheet, handwritten, covered edge to edge in the same two words repeated hundreds of times in shrinking letters, spiraling inward like a drain.\n\n*I remember. I remember. I remember.*\n\nThe handwriting started bold and confident at the outer edge. By the center, the letters were barely visible, scratched by what must have been a nearly dead pen — or a nearly dead hand.\n\nThe medical examiner appeared in the doorway. \"No signs of struggle. No forced entry.\" He paused. \"Honestly, Mara, it looks like he just *stopped*.\"\n\nShe stood up slowly, slipping her hands into her pockets.\n\n\"Then what,\" she said quietly, \"was he trying so hard not to forget?\"\n\n---\n\n*The fern, she noticed, had been recently watered.*"
    }
  ],
  "model": "claude-sonnet-4-6",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 21,
    "output_tokens": 317
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.6',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.6",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
# Recursion

## Core Concept

Recursion is when a **function calls itself** to solve a smaller version of the same problem, until it reaches a simple base case it can solve directly.

Think of it like Russian nesting dolls — each doll contains a smaller version of itself, until you reach the smallest one.

---

## Two Essential Parts

| Part | Purpose |
|------|---------|
| **Base Case** | Stops the recursion (prevents infinite loop) |
| **Recursive Case** | Breaks the problem into a smaller version |

---

## Simple Example: Countdown

```python
def countdown(n):
    # Base case — stop here
    if n == 0:
        print("Go!")
        return

    # Recursive case — call itself with a smaller value
    print(n)
    countdown(n - 1)  # ← calls itself

countdown(3)
```

**Output:**
```
3
2
1
Go!
```

---

## How It Executes Step by Step

```
countdown(3)
  → prints 3, calls countdown(2)
      → prints 2, calls countdown(1)
          → prints 1, calls countdown(0)
              → prints "Go!", returns   ✓ BASE CASE
```

---

## Classic Example: Factorial

```python
def factorial(n):
    if n == 0:          # base case
        return 1
    return n * factorial(n - 1)   # recursive case

print(factorial(4))  # → 24
```

**Why it works:**
```
factorial(4)
= 4 × factorial(3)
= 4 × 3 × factorial(2)
= 4 × 3 × 2 × factorial(1)
= 4 × 3 × 2 × 1 × factorial(0)
= 4 × 3 × 2 × 1 × 1
= 24
```

---

## ⚠️ Common Mistake: Missing Base Case

```python
def broken(n):
    print(n)
    broken(n - 1)  # never stops → stack overflow!
```

---

## When to Use Recursion

✅ **Good fit for:**
- Tree/folder traversal
- Sorting algorithms (merge sort)
- Problems naturally defined recursively (Fibonacci, factorials)

⚠️ **Be careful of:**
- Deep recursion causing stack overflow
- Repeated calculations (use memoization to fix)

---

**The key insight:** Trust that your function works for a smaller input, use that result to solve the current input, and define where to stop.
````

```json
[
  {
    "type": "message_start",
    "message": {
      "model": "claude-sonnet-4-6",
      "id": "msg_01JqufFVcarQ73V8GUn3XSSC",
      "type": "message",
      "role": "assistant",
      "content": [],
      "stop_reason": null,
      "stop_sequence": null,
      "stop_details": null,
      "usage": {
        "input_tokens": 19,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "cache_creation": {
          "ephemeral_5m_input_tokens": 0,
          "ephemeral_1h_input_tokens": 0
        },
        "output_tokens": 1,
        "service_tier": "standard",
        "inference_geo": "global"
      }
    }
  },
  {
    "type": "content_block_start",
    "index": 0,
    "content_block": {
      "type": "text",
      "text": ""
    }
  },
  "... 28 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting Claude use Anthropic's server-side web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-4.6',
  {
    max_tokens: 4096,
    messages: [
      {
        content:
          'What were the top news stories about Cloudflare this week? Summarise in three bullets.',
        role: 'user',
      },
    ],
    tools: [{ max_uses: 3, name: 'web_search', type: 'web_search_20250305' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-4.6",
  "max_tokens": 4096,
  "messages": [
    {
      "content": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
      "role": "user"
    }
  ],
  "tools": [
    {
      "max_uses": 3,
      "name": "web_search",
      "type": "web_search_20250305"
    }
  ]
}'
```

```
Here's a summary of the top Cloudflare news stories this week:

---

• **AI Agent Verification in Bot Management** —
```

```json
{
  "id": "msg_011aLAk6hWx3649oMeuJBm4w",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "server_tool_use",
      "id": "srvtoolu_017fsFRbkfUvtAZDtsdHQHpk",
      "name": "web_search",
      "input": {
        "query": "Cloudflare news June 2026"
      }
    },
    {
      "type": "web_search_tool_result",
      "tool_use_id": "srvtoolu_017fsFRbkfUvtAZDtsdHQHpk",
      "content": [
        {
          "type": "web_search_result",
          "title": "Cloudflare Release Notes - June 2026 Latest Updates - Releasebot",
          "url": "https://releasebot.io/updates/cloudflare",
          "encrypted_content": "EswgCioIEBgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDKsEJxlMa3qQO5JUqBoMFHieeMBm3CiIabVQIjAfi4M7ZSs5NHd7t5JTmrvM/Hf4BrDdFLHQNRjsKoMTfEdwgUt3WHqQUKElEQ3YSjYqzx9YqRMA+faNEhIbKT4P14UT03NEBVT7WCJyTdZpXJKQXE/7QDZrpJZb8aPvIFeJwIs+SZUiMN7M2CVLwElfhPhhWdAXT8o3asJn8/TNOPu4fU6X4vIPkff/gWW3Y8tDhZqXLFJbUrF57FnEsVpRpTyEa6znwLy+VY2MsjTtWYBesOGQlfFPPh+lZgVrcKRPAF5ii5C2IwsDhmm4nZ5esVCZcutrskWWx6rzLyPdVyUVWIVAaYqONAsKqwPu/L9SlhMcHGSppOGW0qYZOoUas+p9qxoOs6QvVyz8rWLc3cFrGmL75DxpJRSIThwHfj7/CPGV8c13VzcK3+pQsd4Y/MNhGpl+CDQtbfftz4bgNcTeXVWYR8kesHMD+EmXh/kpf9fkeGM4GiHMbtf5bFnJYvU00F03kedkErE3GCfBcot8A1zUW6wI1zaS7oCB14JsjR6fMqLvV8YLdXMICIz0pmiuUMtxyLmLZMPTQ0AkAqf7gnDD9FGMTR8EXRlYZBsf+FU4yQ8fQZCUyWqkr2xu3DZxmRcgFm1w3MLPNsk+gXonNVLSuK/iHny66aiOuRfeLB+I8UoeTT/UVaPnLc/Q8+V+TtYmeRFMcEB1u8+TFtG/xYBO00tmAKY8HyrjDChkd/ifHBkPCnWSQbGW3oNK2i44jWd5dXvsIaW44EkKCYO9IUG9uu/F97C50oKRP/5GC/TnTP+IqNhxCa1WCmPNoSRxXKcRVIctzr2mtEMt3Y9bIzLt1qq6tn1ysAzwxJ1ZfhixLcc+OtDDg9YRVeoSXi27mv91nWA8UwwJ2ez3hCI0KDCoE4iYjl143cNrxPLdINuTlKYUVwHznd7S7vsd/G/H73oPDm4CJ7Mw5WGSKk0DbxVKYZjWLycNkMI3YZIoFa4jmqwQlwMwS1K+2AjLkYUSp3yrGYu3/chw1ul6PU7KTo0YErwNAmGTgYba3r4G1luAQ3zhPWvFb9AOhsjd652ZkvdorSj+tDoVL+9HLeI3G5AsITzi0/gtHhSYKrDRFB6/A7+icwmY/tdfVTM3HwDuUd12/GYZ1uDM5yFOCj2TbMqa7P+r0hJkb+orA0erEa+/PZF8cKxc6UzYcKXTW9l73BGnZL5Erl4UL/5XYL+schG/8YVGVFAPYbBaNhu/VBxt4WibPQcwHL7KdkhyYotFwXXMhVJXnTacBoRQYWMP9HMl26LMKzN1cgVK21IuJ6slBQdTfgGrdeiODndURpEog9z/mb2RB3kbN+Fi5RH+iCwwmJyjSjH5P2TBuNeYIPtBy2dl6YSVGL+mddEHw8toulUguE6PfJF9eITwbQNxnMh+1ue2+iT7TX90Idy2qYJMRpkNsqAmAVD2LM9/m+HbQXJOEoGb7TlST3zUROkiWmuicO11stS8hSUQOpanKG1LMXgPcFfmfFtd122XAVpZVsSXNM2mLqbdxlMe07u16xEDNAnP+dtHWzDQ9HkEo4z71TbpNm4/GeimOo/gEiPG0WTu2ho1dtAuXibr34GCBmeo3wc/UdstjfGfEEVU11gUlzDd/D4mt7Lm8wfDyUkWQSYxs4hz8UNb0irLaO/8hIOKEzXWOdiCAN/fwHGTamTnAE/XG05z7XEzPFMpvXP69nHke7Dz5fj+OytwCpBOA7ZRua5ALPM9uPVnzMgTQJBPTSb+6hBkEHnqhahYJHyakcSh5tfUqmUdLU1QVxxGBEZgD9EU7Okxn1cXU7P7RMNdsYRIRna2PG5MFFKBgdGUA0uztHfqJD+kmq5fLCNVCl3C2I8XoyO43ChQsTbUXo/qyipH8SunOVMzrcoDZbJVckNXASslrak/icvOUioDk2HTV4bvd7IVbOWB3j0n/LJhRqsluy7oY84iykbvtX0YZ2rFaj7TMLuya97tAPQx5mchxbP0FZRp+mD+vYJ8KCAqyikB7GYZWnSWMkBzPKCuwob9g3XN5Rj0tmpEbjwVjfSv2NXRuX2rzA4SSPgGjSanyl/n3zhJTUyJFcHLJtETNGGfZXA74wuSaiSVzGhR8bB7PjnCKaUt/kiyTEcSRkGDdj6IhNNnn6NHFdjSxpXmPKrWmWMwxKyzRkL0RziupP6OS9rLwqBCGpmXZ2b+89ekll3IU6AKV9A17XZoFR39ZyPPzmOq8qK5mwTYgKrG+upuHifYLleLcarF/nIwryUSZSB9qwhe0CJuGtoBJB2VgS/lm9tofQDZVYJMkeJ2wn+U/enw2+v1DeU0pXe1OqhEstxZea0LeebsYplDq9nPTeor6YF6WPyJ+n4pYeYQ2kRMZh8RII0j8afHkxuDU8qKtHbbg+huv9FanbAaItj47/KfhuMBUGl3AUeNPerTf/6PSTt3f1IjZHLiVg9ZSkc8lYEfjqBIy2hPVVs/nxa8cVNj3vefnHQXOQbbRUQ/JrOFAbcsgduB9GVD95UhSlRFzdyL0J+JGj84BDIsqChjXc5MjXvRIyfysyHvhE9/wQCr/fHqkbvDPruhQE/Y9vQ2+LPTHyo5rbszwWf/iT+bafegReqS8FkbM4afP9cISrpOX8lqY5ToTuixMK3FVGXL6ulvuQz5iUBPDxv9b0PFdqKJMXp82g8p/1d0oX8Sjc0tVyDJ5FbOS5zmDBxHxPIobHlNOFOZPfofaJTd2amabEu+TWPc5dVSBGuRUDthIQrP9yxKW/dydDmMg1/E58GOs7nSbwLVKPjQphmb3Nrc8c15l8Ybi90yo4308v47UsbaSfq1dAUdoH5AG+KW0KYH1HF5BzAcq4QCFYvdchHR7Oi+z7alxi4b8w55vNZcJt7kz1OensDnL8+No8y4WR/oIAzbTVWqum/zaWZ2WYXmdJipWFgCzQw55G37jL1T0Kbi03Cv+A8jL/hmwhmeztEoVr2ZPm3XsMl4UeK+VTmlOe6uaEBP5YDCz27HiXUGam4frntBGux6y/BGBlphzDyMBnvHYGaN0DTbMcb5wm9M/4b7y75xye6QnKInWxMrkBJ8H1tKhDWRzbpAvGzH3bvpWun+jCI99q3JimBsHWJVwom7JaxgfE3LhJQhVKPP+cnHUzbNeu/a5FV4p08phrE7BEOxAj6fOl15lGZmh2qRxvtNRGcj0l3LV/BeQjOU8UCOur1F5bP4QX225+N842aKMNfma+/F4M6FgWTSXFIXCEL15FiSviukZE9pjHi7H3DjGu7O4pkm1WZJEpCyY5+bjnOspXJhsqCrzdTqNpOEGXU8coaxZcnQ6K27H6oGRYAEt+N07eLMoaHkl+U0/RTpeItjeXED8r6YbFkZIkfvGdu0379sf4UyVr2xsqN43FxrQXLg9pfxCnh+oGNLsqAERKFnbfxVsowEzF6GYroC8HQmBEALdOoIQxxXYul8shSAIiaWx0dwLuiKxEOFEWAVMDjfkBqORoMqzzpx06lUktlS0oSonOfzZeR30h+MchXf10yxTUupR9/5EMSxmY8LVSReJ2TjEeY8LWm4zQHvmXr4ZurVrQOfSq8zeCUVOiBoTsLPXFUzm2pBiRUjb8NNRVoWQ0Q83WC6J7nb5pzXAqj3bdXiOp1pzau227dtRfXvxRNhSUIGRdi6viW1OJyCVdmemhUlJr3MZuv9lzaV8hm0KnlAYl/Cq+V7mZda3d/9GBhJUhZzTtJpEnnTfcCJRQGh/GXZGI3XCDhOG0npG4/EGBey9b0lvbsdTnH83mO2Bj0ct7yzxXBIVrSDX/dYQqG2qwfu34bcQEp4y/bm6g19f/NIh05FOMwcEv9ORXAtDG4DHzQNf858dhossBSW4JTHm2/LgPgHDasn02KwjAA1Yt1dfecnVeFk0rqDlwDUeYp1B9zI1bBrHwkEXTkhDqw7PKr9SAdj01AXrK0V0Dij3IfEtZ3vyKwe0NUE5iHvgDpGehGdXhpFMwKVQOSx2qQ6NaYANz7eahgoSl1iHz0se+SEQcT579dfSZsBT2xMrTg+JxVzGD41rPcAgY/yX1EE8rFFpekYebB+ZvZ0D+gmyNUs07Kzf5yTCP4CiFM2ABU2DssjbMpvh9awJyVGrj61XOiVuQ6VI4YBDPtE8V4kP2iLIgwHqeNhFQRCJL60UOPTioXrncUvGOzRmMG72zFv1Pi9hfgk9JnHAARg76zVLJkaFPaNCyTY582VuWe6eFHn/wDa0SpuOIq+EmaJoLqv5rbIrYJ5Izb++Twsq1hPpwvFYgSMHuTBeWBTFCiYl+Nyhe89xDy/ObKK+IDOcfrus0/Tjj2NGfWZfgahTQAR29afNPgS/ONJWZ8EcgraV5FlOGt64iki0V9vASm3g5tEpFlUn3K0jjeNAdeV3yDpXcAKTPFQ4+HWCoTQPJTm9Q6/T5vLBD5VppU5RGTEsp/ZrrvFHUJGtQFUB/GO75sUABvT1+AA+1R4oHrhRXdgYArirlTQMIjLSCc5i53qdwS8NB/2UyUWvNPq0HAN/T+Nb7/G67Xf0+LzIjjZY6kRKY6hRmLy7SzvWMMhVsDecDQRUI+cUJ/NDDriMlF0rv1KkbVncqit9xsbeZfakGEU7Ac3tPmrdjjTM8FKEkvrw77RnxGFONhghSz6Lz+FhYcOkDAW314OUl9coLo9ycH5yjmqgXS++4+E/0ZkiBNgr2Hgt/cX3VW7QTzowz0L+Skgq8k+tNZZAwTa6uJMpBlfK1HdHVssZAnp1js4xwtN9qUWtcRn4y8MoUUuWZIAU6dap5n1fxL0RoR1XWjTb9lMwPH5D+wvkdxMa//7Uwwrf8hAJB1oq/6xmXx8BbBh+LPEEu+wpQ3prmNDav1K9XKzHcahvnZ7UD38LKvZIeBupb+FIj9idSU+sYNUR001dmaHBlKzErxW9JwOemYFhQ1/JF698dIpUkwbIb5U74Pi4u5z1EORI9G/NUFC9W+yRJuca38QghmnlNfv6Q4NPFaOMboOzyFZ88gLbD0Nf3Brr6njXH2Z7OAqE8zZHutpbtwAyRPm84ng9hPGX2fbnFO+xhTX/9MIxv66mL4dkJpGZBS2VBjaNJX/rNv9CxbO6vzMxT8AaYO3xmmUBIUwSKNSsNOr0PeaHkG+xVSsrSwbJio7+aLaiNE7ouV43PheAiNQnWvIIATcgRvS1/Cjy08QGv8qYQ+fF/4M+BjPPu3vclnZqbUcPj9eYlHKEBPmKq/X6OcPMswY/ttnI0UMT0F1vGj6Fn0EmeG8mwfkD+toWBiCPND6PeydyswoVrLhFbT/eRK2vD6UZ/JOiSX4/I820l3LykHF0d/2czYlHy1mFo1N6bBQ908x0lj1eeMfGFhHhBGlrWg+Ips1D1zQBytO8DxLWfIzu2yhYckPJgHet7SovioK5yMq4RWLtE2bk+oSTRalJ+15YNWCK3LEjuGHEFOjP7iWzCRVZbJ4gA0UZATud5C0TuDuAQ1gkIEYAw==",
          "page_age": "2 days ago"
        },
        {
          "type": "web_search_result",
          "title": "Press Overview | Cloudflare",
          "url": "https://www.cloudflare.com/press/press-releases/",
          "encrypted_content": "EvMCCioIEBgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDCch0SONkciDkIjZyBoMkaSPWo3PaVWy00JBIjDLEt1nqEXoy8JuNkVrddRulYfFkaynmdMj81PTz0pFdNp1JPzH2ivOUIULTwUEnTcq9gHOoLsuFECd+94wuNXYT3y5mDi4JwIF6cgad1D5l1/XcU+IlGgv81XpGKA5mI1bkG8ra1enXlkazfHxp5tRYVKEhAIxK4TZqzxANK0TMXpVIT6HXY6g02RHaguLV01oP59VZ9bcesPf4vju8lNkfcVS/3gi2taiKViTgb5NUzKMmuSdqdmATzHmnPbmTxeTQmvmHYayBxRYCWasF7CyGHeWAYb6VF9c9uPmgOQaNJHotZRlupWt32iJhjuYq2F8JvWLkMvTwzOIRC7q0J5VpRGK/KboVxwkpqN5mQPo1IUcLvcusTdCxr6YaZmbxGZvD+sdbB+0O00YAw==",
          "page_age": null
        },
        {
          "type": "web_search_result",
          "title": "Cloudflare News | June, 2026 (STARTUP EDITION)",
          "url": "https://blog.mean.ceo/cloudflare-news-june-2026/",
          "encrypted_content": "EvsgCioIEBgCIiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDN26YfZgx/3x0lmOBRoMzq0xt+da8XlijBmDIjB608J6yuZ/UpIKBQOUMOlaVHOlbjbRNbgjzTg0h8xL4genq6mxH+csLIh9yqSzEE0q/h+JhNm+c6ZKmYIENTMAvFBsmTolxan/ZL9gXPkkEnqR+8aIIWUr/r9UropurUX8aH/gCUD0Fu8YDz/rRTHZtNEfg/HSNLV/vDBsOWSAY/A+OxF0jC6imZtDUBxi4rYZX3Fn6rECrY4jK9TEoZMQPIwAfqfc3w8laAdzkwcrHgNHIWmum1aHtV/Rd6ISvJHThsbiXa5URNOVkqFaCJ68hu5UX7e3a4+5OHKw+x3HLJ5gynP3cA6eKlVerDuePP+ukD2MUppA0jZY1tyd5CEdwsIxfs9qPwjvUP+dar9tuOSnD4Jn0itbndLANq68v/nNKohRmvKn2GZOjDDBzYu4AF+E0bKF+2DfHxWq0BlJsXB8cWI3aZ2YcafpwwQPcmR0EpJnzQ4YX/9IAYE9r5OwDxzOaXzYhMsgl4lYPQSaLxdm1pHiSvJN91QWaXGuNRUlpU/fIUDsNMw9NmrSBHQ2nH1vvNJCwuTpfrppkD1bosFVwLG73xYymVr2Zbj+K0Qyb+MXJw8Dbwd9jvkpu6JA/sbPTonMYvRI50NrRrsWN/2KjnpsrKwUq1AsTd6D/f+mnseiI7FJEGYralzKn64IdY0CP
... response truncated ...
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

temperature

`number`minimum: 0maximum: 1

top\_p

`number`minimum: 0maximum: 1

top\_k

`number`exclusiveMinimum: 0

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.6/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.6/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.6/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.6/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.6/#page","headline":"Claude Sonnet 4.6","description":"Claude Sonnet 4.6 is Anthropic's latest balanced model offering strong coding, reasoning, and agentic capabilities with improved instruction following.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-4.6/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Sonnet 5 is Anthropic's most agentic Sonnet model yet, built for coding, tool use, reasoning, and long-horizon professional work at lower cost than Opus-class models.
title: Claude Sonnet 5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Sonnet 5

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-sonnet-5`

- Third-party

Claude Sonnet 5 is Anthropic's most agentic Sonnet model yet, built for coding, tool use, reasoning, and long-horizon professional work at lower cost than Opus-class models.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://www.anthropic.com/claude/sonnet) |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Output (per 1M tokens)$10.00</li><li>Cached input (per 1M tokens)$0.20</li><li>Cache creation (per 1M tokens)$2.50</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-5',
  {
    max_tokens: 1024,
    messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
# The Three (Four) Laws of Thermodynamics

Here are the fundamental laws, typically numbered 1-3 (with a "Zeroth Law" often included as foundational):

## Zeroth Law
**If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.**
- This establishes the concept of temperature as a measurable property.

## First Law (Conservation of Energy)
**Energy cannot be created or destroyed, only transformed or transferred.**
- Often expressed as: ΔU = Q − W
- (Change in internal energy = Heat added − Work done by the system)
- This means the total energy of an isolated system remains constant.

## Second Law (Entropy)
**The total entropy of an isolated system can never decrease over time; it tends to increase or remain constant.**
- Heat flows spontaneously from hot to cold objects, not the reverse.
- This law explains why certain processes are irreversible and establishes the "arrow of time."
- No heat engine can be 100% efficient at converting heat into work.

## Third Law
**As the temperature of a system approaches absolute zero (0 Kelvin), the entropy of the system approaches a minimum (constant) value.**
- Absolute zero is unattainable in a finite number of steps.
- At absolute zero, a perfect crystal would have exactly zero entropy.

---

**Quick summary often used colloquially:**
1. You can't win (can't get more energy out than you put in)
2. You can't break even (some energy is always lost as unusable heat)
3. You can't get out of the game (can't reach absolute zero)
```

```json
{
  "id": "msg_01RdqxfAYz2PfZTfiAYpX6Tz",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "# The Three (Four) Laws of Thermodynamics\n\nHere are the fundamental laws, typically numbered 1-3 (with a \"Zeroth Law\" often included as foundational):\n\n## Zeroth Law\n**If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.**\n- This establishes the concept of temperature as a measurable property.\n\n## First Law (Conservation of Energy)\n**Energy cannot be created or destroyed, only transformed or transferred.**\n- Often expressed as: ΔU = Q − W\n- (Change in internal energy = Heat added − Work done by the system)\n- This means the total energy of an isolated system remains constant.\n\n## Second Law (Entropy)\n**The total entropy of an isolated system can never decrease over time; it tends to increase or remain constant.**\n- Heat flows spontaneously from hot to cold objects, not the reverse.\n- This law explains why certain processes are irreversible and establishes the \"arrow of time.\"\n- No heat engine can be 100% efficient at converting heat into work.\n\n## Third Law\n**As the temperature of a system approaches absolute zero (0 Kelvin), the entropy of the system approaches a minimum (constant) value.**\n- Absolute zero is unattainable in a finite number of steps.\n- At absolute zero, a perfect crystal would have exactly zero entropy.\n\n---\n\n**Quick summary often used colloquially:**\n1. You can't win (can't get more energy out than you put in)\n2. You can't break even (some energy is always lost as unusable heat)\n3. You can't get out of the game (can't reach absolute zero)"
    }
  ],
  "model": "claude-sonnet-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 20,
    "output_tokens": 539
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-5',
  {
    max_tokens: 1024,
    messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
    system: 'You are a helpful coding assistant specializing in Python.',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "How do I read a JSON file in Python?",
      "role": "user"
    }
  ],
  "system": "You are a helpful coding assistant specializing in Python."
}'
```

````
# Reading a JSON File in Python

Python's built-in `json` module makes this straightforward.

## Basic Example

```python
import json

with open('data.json', 'r') as file:
    data = json.load(file)

print(data)
```

## Explanation

- **`json.load(file)`** — reads from a file object and parses JSON into Python objects
- **`json.loads(string)`** — use this instead if you have a JSON *string* (not a file) to parse

## Example with Sample Data

Suppose `data.json` contains:

```json
{
    "name": "Alice",
    "age": 30,
    "skills": ["Python", "SQL"]
}
```

You can read and use it like this:

```python
import json

with open('data.json', 'r') as file:
    data = json.load(file)

print(data['name'])      # Alice
print(data['skills'])    # ['Python', 'SQL']
```

## Handling Errors

It's good practice to handle common issues like missing files or invalid JSON:

```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found.")
except json.JSONDecodeError:
    print("Invalid JSON format.")
```

## Reading JSON from a String

If your JSON is already a string in memory:

```python
import json

json_string = '{"name": "Bob", "age": 25}'
data = json.loads(json_string)
print(data['name'])  # Bob
```

## Key Type Mappings

| JSON Type | Python Type |
|-----------|-------------|
| object    | dict        |
| array     | list        |
| string    | str         |
| number    | int / float |
| true/false| bool        |
| null      | None        |

That covers the essentials — let me know if you need help with nested data, writing JSON, or working with large files.
````

```json
{
  "id": "msg_01PptUvPAdU3SPQLQPwG7G3s",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "# Reading a JSON File in Python\n\nPython's built-in `json` module makes this straightforward.\n\n## Basic Example\n\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n## Explanation\n\n- **`json.load(file)`** — reads from a file object and parses JSON into Python objects\n- **`json.loads(string)`** — use this instead if you have a JSON *string* (not a file) to parse\n\n## Example with Sample Data\n\nSuppose `data.json` contains:\n\n```json\n{\n    \"name\": \"Alice\",\n    \"age\": 30,\n    \"skills\": [\"Python\", \"SQL\"]\n}\n```\n\nYou can read and use it like this:\n\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data['name'])      # Alice\nprint(data['skills'])    # ['Python', 'SQL']\n```\n\n## Handling Errors\n\nIt's good practice to handle common issues like missing files or invalid JSON:\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r') as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"File not found.\")\nexcept json.JSONDecodeError:\n    print(\"Invalid JSON format.\")\n```\n\n## Reading JSON from a String\n\nIf your JSON is already a string in memory:\n\n```python\nimport json\n\njson_string = '{\"name\": \"Bob\", \"age\": 25}'\ndata = json.loads(json_string)\nprint(data['name'])  # Bob\n```\n\n## Key Type Mappings\n\n| JSON Type | Python Type |\n|-----------|-------------|\n| object    | dict        |\n| array     | list        |\n| string    | str         |\n| number    | int / float |\n| true/false| bool        |\n| null      | None        |\n\nThat covers the essentials — let me know if you need help with nested data, writing JSON, or working with large files."
    }
  ],
  "model": "claude-sonnet-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 38,
    "output_tokens": 609
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Creative Writing with High Effort** — Use adaptive thinking with high effort for deeper reasoning.</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-5',
  {
    max_tokens: 2048,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    output_config: { effort: 'high' },
    thinking: { type: 'adaptive' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-5",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "output_config": {
    "effort": "high"
  },
  "thinking": {
    "type": "adaptive"
  }
}'
```

```
Detective Mara Voss crouched beside the overturned chair, careful not to let her coat brush the chalk outline still drying on the hardwood floor. The apartment smelled of lavender and something underneath it—copper, sharp and unmistakable.

"You seeing this?" she called to her partner, Reyes, who was photographing the bookshelf.

He crossed the room, careful of the evidence markers scattered like yellow teeth across the carpet. Mara pointed at the small object resting in the dead man's open palm: a single playing card, the seven of diamonds, except where the diamonds should have been, someone had drawn seven tiny, perfect spirals in red ink.

"Could be nothing," Reyes said, though his voice suggested he didn't believe it.

"Could be." Mara pulled an evidence bag from her pocket but didn't reach for the card yet. Something about it held her still. The spirals weren't random—she'd seen that pattern before, scratched into the doorframe of a cold case file she'd inherited three years ago. A case that had never made sense, that had kept her awake on more nights than she cared to admit.

"Mara?"

She blinked, realized she'd been staring. "This isn't our first body with this signature," she said quietly. "I just didn't know there'd be a second."

Outside, rain began to tap against the window, and somewhere in the building, a door clicked shut—soft, deliberate, like someone had been listening.
```

```json
{
  "id": "msg_01DACMFVHe3JbaQREntjsDuc",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Detective Mara Voss crouched beside the overturned chair, careful not to let her coat brush the chalk outline still drying on the hardwood floor. The apartment smelled of lavender and something underneath it—copper, sharp and unmistakable.\n\n\"You seeing this?\" she called to her partner, Reyes, who was photographing the bookshelf.\n\nHe crossed the room, careful of the evidence markers scattered like yellow teeth across the carpet. Mara pointed at the small object resting in the dead man's open palm: a single playing card, the seven of diamonds, except where the diamonds should have been, someone had drawn seven tiny, perfect spirals in red ink.\n\n\"Could be nothing,\" Reyes said, though his voice suggested he didn't believe it.\n\n\"Could be.\" Mara pulled an evidence bag from her pocket but didn't reach for the card yet. Something about it held her still. The spirals weren't random—she'd seen that pattern before, scratched into the doorframe of a cold case file she'd inherited three years ago. A case that had never made sense, that had kept her awake on more nights than she cared to admit.\n\n\"Mara?\"\n\nShe blinked, realized she'd been staring. \"This isn't our first body with this signature,\" she said quietly. \"I just didn't know there'd be a second.\"\n\nOutside, rain began to tap against the window, and somewhere in the building, a door clicked shut—soft, deliberate, like someone had been listening."
    }
  ],
  "model": "claude-sonnet-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 26,
    "output_tokens": 469
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-5',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
# Recursion

**Recursion** is a programming technique where a function calls itself to solve a problem by breaking it down into smaller, similar subproblems.

## Key Components

Every recursive function needs:
1. **Base case** – a condition that stops the recursion (prevents infinite loops)
2. **Recursive case** – where the function calls itself with a smaller/simpler input

## Simple Example: Factorial

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

Mathematically: `5! = 5 × 4 × 3 × 2 × 1 = 120`

This can be defined recursively as:
```
n! = n × (n-1)!
0! = 1  (base case)
```

### Code Example (Python)

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

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

### How It Works (Step-by-Step)

```
factorial(5)
= 5 * factorial(4)
= 5 * (4 * factorial(3))
= 5 * (4 * (3 * factorial(2)))
= 5 * (4 * (3 * (2 * factorial(1))))
= 5 * (4 * (3 * (2 * (1 * factorial(0)))))
= 5 * (4 * (3 * (2 * (1 * 1))))
= 120
```

The function keeps calling itself with smaller values until it hits the **base case** (`n == 0`), then the results "unwind" back up, multiplying together to produce the final answer.

## Why Use Recursion?

- Makes code **cleaner** for problems that are naturally recursive (trees, fractals, divide-and-conquer algorithms)
- Mirrors **mathematical definitions** closely
- Useful for problems like: tree traversal, sorting algorithms (quicksort, mergesort), the Fibonacci sequence, and navigating file systems

## Caution ⚠️
Without a proper base case, recursion leads to **infinite recursion** and a stack overflow error!
````

```json
[
  {
    "type": "message_start",
    "message": {
      "model": "claude-sonnet-5",
      "id": "msg_0188koTEnwXJD4cbqRcEfaCT",
      "type": "message",
      "role": "assistant",
      "content": [],
      "stop_reason": null,
      "stop_sequence": null,
      "stop_details": null,
      "usage": {
        "input_tokens": 22,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "cache_creation": {
          "ephemeral_5m_input_tokens": 0,
          "ephemeral_1h_input_tokens": 0
        },
        "output_tokens": 6,
        "service_tier": "standard",
        "inference_geo": "global"
      }
    }
  },
  {
    "type": "content_block_start",
    "index": 0,
    "content_block": {
      "type": "text",
      "text": ""
    }
  },
  "... 20 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5/#page","headline":"Claude Sonnet 5","description":"Claude Sonnet 5 is Anthropic's most agentic Sonnet model yet, built for coding, tool use, reasoning, and long-horizon professional work at lower cost than Opus-class models.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Claude Sonnet 5.5 offers the best combination of speed and intelligence, with adaptive thinking for coding, tool use, reasoning, and long-horizon work.
title: Claude Sonnet 5.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Anthropic logo](https://developers.cloudflare.com/_astro/anthropic.DbRqBIjP.svg)

# Claude Sonnet 5.5

Text Generation • Anthropic

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`anthropic/claude-sonnet-5.5`

- Third-party

Claude Sonnet 5.5 offers the best combination of speed and intelligence, with adaptive thinking for coding, tool use, reasoning, and long-horizon work.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://www.anthropic.com/legal/commercial-terms) |
| More information | [link ↗](https://platform.claude.com/docs/en/models/sonnet-5-5/overview) |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Cached input (per 1M tokens)$0.20</li><li>Cache creation (per 1M tokens)$2.50</li><li>Output (per 1M tokens)$10.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-5.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain why database indexes improve lookup performance.', role: 'user' }],
    system: 'You are a concise database engineering tutor. Include one concrete example.',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-5.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain why database indexes improve lookup performance.",
      "role": "user"
    }
  ],
  "system": "You are a concise database engineering tutor. Include one concrete example."
}'
```

````
**Core idea:** An index is a separate, sorted data structure (usually a B-tree) that lets the database find rows without scanning the entire table.

**Without an index:** To find a row, the database does a *full table scan*, checking every row. Cost grows linearly: O(n).

**With an index:** The database navigates a balanced tree. Each step eliminates a large fraction of the remaining data, so lookup cost is O(log n). Because B-tree nodes hold hundreds of keys, even huge tables are typically only 3–4 levels deep, meaning just a few disk/page reads.

**Analogy:** It's like a book's index. Instead of reading every page to find "photosynthesis," you look it up alphabetically and jump straight to the page.

**Concrete example**

```sql
CREATE TABLE users (
  id INT PRIMARY KEY,
  email VARCHAR(255),
  name VARCHAR(100)
);
-- Assume 10 million rows

SELECT * FROM users WHERE email = 'ana@example.com';
```

- **No index on `email`:** The database reads all 10,000,000 rows to find matches. This may take seconds.
- **After indexing:**
  ```sql
  CREATE INDEX idx_users_email ON users(email);
  ```
  The database traverses the B-tree on `email` (~3–4 page reads), finds a pointer to the matching row, and fetches it directly. This typically takes milliseconds.

You can verify this with `EXPLAIN`: you'll see a `Seq Scan` / `type: ALL` before, and an `Index Scan` / `type: ref` after.

**Why it works, in short**
1. Keys are stored **sorted**, enabling binary-search-like navigation.
2. The tree is **shallow and wide**, minimizing expensive disk I/O.
3. Leaf entries **point directly** to the row location.

**Tradeoffs:** Indexes consume extra storage and slow down `INSERT`/`UPDATE`/`DELETE`, since the index must be kept in sync. Index columns you frequently filter, join, or sort on, not everything.
````

```json
{
  "model": "claude-sonnet-5-5",
  "id": "msg_011CfWPzXNFbhjzHxLnrjPAs",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "**Core idea:** An index is a separate, sorted data structure (usually a B-tree) that lets the database find rows without scanning the entire table.\n\n**Without an index:** To find a row, the database does a *full table scan*, checking every row. Cost grows linearly: O(n).\n\n**With an index:** The database navigates a balanced tree. Each step eliminates a large fraction of the remaining data, so lookup cost is O(log n). Because B-tree nodes hold hundreds of keys, even huge tables are typically only 3–4 levels deep, meaning just a few disk/page reads.\n\n**Analogy:** It's like a book's index. Instead of reading every page to find \"photosynthesis,\" you look it up alphabetically and jump straight to the page.\n\n**Concrete example**\n\n```sql\nCREATE TABLE users (\n  id INT PRIMARY KEY,\n  email VARCHAR(255),\n  name VARCHAR(100)\n);\n-- Assume 10 million rows\n\nSELECT * FROM users WHERE email = 'ana@example.com';\n```\n\n- **No index on `email`:** The database reads all 10,000,000 rows to find matches. This may take seconds.\n- **After indexing:**\n  ```sql\n  CREATE INDEX idx_users_email ON users(email);\n  ```\n  The database traverses the B-tree on `email` (~3–4 page reads), finds a pointer to the matching row, and fetches it directly. This typically takes milliseconds.\n\nYou can verify this with `EXPLAIN`: you'll see a `Seq Scan` / `type: ALL` before, and an `Index Scan` / `type: ref` after.\n\n**Why it works, in short**\n1. Keys are stored **sorted**, enabling binary-search-like navigation.\n2. The tree is **shallow and wide**, minimizing expensive disk I/O.\n3. Leaf entries **point directly** to the row location.\n\n**Tradeoffs:** Indexes consume extra storage and slow down `INSERT`/`UPDATE`/`DELETE`, since the index must be kept in sync. Index columns you frequently filter, join, or sort on, not everything."
    }
  ],
  "container": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "stop_details": null,
  "usage": {
    "input_tokens": 46,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0,
    "cache_creation": {
      "ephemeral_5m_input_tokens": 0,
      "ephemeral_1h_input_tokens": 0
    },
    "output_tokens": 705,
    "output_tokens_details": {
      "thinking_tokens": 0
    },
    "service_tier": "standard",
    "inference_geo": "global"
  },
  "diagnostics": null
}
```

## Examples

<details>

<summary>**Adaptive Reasoning** — Use adaptive thinking with high effort for a multi-step reasoning task.</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-5.5',
  {
    max_tokens: 2048,
    messages: [
      {
        content:
          'A service processes 120 jobs per minute. Each retry adds 15% more work, and 8% of jobs retry once. What is the expected number of jobs processed per minute including retries? Show the calculation.',
        role: 'user',
      },
    ],
    output_config: { effort: 'high' },
    thinking: { type: 'adaptive' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-5.5",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "A service processes 120 jobs per minute. Each retry adds 15% more work, and 8% of jobs retry once. What is the expected number of jobs processed per minute including retries? Show the calculation.",
      "role": "user"
    }
  ],
  "output_config": {
    "effort": "high"
  },
  "thinking": {
    "type": "adaptive"
  }
}'
```

```
**Assumptions:** 120 jobs/min is the base load. 8% of jobs are retried exactly once. Each retry costs 15% more work than the original run, so it counts as 1.15 job-equivalents.

**Calculation**

1. Jobs retried per minute: 120 × 0.08 = 9.6
2. Work from retries: 9.6 × 1.15 = 11.04 job-equivalents
3. Total: 120 + 11.04 = **131.04 job-equivalents per minute**

That is about 9.2% more load than the base 120.

**Alternative reading:** If you only want the number of executions and each retry counts as one ordinary job, the total is 120 + 9.6 = **129.6 jobs per minute**. The 15% extra work then doesn't enter the count.

The first figure (131.04) is the better estimate of capacity needed, since it reflects the heavier cost of retries.
```

```json
{
  "model": "claude-sonnet-5-5",
  "id": "msg_011CfWPzyhH6mWkQYYXi8zC5",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAQS4QsKEAgSGAI4AUIIdGhpbmtpbmcSDIyPKkWDs4DDWbwLjhoMULVI2ZKBdAfPRMzJIjBaQeA2k0JVmckUM9/CZLdkbCXCRqHa3Z/rAeK4cch4pTAAYCHzFN7yJHpVGkxR4z0q/gqV23QphHBITa0aV3BNaMrVHxDxzaVL1pa64TreQVS+dsZkvxAZHf6vv+HMX9afqKKaq9SbpkbdktuNsnLFCQ/FHHrlEpL1y5lXHPDEbk1wyxwT4j4EWuViMr+GLlAnZOvY4dFWhk4JsOYZxNNUQgWR1zEyeNVtA3GahFUzdo03ptlfTpI5a4L9gFbsX0qGS4QmuMJYf5ksgZcGxmCfu+27AyHs8/oRhAm9O0Ob3N3Say2Xw4wOywKFBYUVRS9yfrB7XbAclB8Dwn3aNQ6WM8N9e3HZgPllitAnCXTRu0kgaaDMFv1uoErPq5ttcYgkGoXar15VsF7xHoMrwQAUAUR2gtEuzEnvdEgTGnt6MKqt6A4LekKQD+jRLQ0IXSuiOaDafRJMoVVKdIBhHT0wSblQnvPIWsx+dMf+plo62zs3kJyP3KqpIjkpzgiZAWLAPumAxod9MAyRPT0UFFyIsv3suEUmGeKgmh4ytzfTjwbZ3+ploNhE2lCbsqvaed2OmxSQneCfg2DqBMTMONL+a7b3I9z7/bQOiGSGteWBlFpqerlJWa9N13MYvWD6SrFPB3r1AjR2d4cLo49v/LO5KKZhuumWHlgYiP8pfHJa9fZoHNe5KZnMdZxz2WURSSOECX68dIn8xvwx+LEtDmE1C1O8RwiDHIjrTZQgVjhCfK4IUqZspdiO+lu8Kfx8vvdjaeQZ3aRopB3j4AyCUtXPlw+ifKy4Ab9JqAsIsLriVJ9Y3Ow495ekt9wQYfwIIQrq5QtKBToq6XKsMaUoFVozIIgkKKlZp4uYDrVcRkyiiRujHzlWkC4Dt5PNULayg8ob9y08FL+H1fxZXtK3uff/jfZx0QFnBglaRSpxsGksP/jzDFOpmdjquwrM15zt3ePWi36aNgU41YBcpo6J1OlMfGR6qRIv6a2pgz+RgkSmCTiacTe4LrPRWtEb3H22GjpzU+kLFfI0MYn1sudTsiC4uveoGs/Ad8+iDz7vv/c9X48IwrBeudACYTNd0l2g2pSdiQ2dKVs48XDS0VxOxBlNUuOw4+sMEXMWz9mDPNNPUJgU2T6Lxva5jEOCfeJ58fDUVfcINsSSQz0fVVdUbBWUGFovTWPUGYf0h+unTn/PN5FrKOYj5P103kx2QK2GogrNMwIsfLJXIbYvqfdQ9xAJt/SEM+xa43YsQ9F2TdJAV1iwru9rN/iVE4evlFpE8Hvwf/ct3Gu0v/cRBiTQggkURXT/pc5/3mV3JTKp7BVWOAU75DdIOsnFt1FoF0aAZXzAWDib7EjflXl3/1WPxVdQ6ILSpyfb5SEOUJZ+DB5O6n5Gp+V+j5Fxtdw5tk83/uQGg1s7sJwDqMuwb92W8FKLxXTEnEgFH0CrT62j2HBxkN9vyVwNkv2XP+IzkNbpPJTBzTtR8yjajleIkCW8dZM0Ewhb7LVQerXBq4UwrEY4Pbc6NdcVuZ8iPl6LKyFv9bW3fG7QcdOAvgZGmL1J6BGgjnmIHhkUjg0S1llyXWWmTQD1iMQKu2C1YCwrzAUQRES4MBfnvDg72GOkiwet/d7zBMC6iH/HJvBlHmxiSOa6ikyMIYR4HbRuLJVhlYREwbz/wRRbM5n7apTDfIhyRdvxb5C3XcCdvun4Ypepluup0Ov7okW+CTzFlAY6fb15cpIE9MSkNCt7loEqBgQju81uqxDPXo62vBnwly3XJ1pxHaZFjpnWhREF2vppJ4rVTWTE/AuyJWRT8PIClzjWjp8kda0cupWZi8XTYnnWpsa0rYgy7osGC1QslgbGpx5GMJ8taKkORVJ8waAgJDpvvSQtDsw3+iec6ZtvCvMdvKQBa7OFEEQe0ZwMR5nC0dcnhshuhQOnZFNw2xFVY8mIaWaEHhgB"
    },
    {
      "type": "text",
      "text": "**Assumptions:** 120 jobs/min is the base load. 8% of jobs are retried exactly once. Each retry costs 15% more work than the original run, so it counts as 1.15 job-equivalents.\n\n**Calculation**\n\n1. Jobs retried per minute: 120 × 0.08 = 9.6\n2. Work from retries: 9.6 × 1.15 = 11.04 job-equivalents\n3. Total: 120 + 11.04 = **131.04 job-equivalents per minute**\n\nThat is about 9.2% more load than the base 120.\n\n**Alternative reading:** If you only want the number of executions and each retry counts as one ordinary job, the total is 120 + 9.6 = **129.6 jobs per minute**. The 15% extra work then doesn't enter the count.\n\nThe first figure (131.04) is the better estimate of capacity needed, since it reflects the heavier cost of retries."
    }
  ],
  "container": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "stop_details": null,
  "usage": {
    "input_tokens": 72,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0,
    "cache_creation": {
      "ephemeral_5m_input_tokens": 0,
      "ephemeral_1h_input_tokens": 0
    },
    "output_tokens": 667,
    "output_tokens_details": {
      "thinking_tokens": 368
    },
    "service_tier": "standard",
    "inference_geo": "global"
  },
  "diagnostics": null
}
```

</details>

<details>

<summary>**Tool Use** — Ask the model to select and call a tool when it needs structured external information.</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-5.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'What is the weather in San Francisco right now?', role: 'user' }],
    tools: [
      {
        description: 'Get the current weather for a city.',
        input_schema: {
          properties: { city: { type: 'string' } },
          required: ['city'],
          type: 'object',
        },
        name: 'get_weather',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-5.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What is the weather in San Francisco right now?",
      "role": "user"
    }
  ],
  "tools": [
    {
      "description": "Get the current weather for a city.",
      "input_schema": {
        "properties": {
          "city": {
            "type": "string"
          }
        },
        "required": [
          "city"
        ],
        "type": "object"
      },
      "name": "get_weather"
    }
  ]
}'
```

</details>

<details>

<summary>**Streaming Checklist** — Enable streaming for incremental response delivery.</summary>



```ts
const response = await env.AI.run(
  'anthropic/claude-sonnet-5.5',
  {
    max_tokens: 1024,
    messages: [
      { content: 'Write a short three-step checklist for reviewing a pull request.', role: 'user' },
    ],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-sonnet-5.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Write a short three-step checklist for reviewing a pull request.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

```
# Pull Request Review Checklist

1. **Understand the intent**
   - Read the PR description and linked issue.
   - Confirm the change solves the stated problem and stays within scope.

2. **Review the code**
   - Check for correctness, edge cases, and potential bugs.
   - Look for clarity, consistency with existing conventions, and unnecessary complexity.
   - Watch for security, performance, or backward-compatibility concerns.

3. **Verify quality and give feedback**
   - Confirm tests exist, are meaningful, and pass in CI.
   - Check that docs or comments are updated where needed.
   - Leave clear, constructive comments, distinguishing blocking issues from optional suggestions, then approve or request changes.
```

```json
[
  {
    "type": "message_start",
    "message": {
      "model": "claude-sonnet-5-5",
      "id": "msg_011CfWQ1TEzRFYuStMzD8Fi7",
      "type": "message",
      "role": "assistant",
      "content": [],
      "container": null,
      "stop_reason": null,
      "stop_sequence": null,
      "stop_details": null,
      "usage": {
        "input_tokens": 28,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "cache_creation": {
          "ephemeral_5m_input_tokens": 0,
          "ephemeral_1h_input_tokens": 0
        },
        "output_tokens": 8,
        "service_tier": "standard",
        "inference_geo": "global"
      },
      "diagnostics": null
    }
  },
  {
    "type": "content_block_start",
    "index": 0,
    "content_block": {
      "type": "text",
      "text": ""
    }
  },
  "... 53 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5.5/#page","headline":"Claude Sonnet 5.5","description":"Claude Sonnet 5.5 offers the best combination of speed and intelligence, with adaptive thinking for coding, tool use, reasoning, and long-horizon work.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: AssemblyAI's Universal 3 Pro speech recognition model for high-accuracy transcription.
title: AssemblyAI Universal-3 Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![AssemblyAI logo](https://developers.cloudflare.com/_astro/assemblyai.DKrad3Z3.svg)

# AssemblyAI Universal-3 Pro

Automatic Speech Recognition • AssemblyAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/assemblyai/universal-3-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`assemblyai/universal-3-pro`

- Third-party
- Zero data retention

AssemblyAI's Universal 3 Pro speech recognition model for high-accuracy transcription.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.assemblyai.com/legal/terms-of-service) |
| More information | [link ↗](https://www.assemblyai.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per audio minute$0.0035</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'assemblyai/universal-3-pro',
  { audio_url: 'https://cdn.openai.com/API/docs/audio/alloy.wav' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "assemblyai/universal-3-pro",
  "input": {
    "audio_url": "https://cdn.openai.com/API/docs/audio/alloy.wav"
  }
}'
```

```
The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years.
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "confidence": 0.99276465,
    "language_code": "en",
    "language_confidence": 0.9998,
    "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years.",
    "utterances": null,
    "words": [
      {
        "confidence": 0.9713957,
        "end": 129,
        "speaker": null,
        "start": 32,
        "text": "The"
      },
      {
        "confidence": 0.97053415,
        "end": 404,
        "speaker": null,
        "start": 129,
        "text": "sun"
      },
      {
        "confidence": 0.9998932,
        "end": 809,
        "speaker": null,
        "start": 420,
        "text": "rises"
      },
      {
        "confidence": 0.999092,
        "end": 922,
        "speaker": null,
        "start": 841,
        "text": "in"
      },
      {
        "confidence": 0.9997658,
        "end": 1068,
        "speaker": null,
        "start": 922,
        "text": "the"
      },
      {
        "confidence": 0.9684294,
        "end": 1456,
        "speaker": null,
        "start": 1149,
        "text": "east"
      },
      {
        "confidence": 0.9894344,
        "end": 1634,
        "speaker": null,
        "start": 1570,
        "text": "and"
      },
      {
        "confidence": 0.9999058,
        "end": 2055,
        "speaker": null,
        "start": 1715,
        "text": "sets"
      },
      {
        "confidence": 0.9997663,
        "end": 2104,
        "speaker": null,
        "start": 2055,
        "text": "in"
      },
      {
        "confidence": 0.9999552,
        "end": 2217,
        "speaker": null,
        "start": 2120,
        "text": "the"
      },
      {
        "confidence": 0.9913442,
        "end": 2638,
        "speaker": null,
        "start": 2217,
        "text": "west."
      },
      {
        "confidence": 0.9974367,
        "end": 3221,
        "speaker": null,
        "start": 3107,
        "text": "This"
      },
      {
        "confidence": 0.99965656,
        "end": 3560,
        "speaker": null,
        "start": 3269,
        "text": "simple"
      },
      {
        "confidence": 0.999713,
        "end": 3997,
        "speaker": null,
        "start": 3593,
        "text": "fact"
      },
      {
        "confidence": 0.99924207,
        "end": 4175,
        "speaker": null,
        "start": 3997,
        "text": "has"
      },
      {
        "confidence": 0.9995851,
        "end": 4289,
        "speaker": null,
        "start": 4224,
        "text": "been"
      },
      {
        "confidence": 0.9984724,
        "end": 4807,
        "speaker": null,
        "start": 4337,
        "text": "observed"
      },
      {
        "confidence": 0.9997143,
        "end": 4952,
        "speaker": null,
        "start": 4807,
        "text": "by"
      },
      {
        "confidence": 0.9997894,
        "end": 5422,
        "speaker": null,
        "start": 4969,
        "text": "humans"
      },
      {
        "confidence": 0.99947494,
        "end": 5519,
        "speaker": null,
        "start": 5422,
        "text": "for"
      },
      {
        "confidence": 0.99950385,
        "end": 6118,
        "speaker": null,
        "start": 5616,
        "text": "thousands"
      },
      {
        "confidence": 0.9995235,
        "end": 6231,
        "speaker": null,
        "start": 6118,
        "text": "of"
      },
      {
        "confidence": 0.9519594,
        "end": 6636,
        "speaker": null,
        "start": 6328,
        "text": "years."
      }
    ]
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**With Language Code** — Transcribe with an explicit language code</summary>



```ts
const response = await env.AI.run(
  'assemblyai/universal-3-pro',
  { audio_url: 'https://cdn.openai.com/API/docs/audio/echo.wav', language_code: 'en' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "assemblyai/universal-3-pro",
  "input": {
    "audio_url": "https://cdn.openai.com/API/docs/audio/echo.wav",
    "language_code": "en"
  }
}'
```

```
In the heart of the city, there is a large park where people go to relax and enjoy nature. The park has a beautiful pond with ducks and swans.
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "confidence": 0.9927905,
    "language_code": "en_us",
    "language_confidence": null,
    "text": "In the heart of the city, there is a large park where people go to relax and enjoy nature. The park has a beautiful pond with ducks and swans.",
    "utterances": null,
    "words": [
      {
        "confidence": 0.88134426,
        "end": 80,
        "speaker": null,
        "start": 32,
        "text": "In"
      },
      {
        "confidence": 0.9984907,
        "end": 241,
        "speaker": null,
        "start": 177,
        "text": "the"
      },
      {
        "confidence": 0.99956447,
        "end": 500,
        "speaker": null,
        "start": 258,
        "text": "heart"
      },
      {
        "confidence": 0.9995684,
        "end": 548,
        "speaker": null,
        "start": 500,
        "text": "of"
      },
      {
        "confidence": 0.99977916,
        "end": 677,
        "speaker": null,
        "start": 596,
        "text": "the"
      },
      {
        "confidence": 0.9956655,
        "end": 967,
        "speaker": null,
        "start": 677,
        "text": "city,"
      },
      {
        "confidence": 0.9987048,
        "end": 1435,
        "speaker": null,
        "start": 1322,
        "text": "there"
      },
      {
        "confidence": 0.99971443,
        "end": 1516,
        "speaker": null,
        "start": 1467,
        "text": "is"
      },
      {
        "confidence": 0.99948585,
        "end": 1596,
        "speaker": null,
        "start": 1564,
        "text": "a"
      },
      {
        "confidence": 0.9987669,
        "end": 2016,
        "speaker": null,
        "start": 1709,
        "text": "large"
      },
      {
        "confidence": 0.9981509,
        "end": 2467,
        "speaker": null,
        "start": 2129,
        "text": "park"
      },
      {
        "confidence": 0.9559358,
        "end": 2838,
        "speaker": null,
        "start": 2693,
        "text": "where"
      },
      {
        "confidence": 0.99979085,
        "end": 3145,
        "speaker": null,
        "start": 2854,
        "text": "people"
      },
      {
        "confidence": 0.9993555,
        "end": 3338,
        "speaker": null,
        "start": 3177,
        "text": "go"
      },
      {
        "confidence": 0.9998317,
        "end": 3467,
        "speaker": null,
        "start": 3338,
        "text": "to"
      },
      {
        "confidence": 0.99991953,
        "end": 4064,
        "speaker": null,
        "start": 3500,
        "text": "relax"
      },
      {
        "confidence": 0.9988979,
        "end": 4161,
        "speaker": null,
        "start": 4064,
        "text": "and"
      },
      {
        "confidence": 0.9999237,
        "end": 4484,
        "speaker": null,
        "start": 4161,
        "text": "enjoy"
      },
      {
        "confidence": 0.998528,
        "end": 4887,
        "speaker": null,
        "start": 4484,
        "text": "nature."
      },
      {
        "confidence": 0.990198,
        "end": 5758,
        "speaker": null,
        "start": 5597,
        "text": "The"
      },
      {
        "confidence": 0.99979144,
        "end": 6016,
        "speaker": null,
        "start": 5758,
        "text": "park"
      },
      {
        "confidence": 0.99926263,
        "end": 6177,
        "speaker": null,
        "start": 6064,
        "text": "has"
      },
      {
        "confidence": 0.9992211,
        "end": 6242,
        "speaker": null,
        "start": 6177,
        "text": "a"
      },
      {
        "confidence": 0.99989605,
        "end": 6774,
        "speaker": null,
        "start": 6322,
        "text": "beautiful"
      },
      {
        "confidence": 0.9998628,
        "end": 7193,
        "speaker": null,
        "start": 6790,
        "text": "pond"
      },
      {
        "confidence": 0.99960047,
        "end": 7355,
        "speaker": null,
        "start": 7193,
        "text": "with"
      },
      {
        "confidence": 0.99963534,
        "end": 7806,
        "speaker": null,
        "start": 7371,
        "text": "ducks"
      },
      {
        "confidence": 0.99866796,
        "end": 7919,
        "speaker": null,
        "start": 7855,
        "text": "and"
      },
      {
        "confidence": 0.9833702,
        "end": 8629,
        "speaker": null,
        "start": 7935,
        "text": "swans."
      }
    ]
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**With Key Terms** — Improve accuracy for domain-specific vocabulary</summary>



```ts
const response = await env.AI.run(
  'assemblyai/universal-3-pro',
  {
    audio_url: 'https://cdn.openai.com/API/docs/audio/nova.wav',
    keyterms_prompt: ['Kubernetes', 'microservices', 'containerization', 'load balancer'],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "assemblyai/universal-3-pro",
  "input": {
    "audio_url": "https://cdn.openai.com/API/docs/audio/nova.wav",
    "keyterms_prompt": [
      "Kubernetes",
      "microservices",
      "containerization",
      "load balancer"
    ]
  }
}'
```

```
In the kitchen, the aroma of freshly baked bread filled the air. The loaves were golden brown and crusty on the outside and soft and warm on the inside.
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "confidence": 0.9901139,
    "language_code": "en",
    "language_confidence": 0.9969,
    "text": "In the kitchen, the aroma of freshly baked bread filled the air. The loaves were golden brown and crusty on the outside and soft and warm on the inside.",
    "utterances": null,
    "words": [
      {
        "confidence": 0.9785539,
        "end": 80,
        "speaker": null,
        "start": 32,
        "text": "In"
      },
      {
        "confidence": 0.99962807,
        "end": 242,
        "speaker": null,
        "start": 177,
        "text": "the"
      },
      {
        "confidence": 0.99617165,
        "end": 565,
        "speaker": null,
        "start": 258,
        "text": "kitchen,"
      },
      {
        "confidence": 0.9991928,
        "end": 839,
        "speaker": null,
        "start": 743,
        "text": "the"
      },
      {
        "confidence": 0.99992657,
        "end": 1292,
        "speaker": null,
        "start": 839,
        "text": "aroma"
      },
      {
        "confidence": 0.99955577,
        "end": 1405,
        "speaker": null,
        "start": 1308,
        "text": "of"
      },
      {
        "confidence": 0.9996594,
        "end": 1889,
        "speaker": null,
        "start": 1405,
        "text": "freshly"
      },
      {
        "confidence": 0.99850214,
        "end": 2261,
        "speaker": null,
        "start": 1970,
        "text": "baked"
      },
      {
        "confidence": 0.9999217,
        "end": 2584,
        "speaker": null,
        "start": 2293,
        "text": "bread"
      },
      {
        "confidence": 0.9999,
        "end": 2859,
        "speaker": null,
        "start": 2600,
        "text": "filled"
      },
      {
        "confidence": 0.99993885,
        "end": 3004,
        "speaker": null,
        "start": 2859,
        "text": "the"
      },
      {
        "confidence": 0.9961201,
        "end": 3262,
        "speaker": null,
        "start": 3020,
        "text": "air."
      },
      {
        "confidence": 0.99501073,
        "end": 4119,
        "speaker": null,
        "start": 4054,
        "text": "The"
      },
      {
        "confidence": 0.9997483,
        "end": 4522,
        "speaker": null,
        "start": 4215,
        "text": "loaves"
      },
      {
        "confidence": 0.9998282,
        "end": 4781,
        "speaker": null,
        "start": 4619,
        "text": "were"
      },
      {
        "confidence": 0.99248224,
        "end": 5249,
        "speaker": null,
        "start": 4878,
        "text": "golden"
      },
      {
        "confidence": 0.9700398,
        "end": 5718,
        "speaker": null,
        "start": 5362,
        "text": "brown"
      },
      {
        "confidence": 0.9419883,
        "end": 5992,
        "speaker": null,
        "start": 5928,
        "text": "and"
      },
      {
        "confidence": 0.9994146,
        "end": 6541,
        "speaker": null,
        "start": 6089,
        "text": "crusty"
      },
      {
        "confidence": 0.9997141,
        "end": 6703,
        "speaker": null,
        "start": 6574,
        "text": "on"
      },
      {
        "confidence": 0.9999218,
        "end": 6784,
        "speaker": null,
        "start": 6719,
        "text": "the"
      },
      {
        "confidence": 0.9993179,
        "end": 7365,
        "speaker": null,
        "start": 6881,
        "text": "outside"
      },
      {
        "confidence": 0.8661144,
        "end": 7462,
        "speaker": null,
        "start": 7365,
        "text": "and"
      },
      {
        "confidence": 0.9996922,
        "end": 7882,
        "speaker": null,
        "start": 7462,
        "text": "soft"
      },
      {
        "confidence": 0.9998481,
        "end": 7995,
        "speaker": null,
        "start": 7882,
        "text": "and"
      },
      {
        "confidence": 0.99996424,
        "end": 8270,
        "speaker": null,
        "start": 8028,
        "text": "warm"
      },
      {
        "confidence": 0.9998791,
        "end": 8399,
        "speaker": null,
        "start": 8270,
        "text": "on"
      },
      {
        "confidence": 0.99982506,
        "end": 8512,
        "speaker": null,
        "start": 8415,
        "text": "the"
      },
      {
        "confidence": 0.9834439,
        "end": 8964,
        "speaker": null,
        "start": 8512,
        "text": "inside."
      }
    ]
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Speaker Diarization** — Identify different speakers in the audio</summary>



```ts
const response = await env.AI.run(
  'assemblyai/universal-3-pro',
  { audio_url: 'https://cdn.openai.com/API/docs/audio/onyx.wav', speaker_labels: true },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "assemblyai/universal-3-pro",
  "input": {
    "audio_url": "https://cdn.openai.com/API/docs/audio/onyx.wav",
    "speaker_labels": true
  }
}'
```

```
The train chugged along the tracks, carrying passengers to their destinations. The rhythmic sound of the wheels on the rails was soothing.
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "confidence": 0.99781793,
    "language_code": "en",
    "language_confidence": 0.9906,
    "text": "The train chugged along the tracks, carrying passengers to their destinations. The rhythmic sound of the wheels on the rails was soothing.",
    "utterances": [
      {
        "confidence": 0.99781793,
        "end": 7719,
        "speaker": "A",
        "start": 32,
        "text": "The train chugged along the tracks, carrying passengers to their destinations. The rhythmic sound of the wheels on the rails was soothing."
      }
    ],
    "words": [
      {
        "confidence": 0.9742124,
        "end": 113,
        "speaker": "A",
        "start": 32,
        "text": "The"
      },
      {
        "confidence": 0.99997795,
        "end": 403,
        "speaker": "A",
        "start": 177,
        "text": "train"
      },
      {
        "confidence": 0.99713653,
        "end": 904,
        "speaker": "A",
        "start": 516,
        "text": "chugged"
      },
      {
        "confidence": 0.9999881,
        "end": 1130,
        "speaker": "A",
        "start": 904,
        "text": "along"
      },
      {
        "confidence": 0.9999676,
        "end": 1308,
        "speaker": "A",
        "start": 1227,
        "text": "the"
      },
      {
        "confidence": 0.9995983,
        "end": 1808,
        "speaker": "A",
        "start": 1308,
        "text": "tracks,"
      },
      {
        "confidence": 0.9998933,
        "end": 2341,
        "speaker": "A",
        "start": 2131,
        "text": "carrying"
      },
      {
        "confidence": 0.999992,
        "end": 3068,
        "speaker": "A",
        "start": 2454,
        "text": "passengers"
      },
      {
        "confidence": 0.99999034,
        "end": 3229,
        "speaker": "A",
        "start": 3100,
        "text": "to"
      },
      {
        "confidence": 0.9999908,
        "end": 3423,
        "speaker": "A",
        "start": 3262,
        "text": "their"
      },
      {
        "confidence": 0.9992286,
        "end": 4198,
        "speaker": "A",
        "start": 3423,
        "text": "destinations."
      },
      {
        "confidence": 0.99871373,
        "end": 5119,
        "speaker": "A",
        "start": 5038,
        "text": "The"
      },
      {
        "confidence": 0.9999517,
        "end": 5523,
        "speaker": "A",
        "start": 5184,
        "text": "rhythmic"
      },
      {
        "confidence": 0.99993813,
        "end": 5926,
        "speaker": "A",
        "start": 5523,
        "text": "sound"
      },
      {
        "confidence": 0.99991894,
        "end": 6007,
        "speaker": "A",
        "start": 5926,
        "text": "of"
      },
      {
        "confidence": 0.99993825,
        "end": 6088,
        "speaker": "A",
        "start": 6007,
        "text": "the"
      },
      {
        "confidence": 0.99995935,
        "end": 6459,
        "speaker": "A",
        "start": 6169,
        "text": "wheels"
      },
      {
        "confidence": 0.99997675,
        "end": 6605,
        "speaker": "A",
        "start": 6556,
        "text": "on"
      },
      {
        "confidence": 0.99999475,
        "end": 6718,
        "speaker": "A",
        "start": 6637,
        "text": "the"
      },
      {
        "confidence": 0.9999932,
        "end": 7105,
        "speaker": "A",
        "start": 6718,
        "text": "rails"
      },
      {
        "confidence": 0.999851,
        "end": 7299,
        "speaker": "A",
        "start": 7138,
        "text": "was"
      },
      {
        "confidence": 0.98378325,
        "end": 7719,
        "speaker": "A",
        "start": 7299,
        "text": "soothing."
      }
    ]
  },
  "state": "Completed"
}
```

</details>

## Parameters

audio\_url

`string`The URL of the audio file to transcribe. Can be a publicly accessible URL or a data URI (data:audio/...;base64,...). For data URIs, the audio will be uploaded to AssemblyAI automatically. Required for pre-recorded transcription (when stream is false or not set).

websocket

`boolean`Enable real-time WebSocket streaming for live audio transcription. When true, a WebSocket connection is established instead of submitting a pre-recorded transcription job. Cannot be used with audio\_url.

language\_code

`string`The language code for the audio file (e.g., "en", "es", "fr"). Defaults to automatic language detection.

language\_detection

`boolean`Enable automatic language detection. When enabled with speech\_models, the system will automatically select the best model for the detected language.

prompt

`string`A custom prompt to guide transcription style, formatting, and output characteristics. Maximum 1,500 words.

▶keyterms\_prompt\[]

`array`An array of up to 1,000 words or phrases (max 6 words per phrase) to improve transcription accuracy. Cannot be used with the prompt parameter.

temperature

`number`minimum: 0maximum: 1Controls randomness in model output (0.0-1.0). Lower values make output more deterministic. Default is 0.0.

speaker\_labels

`boolean`Enable speaker diarization to identify different speakers in the audio.

speakers\_expected

`integer`minimum: 1maximum: 9007199254740991Expected number of speakers for speaker diarization.

auto\_chapters

`boolean`Enable automatic chapter detection.

entity\_detection

`boolean`Enable detection of entities like names, organizations, and locations.

sentiment\_analysis

`boolean`Enable sentiment analysis for each sentence.

auto\_highlights

`boolean`Enable automatic extraction of key phrases and highlights.

content\_safety

`boolean`Enable content safety detection for sensitive content.

iab\_categories

`boolean`Enable IAB (Interactive Advertising Bureau) content taxonomy classification.

▶custom\_spelling\[]

`array`Custom spelling rules to replace specific words or phrases in the transcription output.

disfluencies

`boolean`Include filler words like "um", "uh", etc. in the transcript.

multichannel

`boolean`Process each audio channel separately for multi-channel audio files.

dual\_channel

`boolean`Process audio as dual-channel (stereo) for better accuracy.

webhook\_url

`string`format: uriURL to receive webhook notifications when transcription is complete.

audio\_start\_from

`integer`minimum: 0maximum: 9007199254740991Timestamp (in milliseconds) to start transcription from.

audio\_end\_at

`integer`minimum: 0maximum: 9007199254740991Timestamp (in milliseconds) to end transcription at.

▶word\_boost\[]

`array`Array of words to boost recognition accuracy (legacy - use keyterms\_prompt instead).

boost\_param

`string`enum: low, default, highHow much to boost the words in word\_boost.

filter\_profanity

`boolean`Filter profanity from the transcription.

redact\_pii

`boolean`Redact personally identifiable information.

redact\_pii\_audio

`boolean`Generate a redacted audio file with PII removed.

▶redact\_pii\_policies\[]

`array`Specific PII policies to apply for redaction.

redact\_pii\_sub

`string`enum: entity\_name, hashStrategy for substituting redacted PII.

speech\_threshold

`number`minimum: 0maximum: 1Confidence threshold for speech detection.

domain

`string`enum: medical-v1Domain-specific transcription mode. "medical-v1" enables medical terminology optimization.

text

`string`The transcribed text.

words

`array | null`Word-level timestamps and confidence scores.

utterances

`array | null`Speaker-separated utterances (when speaker\_labels is enabled).

confidence

`number`Overall confidence score for the transcription.

language\_code

`string`Detected or specified language code.

language\_confidence

`number`Confidence score for language detection.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/assemblyai/universal-3-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/assemblyai/universal-3-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/assemblyai/universal-3-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/assemblyai/universal-3-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/assemblyai/universal-3-pro/#page","headline":"AssemblyAI Universal-3 Pro","description":"AssemblyAI's Universal 3 Pro speech recognition model for high-accuracy transcription.","url":"https://developers.cloudflare.com/ai/models/assemblyai/universal-3-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: AssemblyAI's Universal-3.5 Pro speech recognition model for fast, high-accuracy transcription.
title: AssemblyAI Universal-3.5 Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![AssemblyAI logo](https://developers.cloudflare.com/_astro/assemblyai.DKrad3Z3.svg)

# AssemblyAI Universal-3.5 Pro

Automatic Speech Recognition • AssemblyAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/assemblyai/universal-3.5-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`assemblyai/universal-3.5-pro`

- Third-party

AssemblyAI's Universal-3.5 Pro speech recognition model for fast, high-accuracy transcription.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.assemblyai.com/legal/terms-of-service) |
| More information | [link ↗](https://www.assemblyai.com/docs/getting-started/universal-3-5-pro) |
| Pricing | <ul><li>Per audio minute$0.0035</li><li>Per minute (speaker diarization)$0.0003</li><li>Per minute (key terms)$0.00083</li><li>Per minute (medical)$0.0025</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'assemblyai/universal-3.5-pro',
  { audio_url: 'https://cdn.openai.com/API/docs/audio/alloy.wav' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "assemblyai/universal-3.5-pro",
  "input": {
    "audio_url": "https://cdn.openai.com/API/docs/audio/alloy.wav"
  }
}'
```

```
The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years.
```

```json
{
  "id": "93b8082d-22c2-4dd0-adf6-0037d2c7027a",
  "language_model": "assemblyai_default",
  "acoustic_model": "assemblyai_default",
  "language_code": "en",
  "speech_understanding": null,
  "translated_texts": null,
  "status": "completed",
  "audio_url": "https://cdn.openai.com/API/docs/audio/alloy.wav",
  "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years.",
  "words": [
    {
      "text": "The",
      "start": 32,
      "end": 129,
      "confidence": 0.95348084,
      "speaker": null
    },
    {
      "text": "sun",
      "start": 129,
      "end": 404,
      "confidence": 0.97099674,
      "speaker": null
    },
    {
      "text": "rises",
      "start": 420,
      "end": 809,
      "confidence": 0.9999746,
      "speaker": null
    },
    {
      "text": "in",
      "start": 841,
      "end": 922,
      "confidence": 0.999997,
      "speaker": null
    },
    {
      "text": "the",
      "start": 922,
      "end": 1068,
      "confidence": 0.99999905,
      "speaker": null
    },
    {
      "text": "east",
      "start": 1149,
      "end": 1456,
      "confidence": 0.9853527,
      "speaker": null
    },
    {
      "text": "and",
      "start": 1570,
      "end": 1634,
      "confidence": 0.999203,
      "speaker": null
    },
    {
      "text": "sets",
      "start": 1715,
      "end": 2055,
      "confidence": 0.999995,
      "speaker": null
    },
    {
      "text": "in",
      "start": 2055,
      "end": 2104,
      "confidence": 0.99999857,
      "speaker": null
    },
    {
      "text": "the",
      "start": 2120,
      "end": 2217,
      "confidence": 0.9999993,
      "speaker": null
    },
    {
      "text": "west.",
      "start": 2217,
      "end": 2638,
      "confidence": 0.9959912,
      "speaker": null
    },
    {
      "text": "This",
      "start": 3107,
      "end": 3221,
      "confidence": 0.9999709,
      "speaker": null
    },
    {
      "text": "simple",
      "start": 3269,
      "end": 3560,
      "confidence": 0.9999976,
      "speaker": null
    },
    {
      "text": "fact",
      "start": 3593,
      "end": 3997,
      "confidence": 0.999998,
      "speaker": null
    },
    {
      "text": "has",
      "start": 3997,
      "end": 4175,
      "confidence": 0.999995,
      "speaker": null
    },
    {
      "text": "been",
      "start": 4224,
      "end": 4289,
      "confidence": 0.9999974,
      "speaker": null
    },
    {
      "text": "observed",
      "start": 4337,
      "end": 4807,
      "confidence": 0.9999957,
      "speaker": null
    },
    {
      "text": "by",
      "start": 4807,
      "end": 4952,
      "confidence": 0.999998,
      "speaker": null
    },
    {
      "text": "humans",
      "start": 4969,
      "end": 5422,
      "confidence": 0.99999607,
      "speaker": null
    },
    {
      "text": "for",
      "start": 5422,
      "end": 5519,
      "confidence": 0.99999416,
      "speaker": null
    },
    {
      "text": "thousands",
      "start": 5616,
      "end": 6118,
      "confidence": 0.9999938,
      "speaker": null
    },
    {
      "text": "of",
      "start": 6118,
      "end": 6231,
      "confidence": 0.9999945,
      "speaker": null
    },
    {
      "text": "years.",
      "start": 6328,
      "end": 6636,
      "confidence": 0.9984148,
      "speaker": null
    }
  ],
  "utterances": null,
  "confidence": 0.9957971,
  "audio_duration": 7,
  "punctuate": true,
  "format_text": true,
  "webhook_url": null,
  "webhook_status_code": null,
  "webhook_auth": false,
  "webhook_auth_header_name": null,
  "speed_boost": false,
  "auto_highlights_result": null,
  "auto_highlights": false,
  "audio_start_from": null,
  "audio_end_at": null,
  "word_boost": [],
  "boost_param": null,
  "prompt": null,
  "keyterms_prompt": [],
  "filter_profanity": false,
  "redact_pii": false,
  "redact_pii_audio": false,
  "redact_pii_audio_quality": null,
  "redact_pii_audio_options": null,
  "redact_pii_policies": null,
  "redact_pii_sub": null,
  "redact_static_entities": null,
  "speaker_labels": false,
  "speaker_options": null,
  "content_safety": false,
  "iab_categories": false,
  "content_safety_labels": {
    "status": "unavailable",
    "results": [],
    "summary": {}
  },
  "iab_categories_result": {
    "status": "unavailable",
    "results": [],
    "summary": {}
  },
  "language_detection": true,
  "language_detection_options": null,
  "language_detection_results": null,
  "language_confidence_threshold": null,
  "language_confidence": 0.9998,
  "custom_spelling": null,
  "throttled": false,
  "auto_chapters": false,
  "summarization": false,
  "summary_type": null,
  "summary_model": null,
  "custom_topics": false,
  "topics": [],
  "speech_threshold": null,
  "speech_model": null,
  "speech_models": [
    "universal-3-5-pro"
  ],
  "speech_model_used": "universal-3-5-pro",
  "temperature": null,
  "remove_audio_tags": "all",
  "chapters": null,
  "disfluencies": false,
  "entity_detection": false,
  "sentiment_analysis": false,
  "sentiment_analysis_results": null,
  "entities": null,
  "speakers_expected": null,
  "summary": null,
  "custom_topics_results": null,
  "is_deleted": null,
  "multichannel": null,
  "project_id": 1747096,
  "token_id": 1768830
}
```

## Examples

<details>

<summary>**Language and Keyterms** — Transcribe with an explicit language and domain terms</summary>



```ts
const response = await env.AI.run(
  'assemblyai/universal-3.5-pro',
  {
    audio_url: 'https://cdn.openai.com/API/docs/audio/echo.wav',
    language_code: 'en',
    keyterms_prompt: ['Kubernetes', 'microservices', 'containerization', 'load balancer'],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "assemblyai/universal-3.5-pro",
  "input": {
    "audio_url": "https://cdn.openai.com/API/docs/audio/echo.wav",
    "language_code": "en",
    "keyterms_prompt": [
      "Kubernetes",
      "microservices",
      "containerization",
      "load balancer"
    ]
  }
}'
```

```
In the heart of the city, there is a large park where people go to relax and enjoy nature. The park has a beautiful pond with ducks and swans.
```

```json
{
  "id": "7f184aba-4a6d-49fa-b47a-f2ec47e67878",
  "language_model": "assemblyai_default",
  "acoustic_model": "assemblyai_default",
  "language_code": "en_us",
  "speech_understanding": null,
  "translated_texts": null,
  "status": "completed",
  "audio_url": "https://cdn.openai.com/API/docs/audio/echo.wav",
  "text": "In the heart of the city, there is a large park where people go to relax and enjoy nature. The park has a beautiful pond with ducks and swans.",
  "words": [
    {
      "text": "In",
      "start": 32,
      "end": 80,
      "confidence": 0.99823916,
      "speaker": null
    },
    {
      "text": "the",
      "start": 177,
      "end": 241,
      "confidence": 0.9997907,
      "speaker": null
    },
    {
      "text": "heart",
      "start": 258,
      "end": 500,
      "confidence": 0.9998222,
      "speaker": null
    },
    {
      "text": "of",
      "start": 500,
      "end": 548,
      "confidence": 0.9999982,
      "speaker": null
    },
    {
      "text": "the",
      "start": 596,
      "end": 677,
      "confidence": 0.99993014,
      "speaker": null
    },
    {
      "text": "city,",
      "start": 677,
      "end": 967,
      "confidence": 0.9999535,
      "speaker": null
    },
    {
      "text": "there",
      "start": 1322,
      "end": 1435,
      "confidence": 0.99998367,
      "speaker": null
    },
    {
      "text": "is",
      "start": 1467,
      "end": 1516,
      "confidence": 0.9989073,
      "speaker": null
    },
    {
      "text": "a",
      "start": 1564,
      "end": 1596,
      "confidence": 0.99998987,
      "speaker": null
    },
    {
      "text": "large",
      "start": 1709,
      "end": 2016,
      "confidence": 0.99996316,
      "speaker": null
    },
    {
      "text": "park",
      "start": 2129,
      "end": 2467,
      "confidence": 0.99998546,
      "speaker": null
    },
    {
      "text": "where",
      "start": 2693,
      "end": 2838,
      "confidence": 0.99389255,
      "speaker": null
    },
    {
      "text": "people",
      "start": 2854,
      "end": 3145,
      "confidence": 0.99998343,
      "speaker": null
    },
    {
      "text": "go",
      "start": 3177,
      "end": 3338,
      "confidence": 0.9999392,
      "speaker": null
    },
    {
      "text": "to",
      "start": 3338,
      "end": 3467,
      "confidence": 0.9999963,
      "speaker": null
    },
    {
      "text": "relax",
      "start": 3500,
      "end": 4064,
      "confidence": 0.99998176,
      "speaker": null
    },
    {
      "text": "and",
      "start": 4064,
      "end": 4161,
      "confidence": 0.99998665,
      "speaker": null
    },
    {
      "text": "enjoy",
      "start": 4161,
      "end": 4484,
      "confidence": 0.9999976,
      "speaker": null
    },
    {
      "text": "nature.",
      "start": 4484,
      "end": 4887,
      "confidence": 0.9999689,
      "speaker": null
    },
    {
      "text": "The",
      "start": 5597,
      "end": 5758,
      "confidence": 0.9997563,
      "speaker": null
    },
    {
      "text": "park",
      "start": 5758,
      "end": 6016,
      "confidence": 0.99999034,
      "speaker": null
    },
    {
      "text": "has",
      "start": 6064,
      "end": 6177,
      "confidence": 0.99998844,
      "speaker": null
    },
    {
      "text": "a",
      "start": 6177,
      "end": 6242,
      "confidence": 0.9999819,
      "speaker": null
    },
    {
      "text": "beautiful",
      "start": 6322,
      "end": 6774,
      "confidence": 0.9999924,
      "speaker": null
    },
    {
      "text": "pond",
      "start": 6790,
      "end": 7193,
      "confidence": 0.99999106,
      "speaker": null
    },
    {
      "text": "with",
      "start": 7193,
      "end": 7355,
      "confidence": 0.9997123,
      "speaker": null
    },
    {
      "text": "ducks",
      "start": 7371,
      "end": 7806,
      "confidence": 0.9999808,
      "speaker": null
    },
    {
      "text": "and",
      "start": 7855,
      "end": 7919,
      "confidence": 0.9999771,
      "speaker": null
    },
    {
      "text": "swans.",
      "start": 7935,
      "end": 8629,
      "confidence": 0.99828225,
      "speaker": null
    }
  ],
  "utterances": null,
  "confidence": 0.9995849,
  "audio_duration": 9,
  "punctuate": true,
  "format_text": true,
  "webhook_url": null,
  "webhook_status_code": null,
  "webhook_auth": false,
  "webhook_auth_header_name": null,
  "speed_boost": false,
  "auto_highlights_result": null,
  "auto_highlights": false,
  "audio_start_from": null,
  "audio_end_at": null,
  "word_boost": [],
  "boost_param": null,
  "prompt": null,
  "keyterms_prompt": [
    "Kubernetes",
    "microservices",
    "containerization",
    "load balancer"
  ],
  "filter_profanity": false,
  "redact_pii": false,
  "redact_pii_audio": false,
  "redact_pii_audio_quality": null,
  "redact_pii_audio_options": null,
  "redact_pii_policies": null,
  "redact_pii_sub": null,
  "redact_static_entities": null,
  "speaker_labels": false,
  "speaker_options": null,
  "content_safety": false,
  "iab_categories": false,
  "content_safety_labels": {
    "status": "unavailable",
    "results": [],
    "summary": {}
  },
  "iab_categories_result": {
    "status": "unavailable",
    "results": [],
    "summary": {}
  },
  "language_detection": false,
  "language_detection_options": null,
  "language_detection_results": null,
  "language_confidence_threshold": null,
  "language_confidence": null,
  "custom_spelling": null,
  "throttled": false,
  "auto_chapters": false,
  "summarization": false,
  "summary_type": null,
  "summary_model": null,
  "custom_topics": false,
  "topics": [],
  "speech_threshold": null,
  "speech_model": null,
  "speech_models": [
    "universal-3-5-pro"
  ],
  "speech_model_used": "universal-3-5-pro",
  "temperature": null,
  "remove_audio_tags": "all",
  "chapters": null,
  "disfluencies": false,
  "entity_detection": false,
  "sentiment_analysis": false,
  "sentiment_analysis_results": null,
  "entities": null,
  "speakers_expected": null,
  "summary": null,
  "custom_topics_results": null,
  "is_deleted": null,
  "multichannel": null,
  "project_id": 1747096,
  "token_id": 1768830
}
```

</details>

## Parameters

audio\_url

`string`requiredThe URL of the audio or video file to transcribe, or a data URI.

audio\_start\_from

`integer`minimum: 0maximum: 9007199254740991Timestamp in milliseconds at which to begin transcription.

audio\_end\_at

`integer`minimum: 0maximum: 9007199254740991Timestamp in milliseconds at which to stop transcription.

language\_code

`string`Language code of the audio.

language\_detection

`boolean`Whether to automatically detect the language.

▶language\_detection\_options{}

`object`

prompt

`string`Natural-language instructions for transcription style.

▶keyterms\_prompt\[]

`array`Words or phrases to prioritize during transcription.

temperature

`number`minimum: 0maximum: 1Controls transcription randomness from 0 to 1.

punctuate

`boolean`Whether to add punctuation.

format\_text

`boolean`Whether to apply text formatting.

disfluencies

`boolean`Whether to include filler words such as um and uh.

filter\_profanity

`boolean`Whether to filter profanity.

speaker\_labels

`boolean`Whether to identify speakers in the transcript.

speakers\_expected

`integer`exclusiveMinimum: 0maximum: 9007199254740991Expected number of speakers.

▶speaker\_options{}

`object`

multichannel

`boolean`Whether to transcribe each audio channel separately.

▶custom\_spelling\[]

`array`

auto\_highlights

`boolean`Whether to extract key phrases.

content\_safety

`boolean`Whether to detect sensitive content.

content\_safety\_confidence

`integer`minimum: 25maximum: 100Content safety confidence threshold from 25 to 100.

iab\_categories

`boolean`Whether to classify topics using IAB categories.

entity\_detection

`boolean`Whether to detect named entities.

sentiment\_analysis

`boolean`Whether to analyze sentence sentiment.

domain

`string`const: medical-v1Domain-specific model for medical terminology.

speech\_threshold

`number`minimum: 0maximum: 1Minimum fraction of speech required for transcription.

redact\_pii

`boolean`Whether to redact personally identifiable information.

redact\_pii\_audio

`boolean`Whether to generate an audio file with spoken PII redacted.

redact\_pii\_audio\_quality

`string`enum: mp3, wavFormat of the redacted audio file.

▶redact\_pii\_audio\_options{}

`object`

▶redact\_pii\_policies\[]

`array`PII categories to redact.

redact\_pii\_sub

`string`enum: entity\_name, hashReplacement strategy for redacted PII.

redact\_pii\_return\_unredacted

`boolean`Whether to include unredacted fields alongside the redacted transcript.

▶redact\_static\_entities{}

`object`User-defined terms to redact, grouped by label.

text

`string`The transcribed text.

words

`array | null`Word-level timestamps and confidence scores.

utterances

`array | null`Speaker-separated utterances (when speaker\_labels is enabled).

confidence

`number`Overall confidence score for the transcription.

language\_code

`string`Detected or specified language code.

language\_confidence

`number`Confidence score for language detection.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/assemblyai/universal-3.5-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/assemblyai/universal-3.5-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/assemblyai/universal-3.5-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/assemblyai/universal-3.5-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/assemblyai/universal-3.5-pro/#page","headline":"AssemblyAI Universal-3.5 Pro","description":"AssemblyAI's Universal-3.5 Pro speech recognition model for fast, high-accuracy transcription.","url":"https://developers.cloudflare.com/ai/models/assemblyai/universal-3.5-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: FLUX.1 Kontext [max] is Black Forest Labs' highest-quality Kontext model for text-to-image generation and context-aware image editing.
title: FLUX.1 Kontext [max]
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)

# FLUX.1 Kontext \[max]

Text-to-Image • Black Forest Labs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-max/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`black-forest-labs/flux-1-kontext-max`

- Third-party

FLUX.1 Kontext \[max] is Black Forest Labs' highest-quality Kontext model for text-to-image generation and context-aware image editing.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://blackforestlabs.ai/terms-of-service/) |
| More information | [link ↗](https://docs.bfl.ml/api-reference/models/edit-or-create-an-image-with-flux1-kontext-[max]) |
| Pricing | <ul><li>Per image$0.08</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'black-forest-labs/flux-1-kontext-max',
  {
    prompt:
      'A lone warrior in bloodstained samurai armor stands before a pagoda engulfed in flames, cinematic dark fantasy realism',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-1-kontext-max",
  "input": {
    "prompt": "A lone warrior in bloodstained samurai armor stands before a pagoda engulfed in flames, cinematic dark fantasy realism"
  }
}'
```

![Maximum Quality Generation](https://examples.aig.cloudflare.com/black-forest-labs/flux-1-kontext-max/maximum-quality-generation.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-1-kontext-max/maximum-quality-generation.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Reproducible Generation** — Use a seed and PNG output for reproducible image generation.</summary>



```ts
const response = await env.AI.run(
  'black-forest-labs/flux-1-kontext-max',
  {
    prompt:
      'A detailed oil painting portrait of a Renaissance nobleman with an intricate lace collar',
    seed: 42,
    output_format: 'png',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-1-kontext-max",
  "input": {
    "prompt": "A detailed oil painting portrait of a Renaissance nobleman with an intricate lace collar",
    "seed": 42,
    "output_format": "png"
  }
}'
```

![Reproducible Generation](https://examples.aig.cloudflare.com/black-forest-labs/flux-1-kontext-max/reproducible-generation.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-1-kontext-max/reproducible-generation.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredText prompt for image generation or editing.

input\_image

`string`Optional base64 encoded image or URL to edit.

aspect\_ratio

`string`Output aspect ratio, from 3:7 to 7:3. Defaults to 1:1.

seed

`integer | null`Optional seed for reproducible generation.

prompt\_upsampling

`boolean`Whether to upsample the prompt. Defaults to false.

safety\_tolerance

`integer`minimum: 0maximum: 6Moderation tolerance. 0 is strictest and 6 is most permissive.

output\_format

`string`enum: jpeg, pngOutput image format. Defaults to jpeg.

image

`string`format: uriURL to the generated image

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-max/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-max/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-max/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-max/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-max/#page","headline":"FLUX.1 Kontext [max]","description":"FLUX.1 Kontext [max] is Black Forest Labs' highest-quality Kontext model for text-to-image generation and context-aware image editing.","url":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-max/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: FLUX.1 Kontext [pro] creates and edits images from text prompts with strong character and style consistency.
title: FLUX.1 Kontext [pro]
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)

# FLUX.1 Kontext \[pro]

Text-to-Image • Black Forest Labs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`black-forest-labs/flux-1-kontext-pro`

- Third-party

FLUX.1 Kontext \[pro] creates and edits images from text prompts with strong character and style consistency.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://blackforestlabs.ai/terms-of-service/) |
| More information | [link ↗](https://docs.bfl.ml/api-reference/models/edit-or-create-an-image-with-flux1-kontext-[pro]) |
| Pricing | <ul><li>Per image$0.04</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'black-forest-labs/flux-1-kontext-pro',
  { prompt: 'A small furry elephant pet looks out from a cat house' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-1-kontext-pro",
  "input": {
    "prompt": "A small furry elephant pet looks out from a cat house"
  }
}'
```

![Text to Image](https://examples.aig.cloudflare.com/black-forest-labs/flux-1-kontext-pro/text-to-image.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-1-kontext-pro/text-to-image.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Wide Cinematic Image** — Generate a cinematic landscape using a wide aspect ratio.</summary>



```ts
const response = await env.AI.run(
  'black-forest-labs/flux-1-kontext-pro',
  {
    prompt:
      'A remote gas station swallowed by crimson fog, green glow from overhead lights staining the asphalt, cinematic wide shot',
    input_image:
      'https://cdn.sanity.io/images/gsvmb6gz/production/3ae6ee032b85373b84934574f3ac3bb2fb792d64-2048x1365.jpg',
    aspect_ratio: '16:9',
    output_format: 'jpeg',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-1-kontext-pro",
  "input": {
    "prompt": "A remote gas station swallowed by crimson fog, green glow from overhead lights staining the asphalt, cinematic wide shot",
    "input_image": "https://cdn.sanity.io/images/gsvmb6gz/production/3ae6ee032b85373b84934574f3ac3bb2fb792d64-2048x1365.jpg",
    "aspect_ratio": "16:9",
    "output_format": "jpeg"
  }
}'
```

![Wide Cinematic Image](https://examples.aig.cloudflare.com/black-forest-labs/flux-1-kontext-pro/wide-cinematic-image.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-1-kontext-pro/wide-cinematic-image.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredText prompt for image generation or editing.

input\_image

`string`Optional base64 encoded image or URL to edit.

aspect\_ratio

`string`Output aspect ratio, from 3:7 to 7:3. Defaults to 1:1.

seed

`integer | null`Optional seed for reproducible generation.

prompt\_upsampling

`boolean`Whether to upsample the prompt. Defaults to false.

safety\_tolerance

`integer`minimum: 0maximum: 6Moderation tolerance. 0 is strictest and 6 is most permissive.

output\_format

`string`enum: jpeg, pngOutput image format. Defaults to jpeg.

image

`string`format: uriURL to the generated image

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-pro/#page","headline":"FLUX.1 Kontext [pro]","description":"FLUX.1 Kontext [pro] creates and edits images from text prompts with strong character and style consistency.","url":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-1-kontext-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: FLUX.2 [flex] is Black Forest Labs' fine-grained control variant of FLUX.2 — exposes tunable inference steps, guidance, and prompt upsampling for typography-heavy and production workflows.
title: FLUX.2 [flex]
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)

# FLUX.2 \[flex]

Text-to-Image • Black Forest Labs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-flex/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`black-forest-labs/flux-2-flex`

- Third-party

FLUX.2 \[flex] is Black Forest Labs' fine-grained control variant of FLUX.2 — exposes tunable inference steps, guidance, and prompt upsampling for typography-heavy and production workflows.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://blackforestlabs.ai/terms-of-service/) |
| More information | [link ↗](https://blackforestlabs.ai/) |
| Pricing | <ul><li>First output megapixel$0.05</li><li>Per additional output megapixel$0.05</li><li>Per input megapixel$0.05</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'black-forest-labs/flux-2-flex',
  {
    prompt:
      "Samsung Galaxy S25 Ultra product advertisement, 'Ultra-strong titanium' headline, close-up of phone edge showing titanium frame, dark gradient background, clean minimalist tech aesthetic",
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-2-flex",
  "input": {
    "prompt": "Samsung Galaxy S25 Ultra product advertisement, '\''Ultra-strong titanium'\'' headline, close-up of phone edge showing titanium frame, dark gradient background, clean minimalist tech aesthetic"
  }
}'
```

![Typography \& Design](https://examples.aig.cloudflare.com/black-forest-labs/flux-2-flex/typography-design.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-2-flex/typography-design.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**High Detail Generation** — Crank steps and guidance for maximum detail when latency is not the priority</summary>



```ts
const response = await env.AI.run(
  'black-forest-labs/flux-2-flex',
  {
    prompt: 'A detailed oil painting portrait of a Renaissance nobleman with intricate lace collar',
    guidance: 7.5,
    steps: 50,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-2-flex",
  "input": {
    "prompt": "A detailed oil painting portrait of a Renaissance nobleman with intricate lace collar",
    "guidance": 7.5,
    "steps": 50
  }
}'
```

![High Detail Generation](https://examples.aig.cloudflare.com/black-forest-labs/flux-2-flex/high-detail-generation.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-2-flex/high-detail-generation.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Fast Draft** — Fast draft with prompt upsampling disabled — preserves the literal prompt</summary>



```ts
const response = await env.AI.run(
  'black-forest-labs/flux-2-flex',
  { prompt: 'A simple line sketch of a mountain landscape', prompt_upsampling: false, steps: 10 },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-2-flex",
  "input": {
    "prompt": "A simple line sketch of a mountain landscape",
    "prompt_upsampling": false,
    "steps": 10
  }
}'
```

![Fast Draft](https://examples.aig.cloudflare.com/black-forest-labs/flux-2-flex/fast-draft.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-2-flex/fast-draft.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredText prompt for image generation or editing.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Optional seed for reproducible generation.

width

`integer`minimum: 64maximum: 9007199254740991Width of the generated image in pixels (minimum 64). Omit to let BFL pick.

height

`integer`minimum: 64maximum: 9007199254740991Height of the generated image in pixels (minimum 64). Omit to let BFL pick.

safety\_tolerance

`integer`minimum: 0maximum: 5Tolerance for input/output moderation. 0 is the strictest, 5 the most permissive. Defaults to 2.

output\_format

`string`enum: jpeg, png, webpOutput image format. Defaults to jpeg.

▶input\_images\[]

`array`maxItems: 8Up to 8 reference images for editing or multi-image composition. Each entry is an HTTPS URL or a data:image/...;base64,... URI.

prompt\_upsampling

`boolean`Whether BFL should expand short prompts before generation. Defaults to true on flex.

guidance

`number`minimum: 1.5maximum: 10Classifier-free guidance scale (1.5–10). Higher values follow the prompt more strictly at the cost of realism.

steps

`integer`minimum: 1maximum: 50Number of denoising steps (1–50). Higher steps yield more detail at the cost of latency.

image

`string`format: uriURL to the generated image

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-flex/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-flex/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-flex/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-flex/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-flex/#page","headline":"FLUX.2 [flex]","description":"FLUX.2 [flex] is Black Forest Labs' fine-grained control variant of FLUX.2 — exposes tunable inference steps, guidance, and prompt upsampling for typography-heavy and production workflows.","url":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-flex/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: FLUX.2 [max] is Black Forest Labs' highest-quality image model — top editing consistency, strongest prompt following, and grounding search for visualizations of real-time information.
title: FLUX.2 [max]
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)

# FLUX.2 \[max]

Text-to-Image • Black Forest Labs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-max/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`black-forest-labs/flux-2-max`

- Third-party

FLUX.2 \[max] is Black Forest Labs' highest-quality image model — top editing consistency, strongest prompt following, and grounding search for visualizations of real-time information.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://blackforestlabs.ai/terms-of-service/) |
| More information | [link ↗](https://blackforestlabs.ai/) |
| Pricing | <ul><li>First output megapixel$0.07</li><li>Per additional output megapixel$0.03</li><li>Per input megapixel$0.03</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'black-forest-labs/flux-2-max',
  {
    prompt:
      'A cat on its back legs running like a human is holding a big silver fish with its arms. The cat is running away from the shop owner and has a panicked look on his face. The scene is situated in a crowded market.',
    height: 2048,
    width: 1440,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-2-max",
  "input": {
    "prompt": "A cat on its back legs running like a human is holding a big silver fish with its arms. The cat is running away from the shop owner and has a panicked look on his face. The scene is situated in a crowded market.",
    "height": 2048,
    "width": 1440
  }
}'
```

![High Resolution Scene](https://examples.aig.cloudflare.com/black-forest-labs/flux-2-max/high-resolution-scene.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-2-max/high-resolution-scene.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Hex Color Control** — Exact color control via hex codes — useful for brand-consistent imagery</summary>



```ts
const response = await env.AI.run(
  'black-forest-labs/flux-2-max',
  {
    prompt:
      'A vase on a table in living room, the color of the vase is a gradient of color, starting with color #02eb3c and finishing with color #edfa3c. The flowers inside the vase have the color #ff0088',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-2-max",
  "input": {
    "prompt": "A vase on a table in living room, the color of the vase is a gradient of color, starting with color #02eb3c and finishing with color #edfa3c. The flowers inside the vase have the color #ff0088"
  }
}'
```

![Hex Color Control](https://examples.aig.cloudflare.com/black-forest-labs/flux-2-max/hex-color-control.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-2-max/hex-color-control.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Image Editing** — Single-reference image editing — relight or restage a product photo</summary>



```ts
const response = await env.AI.run(
  'black-forest-labs/flux-2-max',
  {
    prompt: 'Place this product onto a minimalist marble countertop with soft window light',
    input_images: [
      'https://replicate.delivery/xezq/jCypj4MeXYUiRyq7nfgm8z1OvFZF81wh4FznutDsZOuJz0YWA/tmp1iukn307.jpg',
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-2-max",
  "input": {
    "prompt": "Place this product onto a minimalist marble countertop with soft window light",
    "input_images": [
      "https://replicate.delivery/xezq/jCypj4MeXYUiRyq7nfgm8z1OvFZF81wh4FznutDsZOuJz0YWA/tmp1iukn307.jpg"
    ]
  }
}'
```

![Image Editing](https://examples.aig.cloudflare.com/black-forest-labs/flux-2-max/image-editing.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-2-max/image-editing.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredText prompt for image generation or editing.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Optional seed for reproducible generation.

width

`integer`minimum: 64maximum: 9007199254740991Width of the generated image in pixels (minimum 64). Omit to let BFL pick.

height

`integer`minimum: 64maximum: 9007199254740991Height of the generated image in pixels (minimum 64). Omit to let BFL pick.

safety\_tolerance

`integer`minimum: 0maximum: 5Tolerance for input/output moderation. 0 is the strictest, 5 the most permissive. Defaults to 2.

output\_format

`string`enum: jpeg, png, webpOutput image format. Defaults to jpeg.

▶input\_images\[]

`array`maxItems: 8Up to 8 reference images for editing or multi-image composition. Each entry is an HTTPS URL or a data:image/...;base64,... URI.

image

`string`format: uriURL to the generated image

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-max/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-max/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-max/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-max/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-max/#page","headline":"FLUX.2 [max]","description":"FLUX.2 [max] is Black Forest Labs' highest-quality image model — top editing consistency, strongest prompt following, and grounding search for visualizations of real-time information.","url":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-max/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: FLUX.2 [pro] Preview is Black Forest Labs' recommended default for production image generation and editing — tracks the latest [pro] weights with strong multi-reference support.
title: FLUX.2 [pro]
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)

# FLUX.2 \[pro]

Text-to-Image • Black Forest Labs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-pro-preview/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`black-forest-labs/flux-2-pro-preview`

- Third-party

FLUX.2 \[pro] Preview is Black Forest Labs' recommended default for production image generation and editing — tracks the latest \[pro] weights with strong multi-reference support.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://blackforestlabs.ai/terms-of-service/) |
| More information | [link ↗](https://blackforestlabs.ai/) |
| Pricing | <ul><li>First output megapixel$0.03</li><li>Per additional output megapixel$0.015</li><li>Per input megapixel$0.015</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'black-forest-labs/flux-2-pro-preview',
  {
    prompt:
      'A serene mountain landscape at golden hour, soft diffused light filtering through clouds',
    height: 1024,
    width: 1024,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-2-pro-preview",
  "input": {
    "prompt": "A serene mountain landscape at golden hour, soft diffused light filtering through clouds",
    "height": 1024,
    "width": 1024
  }
}'
```

![Simple Prompt](https://examples.aig.cloudflare.com/black-forest-labs/flux-2-pro-preview/simple-prompt.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-2-pro-preview/simple-prompt.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Multi-Reference Editing** — Multi-reference editing — combine two reference images in a single composition</summary>



```ts
const response = await env.AI.run(
  'black-forest-labs/flux-2-pro-preview',
  {
    prompt: 'Combine the subjects of these images into a single editorial fashion scene',
    input_images: [
      'https://replicate.delivery/xezq/jCypj4MeXYUiRyq7nfgm8z1OvFZF81wh4FznutDsZOuJz0YWA/tmp1iukn307.jpg',
      'https://replicate.delivery/xezq/0lxxNQSg3NabCZrDiQVAPGVmjP1Q2dd7TgYCOTfI9LpyZaMLA/tmp89gopylq.jpg',
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-2-pro-preview",
  "input": {
    "prompt": "Combine the subjects of these images into a single editorial fashion scene",
    "input_images": [
      "https://replicate.delivery/xezq/jCypj4MeXYUiRyq7nfgm8z1OvFZF81wh4FznutDsZOuJz0YWA/tmp1iukn307.jpg",
      "https://replicate.delivery/xezq/0lxxNQSg3NabCZrDiQVAPGVmjP1Q2dd7TgYCOTfI9LpyZaMLA/tmp89gopylq.jpg"
    ]
  }
}'
```

![Multi-Reference Editing](https://examples.aig.cloudflare.com/black-forest-labs/flux-2-pro-preview/multi-reference-editing.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-2-pro-preview/multi-reference-editing.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Reproducible PNG Output** — Seeded generation with PNG output for downstream editing pipelines</summary>



```ts
const response = await env.AI.run(
  'black-forest-labs/flux-2-pro-preview',
  { prompt: 'A pastel watercolor of a koi pond at sunrise', output_format: 'png', seed: 1337 },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-2-pro-preview",
  "input": {
    "prompt": "A pastel watercolor of a koi pond at sunrise",
    "output_format": "png",
    "seed": 1337
  }
}'
```

![Reproducible PNG Output](https://examples.aig.cloudflare.com/black-forest-labs/flux-2-pro-preview/reproducible-png-output.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/black-forest-labs/flux-2-pro-preview/reproducible-png-output.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredText prompt for image generation or editing.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Optional seed for reproducible generation.

width

`integer`minimum: 64maximum: 9007199254740991Width of the generated image in pixels (minimum 64). Omit to let BFL pick.

height

`integer`minimum: 64maximum: 9007199254740991Height of the generated image in pixels (minimum 64). Omit to let BFL pick.

safety\_tolerance

`integer`minimum: 0maximum: 5Tolerance for input/output moderation. 0 is the strictest, 5 the most permissive. Defaults to 2.

output\_format

`string`enum: jpeg, png, webpOutput image format. Defaults to jpeg.

▶input\_images\[]

`array`maxItems: 8Up to 8 reference images for editing or multi-image composition. Each entry is an HTTPS URL or a data:image/...;base64,... URI.

image

`string`format: uriURL to the generated image

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-pro-preview/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-pro-preview/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-pro-preview/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-pro-preview/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-pro-preview/#page","headline":"FLUX.2 [pro]","description":"FLUX.2 [pro] Preview is Black Forest Labs' recommended default for production image generation and editing — tracks the latest [pro] weights with strong multi-reference support.","url":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-2-pro-preview/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: FLUX 3 Video is Black Forest Labs' video generation model. It generates video from a text prompt (t2v), animates one or more reference images (i2v), or continues an existing clip (v2v), with synchronized audio, up to fhd resolution, and 5-20 second durations.
title: FLUX 3 Video
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)

# FLUX 3 Video

Text-to-Video • Black Forest Labs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-3-video/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`black-forest-labs/flux-3-video`

- Third-party

FLUX 3 Video is Black Forest Labs' video generation model. It generates video from a text prompt (t2v), animates one or more reference images (i2v), or continues an existing clip (v2v), with synchronized audio, up to fhd resolution, and 5-20 second durations.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://blackforestlabs.ai/terms-of-service/) |
| More information | [link ↗](https://blackforestlabs.ai/) |
| Pricing | <ul><li>hd$0.17</li><li>fhd$0.29</li><li>v2v hd$0.41</li><li>v2v fhd$0.53</li><li>hd draft$0.06</li><li>v2v hd draft$0.12</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'black-forest-labs/flux-3-video',
  {
    mode: 't2v',
    prompt:
      'A cozy ramen shop on a rainy Tokyo night, steam rising from the broth. Rain patter and quiet kitchen sounds.',
    resolution: 'hd',
    duration: 5,
    generate_audio: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-3-video",
  "input": {
    "mode": "t2v",
    "prompt": "A cozy ramen shop on a rainy Tokyo night, steam rising from the broth. Rain patter and quiet kitchen sounds.",
    "resolution": "hd",
    "duration": 5,
    "generate_audio": true
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/black-forest-labs/flux-3-video/text-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

▶Option 1{}

object

▶Option 2{}

object

▶Option 3{}

object

video

`string`format: uriSigned URL to the generated mp4 (24fps, with audio by default). Expires \~2 hours after ready — download promptly.

draft\_cache

`string`Draft-mode cache bundle URL, only present for draft: true requests.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-3-video/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-3-video/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-3-video/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-3-video/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-3-video/#page","headline":"FLUX 3 Video","description":"FLUX 3 Video is Black Forest Labs' video generation model. It generates video from a text prompt (t2v), animates one or more reference images (i2v), or continues an existing clip (v2v), with synchronized audio, up to fhd resolution, and 5-20 second durations.","url":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-3-video/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: FLUX Video Upscale increases video resolution with a precise mode for source-faithful results and a creative mode for stronger detail enhancement. It accepts clips up to 20 seconds and preserves audio.
title: FLUX Video Upscale
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Black Forest Labs logo](https://developers.cloudflare.com/_astro/blackforestlabs.Ccs-Y4-D.svg)

# FLUX Video Upscale

video-to-video • Black Forest Labs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-video-upscale/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`black-forest-labs/flux-video-upscale`

- Third-party

FLUX Video Upscale increases video resolution with a precise mode for source-faithful results and a creative mode for stronger detail enhancement. It accepts clips up to 20 seconds and preserves audio.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://blackforestlabs.ai/terms-of-service/) |
| More information | [link ↗](https://docs.bfl.ml/flux_tools/flux_video_upscale) |
| Pricing | <ul><li>Precise (per megapixel-second)$0.07</li><li>Creative (per megapixel-second)$0.10</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'black-forest-labs/flux-video-upscale',
  {
    input_video: 'https://replicate.delivery/pbxt/PetLEVcclEkT5H9A3tYETZyAMT5GE2Sa4m6sQqPDpj8vgHga/animatediff.B572L3lv.mp4',
    upscale_factor: 2,
    creativity: 0,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-video-upscale",
  "input": {
    "input_video": "https://replicate.delivery/pbxt/PetLEVcclEkT5H9A3tYETZyAMT5GE2Sa4m6sQqPDpj8vgHga/animatediff.B572L3lv.mp4",
    "upscale_factor": 2,
    "creativity": 0
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/black-forest-labs/flux-video-upscale/precise-video-upscale.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Creative Video Upscale** — Enhance fine detail in a source clip using creative mode.</summary>



```ts
const response = await env.AI.run(
  'black-forest-labs/flux-video-upscale',
  {
    input_video: 'https://replicate.delivery/xezq/q1XccP3m8V4HMBNDY3LBkaiKjPdJ6e7t74ICqq2wbfWHJNFXA/tmpq8inl7pd.mp4',
    upscale_factor: 2,
    creativity: 1,
    prompt: 'A cinematic travel video with detailed natural scenery and crisp texture',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "black-forest-labs/flux-video-upscale",
  "input": {
    "input_video": "https://replicate.delivery/xezq/q1XccP3m8V4HMBNDY3LBkaiKjPdJ6e7t74ICqq2wbfWHJNFXA/tmpq8inl7pd.mp4",
    "upscale_factor": 2,
    "creativity": 1,
    "prompt": "A cinematic travel video with detailed natural scenery and crisp texture"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/black-forest-labs/flux-video-upscale/creative-video-upscale.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

input\_video

`string`requiredHTTP(S) URL or base64-encoded MP4 video, up to 20 seconds and 50MB.

upscale\_factor

`number`minimum: 1.5maximum: 3Output scale relative to the source resolution, from 1.5x to 3x.

▶creativity

`one of`

prompt

`string`Optional description of the clip to guide creative detail enhancement.

safety\_tolerance

`integer`minimum: 0maximum: 4Moderation strictness, from 0 (strictest) to 4.

video

`string`format: uriSigned URL to the upscaled MP4. Download promptly before it expires.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-video-upscale/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-video-upscale/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-video-upscale/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/black-forest-labs/flux-video-upscale/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-video-upscale/#page","headline":"FLUX Video Upscale","description":"FLUX Video Upscale increases video resolution with a precise mode for source-faithful results and a creative mode for stronger detail enhancement. It accepts clips up to 20 seconds and preserves audio.","url":"https://developers.cloudflare.com/ai/models/black-forest-labs/flux-video-upscale/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: FIBO Edit changes one to four input images from a natural-language or structured JSON (VGL) instruction. Add a black-and-white mask to edit only part of a single image, or refer to several images as &quot;image 1&quot;, &quot;image 2&quot;, and so on to combine them or transfer a style.
title: FIBO Edit 1.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

b

# FIBO Edit 1.5

Image-to-Image • bria

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bria/fibo-edit-1.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bria/fibo-edit-1.5`

- Third-party

FIBO Edit changes one to four input images from a natural-language or structured JSON (VGL) instruction. Add a black-and-white mask to edit only part of a single image, or refer to several images as "image 1", "image 2", and so on to combine them or transfer a style.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://bria.ai/terms-of-use) |
| More information | [link ↗](https://docs.bria.ai/image-editing/editing/edit-image) |
| Pricing | <ul><li>Per image$0.03</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bria/fibo-edit-1.5',
  {
    instruction:
      'Change the color palette of the image to #014040, #02735E, #03A678, #F27405, and #731702',
    images: [
      'https://bria-datasets.s3.us-east-1.amazonaws.com/api_doc/fibo-edit/pexels-cottonbro-3401900.jpg',
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bria/fibo-edit-1.5",
  "input": {
    "instruction": "Change the color palette of the image to #014040, #02735E, #03A678, #F27405, and #731702",
    "images": [
      "https://bria-datasets.s3.us-east-1.amazonaws.com/api_doc/fibo-edit/pexels-cottonbro-3401900.jpg"
    ]
  }
}'
```

![Color Palette](https://examples.aig.cloudflare.com/bria/fibo-edit-1.5/color-palette.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/bria/fibo-edit-1.5/color-palette.png",
    "seed": 3749705
  }
}
```

## Examples

<details>

<summary>**Masked Edit** — Edit only the masked balloons: white areas of the mask are edited and black areas are kept. Adapted from Bria's docs.</summary>



```ts
const response = await env.AI.run(
  'bria/fibo-edit-1.5',
  {
    instruction:
      'Write PARTY on the balloons in a dark, playful font, using a different font for each balloon',
    images: [
      'https://bria-datasets.s3.us-east-1.amazonaws.com/api_doc/fibo-edit/pexels-natalie-bond-320378-3371094.jpg',
    ],
    mask: 'https://bria-datasets.s3.us-east-1.amazonaws.com/api_doc/fibo-edit/pexels-natalie-bond-320378-3371094_mask.png',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bria/fibo-edit-1.5",
  "input": {
    "instruction": "Write PARTY on the balloons in a dark, playful font, using a different font for each balloon",
    "images": [
      "https://bria-datasets.s3.us-east-1.amazonaws.com/api_doc/fibo-edit/pexels-natalie-bond-320378-3371094.jpg"
    ],
    "mask": "https://bria-datasets.s3.us-east-1.amazonaws.com/api_doc/fibo-edit/pexels-natalie-bond-320378-3371094_mask.png"
  }
}'
```

![Masked Edit](https://examples.aig.cloudflare.com/bria/fibo-edit-1.5/masked-edit.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/bria/fibo-edit-1.5/masked-edit.png",
    "seed": 912468565
  }
}
```

</details>

<details>

<summary>**Multi-Image Style Transfer** — Restyle the first image in the style of the second. Both inputs are Nano Banana catalog examples.</summary>



```ts
const response = await env.AI.run(
  'bria/fibo-edit-1.5',
  {
    instruction:
      'Redraw image 1 in the pixel art style of image 2. Keep the armchair, the sleeping cat, and the hanging plants.',
    images: [
      'https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/cozy-coffee-shop.png',
      'https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/pixel-art-marketplace.png',
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bria/fibo-edit-1.5",
  "input": {
    "instruction": "Redraw image 1 in the pixel art style of image 2. Keep the armchair, the sleeping cat, and the hanging plants.",
    "images": [
      "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/cozy-coffee-shop.png",
      "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/pixel-art-marketplace.png"
    ]
  }
}'
```

![Multi-Image Style Transfer](https://examples.aig.cloudflare.com/bria/fibo-edit-1.5/multi-image-style-transfer.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/bria/fibo-edit-1.5/multi-image-style-transfer.png",
    "seed": 1523838269
  }
}
```

</details>

## Parameters

▶images\[]

`array`requiredminItems: 1maxItems: 4One to four input images, each a public URL or base64-encoded image data (a \`data:\` URI prefix is accepted). Refer to them in the instruction as "image 1", "image 2", and so on.

instruction

`string`minLength: 1Edit instruction in natural language. Provide this or \`structured\_instruction\`.

structured\_instruction

`string`minLength: 1Structured (VGL) edit instruction as a JSON string, as returned by a previous result. Provide this or \`instruction\`.

mask

`string`minLength: 1Black-and-white mask the same size as the input image, a public URL or base64-encoded image data (a \`data:\` URI prefix is accepted). White areas are edited and black areas are kept. Only allowed with a single input image.

aspect\_ratio

`string`enum: 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9Output aspect ratio. Defaults to the aspect ratio of the first input image.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Seed for reproducible results.

output\_type

`string`enum: png, jpegOutput image format. Default png.

ip\_signal

`boolean`When true, the result carries a \`warning\` if the text input may reference IP-protected content. Default false.

prompt\_content\_moderation

`boolean`Reject the request if the instruction fails content moderation. Default true.

visual\_input\_content\_moderation

`boolean`Reject the request if an input image or the mask fails content moderation. Default true.

visual\_output\_content\_moderation

`boolean`Fail the request if the edited image fails content moderation. Default true.

image

`string`format: uriURL of the edited image. Bria hosts it for a limited time (3 days by default); download it to keep it.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Seed used for this image.

structured\_instruction

`string`Structured (VGL) edit instruction used for this image, as a JSON string.

warning

`string`Present when \`ip\_signal\` flagged the instruction as possibly IP-protected.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bria/fibo-edit-1.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bria/fibo-edit-1.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bria/fibo-edit-1.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bria/fibo-edit-1.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bria/fibo-edit-1.5/#page","headline":"FIBO Edit 1.5","description":"FIBO Edit changes one to four input images from a natural-language or structured JSON (VGL) instruction. Add a black-and-white mask to edit only part of a single image, or refer to several images as \"image 1\", \"image 2\", and so on to combine them or transfer a style.","url":"https://developers.cloudflare.com/ai/models/bria/fibo-edit-1.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: FIBO Generate creates images from a text prompt, a reference image, or both. Each result includes the seed and the structured JSON (VGL) prompt used to render it; send them back to recreate the image exactly or to refine it with a new prompt. Outputs are 1MP or 4MP in nine aspect ratios.
title: FIBO Generate 1.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

b

# FIBO Generate 1.5

Text-to-Image • bria

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bria/fibo-generate-1.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bria/fibo-generate-1.5`

- Third-party

FIBO Generate creates images from a text prompt, a reference image, or both. Each result includes the seed and the structured JSON (VGL) prompt used to render it; send them back to recreate the image exactly or to refine it with a new prompt. Outputs are 1MP or 4MP in nine aspect ratios.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://bria.ai/terms-of-use) |
| More information | [link ↗](https://docs.bria.ai/image-generation/generation/image-generate) |
| Pricing | <ul><li>Per image$0.03</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bria/fibo-generate-1.5',
  {
    prompt:
      'studio product photo of a matte black insulated travel mug on a white seamless background, soft diffused key light from the upper left, crisp edges',
    aspect_ratio: '1:1',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bria/fibo-generate-1.5",
  "input": {
    "prompt": "studio product photo of a matte black insulated travel mug on a white seamless background, soft diffused key light from the upper left, crisp edges",
    "aspect_ratio": "1:1"
  }
}'
```

![Product Photo](https://examples.aig.cloudflare.com/bria/fibo-generate-1.5/product-photo.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/bria/fibo-generate-1.5/product-photo.png",
    "seed": 1528689072,
    "structured_prompt": "{\"short_description\": \"A meticulously composed studio product photograph of a matte black insulated travel mug. The mug stands prominently on a pristine white seamless background, highlighted by soft, diffused key lighting from the upper left, emphasizing its sleek design and crisp edges. The image conveys a sense of modern simplicity and sophisticated utility.\", \"objects\": [{\"description\": \"A modern, insulated travel mug with a minimalist design. It features a cylindrical body that tapers slightly towards the top, with a secure, leak-proof lid. The matte black finish absorbs light, giving it a premium, non-reflective appearance.\", \"location\": \"center\", \"relationship\": \"The primary subject of the photograph, centrally positioned to draw immediate attention.\", \"relative_size\": \"large within frame\", \"shape_and_color\": \"Cylindrical, matte black\", \"texture\": \"Smooth, non-reflective matte finish\", \"appearance_details\": \"Subtle branding logo debossed near the bottom, barely visible due to the matte finish and lighting. The lid is also matte black, with a small, integrated sip opening.\", \"orientation\": \"Upright, perfectly vertical\"}], \"background_setting\": \"A pristine, pure white seamless studio background that creates an infinite, shadow-free horizon, ensuring the product stands out without distractions.\", \"lighting\": {\"conditions\": \"Studio lighting, soft and diffused\", \"direction\": \"Key light from the upper left, fill light from the right to minimize harsh shadows\", \"shadows\": \"Very soft, subtle shadow cast directly beneath and slightly to the right of the mug, providing just enough depth without being distracting. Edges are crisp and well-defined.\"}, \"aesthetics\": {\"composition\": \"Centered, product photography composition, emphasizing symmetry and clean lines.\", \"color_scheme\": \"Monochromatic with high contrast between the matte black mug and the pure white background.\", \"mood_atmosphere\": \"Clean, sophisticated, modern, and minimalist.\", \"aesthetic_score\": \"very high\", \"preference_score\": \"very high\"}, \"photographic_characteristics\": {\"depth_of_field\": \"Shallow, with the mug in sharp focus and the background completely blurred into an abstract white field.\", \"focus\": \"Sharp focus on the entire travel mug, highlighting its crisp edges and surface details.\", \"camera_angle\": \"Eye-level, slightly elevated to showcase the top edge of the lid.\", \"lens_focal_length\": \"Standard lens (e.g., 50mm-85mm) to avoid distortion and accurately represent the product.\"}, \"style_medium\": \"photograph\", \"context\": \"This is a product marketing photograph intended for e-commerce websites, print catalogs, or advertising campaigns, designed to showcase the quality and aesthetic appeal of the travel mug.\", \"artistic_style\": \"realistic\"}"
  }
}
```

## Examples

<details>

<summary>**Reference Image** — Generate a new piece of jewelry inspired by a reference photo, from Bria's docs.</summary>



```ts
const response = await env.AI.run(
  'bria/fibo-generate-1.5',
  {
    prompt: 'a ring inspired by the image',
    images: ['https://bria-datasets.s3.us-east-1.amazonaws.com/api_doc/fibo/ref_1.jpg'],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bria/fibo-generate-1.5",
  "input": {
    "prompt": "a ring inspired by the image",
    "images": [
      "https://bria-datasets.s3.us-east-1.amazonaws.com/api_doc/fibo/ref_1.jpg"
    ]
  }
}'
```

![Reference Image](https://examples.aig.cloudflare.com/bria/fibo-generate-1.5/reference-image.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/bria/fibo-generate-1.5/reference-image.png",
    "seed": 120559985,
    "structured_prompt": "{\"short_description\": \"A close-up photograph of an elegant ring featuring a teardrop-shaped ruby set in a thick, curb-chain inspired gold band. The ring is positioned on a smooth, light-colored surface, with soft, diffused lighting highlighting its intricate details and the gem's vibrant color.\", \"objects\": [{\"description\": \"An elegant ring with a prominent teardrop-shaped ruby gemstone. The band of the ring is crafted from polished gold, designed to resemble a thick, interlocked curb chain, giving it a modern yet classic aesthetic. The ruby is securely set in a gold bezel, allowing light to pass through and enhance its deep red hue.\", \"location\": \"center\", \"relationship\": \"The central focus of the image, resting on a smooth surface.\", \"relative_size\": \"large within frame\", \"shape_and_color\": \"Irregular shape with a teardrop red gem and a golden band.\", \"texture\": \"Smooth, polished metal and faceted, glassy gemstone.\", \"appearance_details\": \"The gold band has distinct, interlocked links, mimicking a curb chain. The ruby is a rich, translucent red with visible facets.\", \"orientation\": \"Slightly angled, with the teardrop point facing towards the bottom-right.\"}], \"background_setting\": \"A minimalist, light-colored, smooth surface, possibly a tabletop or a display stand, providing a clean and uncluttered backdrop that allows the ring to stand out. There are no other distracting elements in the background.\", \"lighting\": {\"conditions\": \"Soft, diffused studio lighting\", \"direction\": \"Evenly lit from above and slightly to the front\", \"shadows\": \"Subtle, soft shadows directly beneath the ring, indicating depth without harshness.\"}, \"aesthetics\": {\"composition\": \"Centered, close-up shot, with the ring occupying a significant portion of the frame.\", \"color_scheme\": \"Warm complementary colors, with the rich red of the ruby contrasting with the golden band and the neutral, light background.\", \"mood_atmosphere\": \"Elegant, luxurious, and sophisticated.\", \"aesthetic_score\": \"very high\", \"preference_score\": \"very high\"}, \"photographic_characteristics\": {\"depth_of_field\": \"Shallow, with the ring in sharp focus and the background slightly blurred to isolate the subject.\", \"focus\": \"Sharp focus on subject\", \"camera_angle\": \"Slightly high angle, looking down at the ring.\", \"lens_focal_length\": \"Macro\"}, \"style_medium\": \"photograph\", \"context\": \"This is a concept for a high-end jewelry product photograph, suitable for an e-commerce website, a luxury catalog, or a fashion magazine advertisement.\", \"artistic_style\": \"realistic\"}"
  }
}
```

</details>

<details>

<summary>**4MP Landscape** — Generate a widescreen image at 4MP. 4MP adds about 30 seconds of latency compared with 1MP.</summary>



```ts
const response = await env.AI.run(
  'bria/fibo-generate-1.5',
  {
    prompt:
      'aerial view of a winding river through an autumn forest at golden hour, mist rising from the water, highly detailed',
    resolution: '4MP',
    aspect_ratio: '16:9',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bria/fibo-generate-1.5",
  "input": {
    "prompt": "aerial view of a winding river through an autumn forest at golden hour, mist rising from the water, highly detailed",
    "resolution": "4MP",
    "aspect_ratio": "16:9"
  }
}'
```

![4MP Landscape](https://examples.aig.cloudflare.com/bria/fibo-generate-1.5/4mp-landscape.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/bria/fibo-generate-1.5/4mp-landscape.png",
    "seed": 1535063202,
    "structured_prompt": "{\"short_description\": \"An aerial view of a winding river meandering through a dense autumn forest during the golden hour. Soft mist gently rises from the water's surface, illuminated by the warm, low-angle sunlight, highlighting the vibrant reds, oranges, and yellows of the fall foliage. The scene is highly detailed, capturing the intricate patterns of the trees and the river's flow.\", \"objects\": [{\"description\": \"A wide, winding river, appearing as a dark, reflective ribbon cutting through the forest. Its surface is smooth in some areas, with subtle ripples in others, and a delicate mist hovers just above it.\", \"location\": \"center, extending from foreground to background\", \"relationship\": \"The central element, guiding the eye through the forest.\", \"relative_size\": \"large within frame\", \"shape_and_color\": \"Irregular, sinuous shape; dark blue-green with golden reflections.\", \"texture\": \"Smooth, reflective water with soft, wispy mist.\", \"appearance_details\": \"Reflects the golden light of the sky, creating shimmering streaks.\", \"orientation\": \"Flowing from bottom-right to top-left, then curving through the scene.\"}, {\"description\": \"Dense clusters of deciduous trees, showcasing a spectacular array of autumn colors. Each tree is individually distinguishable, contributing to the rich tapestry of the forest.\", \"location\": \"surrounding the river, filling the midground and background\", \"relationship\": \"Form the main environment through which the river flows, providing a vibrant contrast.\", \"relative_size\": \"large within frame\", \"shape_and_color\": \"Varied organic shapes; predominantly red, orange, yellow, and some lingering green.\", \"texture\": \"Rough, textured canopy with individual leaves visible.\", \"appearance_details\": \"Leaves are illuminated from above, creating a glowing effect.\", \"orientation\": \"Upright, forming a continuous canopy.\"}, {\"description\": \"Thin, ethereal wisps of mist gently rising from the cool surface of the river, catching the golden light.\", \"location\": \"directly above the river\", \"relationship\": \"Intertwined with the river, enhancing the atmospheric quality.\", \"relative_size\": \"small to medium within frame\", \"shape_and_color\": \"Amorphous, transparent white.\", \"texture\": \"Soft, translucent, and diffuse.\", \"appearance_details\": \"Subtly glows with the warm light, creating a mystical effect.\", \"orientation\": \"Rising vertically and drifting gently.\"}], \"background_setting\": \"The forest extends into the horizon, appearing as a vast, undulating carpet of autumn colors. The distant sky, partially visible, shows a soft, hazy golden glow typical of late afternoon.\", \"lighting\": {\"conditions\": \"Golden hour sunlight, low and warm.\", \"direction\": \"Side-lit from the upper left, casting long, soft highlights.\", \"shadows\": \"Long, soft shadows are cast by the trees, stretching across the forest floor and partially obscuring some areas, adding depth and contrast. The mist catches the light, reducing some shadow intensity over the river.\"}, \"aesthetics\": {\"composition\": \"Leading lines created by the winding river, drawing the viewer's eye through the vast landscape. The composition is balanced with the river as a central element.\", \"color_scheme\": \"Warm complementary colors, dominated by rich oranges, reds, and yellows against the cool blues and greens of the river and deeper forest areas.\", \"mood_atmosphere\": \"Serene, majestic, ethereal, and tranquil.\", \"aesthetic_score\": \"very high\", \"preference_score\": \"very high\"}, \"photographic_characteristics\": {\"depth_of_field\": \"Deep, ensuring clarity from the foreground river to the distant forest.\", \"focus\": \"Sharp focus throughout the entire scene, emphasizing the high detail.\", \"camera_angle\": \"High aerial view, directly overhead but slightly angled to show the river's flow and forest depth.\", \"lens_focal_length\": \"Wide-angle, to capture the expansive landscape.\"}, \"style_medium\": \"photograph\", \"context\": \"This is a concept for a high-resolution landscape photograph, ideal for nature documentaries, travel magazines, or fine art prints, capturing the breathtaking beauty of autumn from an aerial perspective.\", \"artistic_style\": \"realistic\"}"
  }
}
```

</details>

## Parameters

prompt

`string`minLength: 1Text prompt. Use alone, with \`images\` as a reference, or with \`structured\_prompt\` to refine a previous result.

▶images\[]

`array`minItems: 1maxItems: 1One reference image: a public URL or base64-encoded image data (a \`data:\` URI prefix is accepted).

structured\_prompt

`string`minLength: 1Structured (VGL) prompt as a JSON string, as returned by a previous result. Recreates that image with the same \`seed\`; add \`prompt\` to refine it. Cannot be combined with \`images\`.

resolution

`string`enum: 1MP, 4MPOutput resolution. 4MP adds about 30 seconds of latency. Default 1MP.

aspect\_ratio

`string`enum: 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9Output aspect ratio. Default 1:1.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Seed for reproducible results. Pass the seed of a previous result with its \`structured\_prompt\` to recreate or refine it.

output\_type

`string`enum: png, jpegOutput image format. Default png.

ip\_signal

`boolean`When true, the result carries a \`warning\` if the text input may reference IP-protected content. Default false.

prompt\_content\_moderation

`boolean`Reject the request if the prompt fails content moderation. Default true.

visual\_input\_content\_moderation

`boolean`Reject the request if the reference image fails content moderation. Default true.

visual\_output\_content\_moderation

`boolean`Fail the request if the generated image fails content moderation. Default true.

image

`string`format: uriURL of the generated image. Bria hosts it for a limited time (3 days by default); download it to keep it.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Seed used for this image.

structured\_prompt

`string`Structured (VGL) prompt used for this image, as a JSON string. Pass it back with \`seed\` to recreate or refine the image.

warning

`string`Present when \`ip\_signal\` flagged the prompt as possibly IP-protected.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bria/fibo-generate-1.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bria/fibo-generate-1.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bria/fibo-generate-1.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bria/fibo-generate-1.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bria/fibo-generate-1.5/#page","headline":"FIBO Generate 1.5","description":"FIBO Generate creates images from a text prompt, a reference image, or both. Each result includes the seed and the structured JSON (VGL) prompt used to render it; send them back to recreate the image exactly or to refine it with a new prompt. Outputs are 1MP or 4MP in nine aspect ratios.","url":"https://developers.cloudflare.com/ai/models/bria/fibo-generate-1.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Bria's RMBG 2.0 model removes the background from an image and returns a PNG cutout with a transparent background. Partial transparency from the input's alpha channel is kept by default.
title: Remove Background
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

b

# Remove Background

Image-to-Image • bria

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bria/remove-background/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bria/remove-background`

- Third-party

Bria's RMBG 2.0 model removes the background from an image and returns a PNG cutout with a transparent background. Partial transparency from the input's alpha channel is kept by default.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://bria.ai/terms-of-use) |
| More information | [link ↗](https://docs.bria.ai/image-editing/editing/background-remove) |
| Pricing | <ul><li>Per image$0.018</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bria/remove-background',
  { image: 'https://labs-assets.bria.ai/sandbox-example-inputs/remove_background_example.jpg' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bria/remove-background",
  "input": {
    "image": "https://labs-assets.bria.ai/sandbox-example-inputs/remove_background_example.jpg"
  }
}'
```

![Portrait Cutout](https://examples.aig.cloudflare.com/bria/remove-background/portrait-cutout.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/bria/remove-background/portrait-cutout.png"
  }
}
```

## Parameters

image

`string`requiredminLength: 1JPEG or PNG image (RGB, RGBA, or CMYK), a public URL or base64-encoded image data (a \`data:\` URI prefix is accepted).

preserve\_alpha

`boolean`Keep partial transparency from the input alpha channel. When false, every foreground pixel is fully opaque. Default true.

visual\_input\_content\_moderation

`boolean`Reject the request if the input image fails content moderation. Default false.

visual\_output\_content\_moderation

`boolean`Fail the request if the result fails content moderation. Default false.

image

`string`format: uriURL of the PNG cutout with a transparent background. Bria hosts it for a limited time (3 days by default); download it to keep it.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bria/remove-background/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bria/remove-background/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bria/remove-background/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bria/remove-background/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bria/remove-background/#page","headline":"Remove Background","description":"Bria's RMBG 2.0 model removes the background from an image and returns a PNG cutout with a transparent background. Partial transparency from the input's alpha channel is kept by default.","url":"https://developers.cloudflare.com/ai/models/bria/remove-background/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Bria's video background removal replaces the background of a clip up to 60 seconds long with a solid color or with transparency. Transparent output needs the mov_proresks (ProRes) preset. Frame rate and audio are preserved, and the output resolution matches the input unless auto_zoom crops to the subject.
title: Video Remove Background 3.0
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

b

# Video Remove Background 3.0

video-to-video • bria

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bria/v-rmbg-3.0/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bria/v-rmbg-3.0`

- Third-party

Bria's video background removal replaces the background of a clip up to 60 seconds long with a solid color or with transparency. Transparent output needs the mov\_proresks (ProRes) preset. Frame rate and audio are preserved, and the output resolution matches the input unless auto\_zoom crops to the subject.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://bria.ai/terms-of-use) |
| More information | [link ↗](https://docs.bria.ai/video-editing/editing/remove-background) |
| Pricing | <ul><li>Default (per second)$0.0225</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bria/v-rmbg-3.0',
  {
    video:
      'https://labs-assets.bria.ai/sandbox-example-inputs/5586521-uhd_3840_2160_25fps_original.mp4',
    background_color: 'White',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bria/v-rmbg-3.0",
  "input": {
    "video": "https://labs-assets.bria.ai/sandbox-example-inputs/5586521-uhd_3840_2160_25fps_original.mp4",
    "background_color": "White"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bria/v-rmbg-3.0/white-background.mp4"
  }
}
```

## Parameters

video

`string`requiredformat: uriPublic URL of the input video: MP4, MOV, WEBM, AVI, or GIF, up to 60 seconds and 16000x16000.

background\_color

`string`enum: Transparent, Black, White, Gray, Red, Green, Blue, Yellow, Cyan, Magenta, OrangeColor that replaces the removed background; set it explicitly. Transparent needs the mov\_proresks preset: with any other preset Bria uses Black and returns a \`warning\`.

output\_container\_and\_codec

`string`enum: mp4\_h264, mp4\_h265, mov\_h265, mov\_proresksOutput container and codec. Default mp4\_h264. mov\_proresks (ProRes) is the preset that keeps transparency.

auto\_zoom

`boolean`Crop once to the subject for the whole video. Output resolution and aspect ratio may change, and processing is slower. Default false.

preserve\_audio

`boolean`Keep the input audio track. Default true.

spill\_suppression

`number`minimum: 0maximum: 1Strength of green-fringe removal for green-screen footage, from 0 (off) to 1. Default 0.

video

`string`format: uriURL of the processed video.

warning

`string`Present when Bria adjusted the request, such as a Transparent background with a preset that has no alpha channel.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bria/v-rmbg-3.0/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bria/v-rmbg-3.0/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bria/v-rmbg-3.0/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bria/v-rmbg-3.0/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bria/v-rmbg-3.0/#page","headline":"Video Remove Background 3.0","description":"Bria's video background removal replaces the background of a clip up to 60 seconds long with a solid color or with transparency. Transparent output needs the mov_proresks (ProRes) preset. Frame rate and audio are preserved, and the output resolution matches the input unless auto_zoom crops to the subject.","url":"https://developers.cloudflare.com/ai/models/bria/v-rmbg-3.0/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: ByteDance's next-generation video model with a unified multimodal architecture. Generates high-quality video with synchronized audio from text, images, video clips, and audio inputs. Supports multimodal references (up to 9 images, 3 videos, 3 audio files), native audio generation, video editing, video extension, intelligent duration, and adaptive aspect ratio.
title: Seedance 2.0
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)

# Seedance 2.0

Text-to-Video • ByteDance

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bytedance/seedance-2.0`

- Third-party

ByteDance's next-generation video model with a unified multimodal architecture. Generates high-quality video with synchronized audio from text, images, video clips, and audio inputs. Supports multimodal references (up to 9 images, 3 videos, 3 audio files), native audio generation, video editing, video extension, intelligent duration, and adaptive aspect ratio.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://seed.bytedance.com/en/seedance2_0) |
| Pricing | <ul><li>Default (per second)$0.15</li><li>@480p video input (per second)$0.172</li><li>@720p video input (per second)$0.372</li><li>@1080p video input (per second)$0.914</li><li>@4k video input (per second)$1.866</li><li>@480p non-video input (per second)$0.07</li><li>@720p non-video input (per second)$0.15</li><li>@1080p non-video input (per second)$0.37</li><li>@4k non-video input (per second)$0.78</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0',
  {
    prompt: 'A golden retriever running through a field of sunflowers on a sunny day',
    aspect_ratio: '16:9',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0",
  "input": {
    "prompt": "A golden retriever running through a field of sunflowers on a sunny day",
    "aspect_ratio": "16:9",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0/simple-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**High Resolution Cinematic** — Cinematic video in 1080p</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0',
  {
    prompt:
      'A dramatic drone shot flying through misty mountain peaks at sunrise, cinematic lighting with volumetric fog',
    aspect_ratio: '16:9',
    duration: 10,
    resolution: '1080p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0",
  "input": {
    "prompt": "A dramatic drone shot flying through misty mountain peaks at sunrise, cinematic lighting with volumetric fog",
    "aspect_ratio": "16:9",
    "duration": 10,
    "resolution": "1080p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0/high-resolution-cinematic.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Image to Video** — Generate video from a reference image</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0',
  {
    image:
      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAnklEQVR42u2XQRLAIAgD8/839i/26qFCACm0ozPe1KwcQsAoXvgcAABxpwFowl4QWITHxW0LCBhxVngF4gKIirMQyBRnIJAtrkE8AuwWnyFEgKzfS1UA+3sWTju3BGAu7gKYIfBW+Q/AAQgBeMCkt1wVsLZjcwUYG2Z9wGLHZitWk1DEisubUYt2XB5IWkSyFqG0RSxvMZi0Gc1+Ox3fm00ZJ5mGVtkAAAAASUVORK5CYII=',
    prompt: 'The character begins walking forward through the scene',
    aspect_ratio: '16:9',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0",
  "input": {
    "image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAnklEQVR42u2XQRLAIAgD8/839i/26qFCACm0ozPe1KwcQsAoXvgcAABxpwFowl4QWITHxW0LCBhxVngF4gKIirMQyBRnIJAtrkE8AuwWnyFEgKzfS1UA+3sWTju3BGAu7gKYIfBW+Q/AAQgBeMCkt1wVsLZjcwUYG2Z9wGLHZitWk1DEisubUYt2XB5IWkSyFqG0RSxvMZi0Gc1+Ox3fm00ZJ5mGVtkAAAAASUVORK5CYII=",
    "prompt": "The character begins walking forward through the scene",
    "aspect_ratio": "16:9",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0/image-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Portrait Video** — Vertical video for social media</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0',
  {
    prompt: 'Abstract ink drops spreading through water, vivid colors mixing in slow motion',
    aspect_ratio: '9:16',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0",
  "input": {
    "prompt": "Abstract ink drops spreading through water, vivid colors mixing in slow motion",
    "aspect_ratio": "9:16",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0/portrait-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**4K Cinematic Video** — Generate a detailed cinematic video in 4K</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0',
  {
    prompt:
      'A sweeping cinematic shot of a futuristic city skyline at dusk, flying past glass towers with neon reflections and dramatic clouds',
    aspect_ratio: '16:9',
    duration: 5,
    resolution: '4k',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0",
  "input": {
    "prompt": "A sweeping cinematic shot of a futuristic city skyline at dusk, flying past glass towers with neon reflections and dramatic clouds",
    "aspect_ratio": "16:9",
    "duration": 5,
    "resolution": "4k"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0/4k-cinematic-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Virtual Avatar Reference** — Use a virtual character avatar from the trusted asset library</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0',
  {
    image: 'https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg',
    prompt: 'The scene gently animates with subtle motion',
    aspect_ratio: '16:9',
    duration: 5,
    resolution: '720p',
    use_virtual_avatar: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0",
  "input": {
    "image": "https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg",
    "prompt": "The scene gently animates with subtle motion",
    "aspect_ratio": "16:9",
    "duration": 5,
    "resolution": "720p",
    "use_virtual_avatar": true
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0/virtual-avatar-reference.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredmaxLength: 2000Text prompt describing the video to generate

image

`string`Reference image (HTTP(S) URL or base64 data URI) for image-to-video

reference\_video

`string`Reference video (HTTP(S) URL or base64 data URI) for style/motion guidance

last\_frame\_image

`string`Reference image (HTTP(S) URL or base64 data URI) for last-frame guidance. Only works if an image start frame is also given.

▶reference\_images\[]

`array`maxItems: 4Reference images (1-4, HTTP(S) URLs or base64 data URIs) to guide video generation for characters, avatars, clothing, or environments. Cannot be used with 1080p resolution or first/last frame images.

duration

`integer`requireddefault: 5minimum: 4maximum: 12Video duration in seconds

resolution

`string`requireddefault: 720penum: 480p, 720p, 1080p, 4kVideo resolution

aspect\_ratio

`string`requireddefault: 16:9enum: 16:9, 4:3, 1:1, 3:4, 9:16, 21:9, 9:21Video aspect ratio. Ignored if an image is used.

fps

`number`requireddefault: 24const: 24Frame rate (frames per second)

camera\_fixed

`boolean`requireddefault: falseWhether to fix camera position

generate\_audio

`boolean`Whether to generate audio with the video

watermark

`boolean`requireddefault: falseWhether to add a watermark to the output video

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Random seed for reproducible generation

use\_virtual\_avatar

`boolean`requireddefault: falseRoute image reference inputs (image, reference\_images, last\_frame\_image) through ByteDance's trusted virtual avatar asset library before generation. Intended for AI-generated/virtual character avatars that would otherwise be blocked by face or deepfake detection

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0/#page","headline":"Seedance 2.0","description":"ByteDance's next-generation video model with a unified multimodal architecture. Generates high-quality video with synchronized audio from text, images, video clips, and audio inputs. Supports multimodal references (up to 9 images, 3 videos, 3 audio files), native audio generation, video editing, video extension, intelligent duration, and adaptive aspect ratio.","url":"https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Faster variant of ByteDance's Seedance 2.0 video model. Trades some quality for speed while sharing the same multimodal architecture. Supports text-to-video, image-to-video, native audio generation, multimodal references (images, videos, audio), video editing, and video extension.
title: Seedance 2.0 Fast
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)

# Seedance 2.0 Fast

Text-to-Video • ByteDance

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-fast/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bytedance/seedance-2.0-fast`

- Third-party

Faster variant of ByteDance's Seedance 2.0 video model. Trades some quality for speed while sharing the same multimodal architecture. Supports text-to-video, image-to-video, native audio generation, multimodal references (images, videos, audio), video editing, and video extension.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://seed.bytedance.com/en/seedance) |
| Pricing | <ul><li>Default (per second)$0.12</li><li>@480p video input (per second)$0.132</li><li>@720p video input (per second)$0.286</li><li>@480p non-video input (per second)$0.06</li><li>@720p non-video input (per second)$0.12</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0-fast',
  {
    prompt: 'A golden retriever running through a field of sunflowers on a sunny day',
    aspect_ratio: '16:9',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0-fast",
  "input": {
    "prompt": "A golden retriever running through a field of sunflowers on a sunny day",
    "aspect_ratio": "16:9",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0-fast/quick-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Portrait Video** — Vertical video for social media</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0-fast',
  {
    prompt: 'A barista pouring latte art in a cozy coffee shop, close-up with shallow depth of field',
    aspect_ratio: '9:16',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0-fast",
  "input": {
    "prompt": "A barista pouring latte art in a cozy coffee shop, close-up with shallow depth of field",
    "aspect_ratio": "9:16",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0-fast/portrait-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Virtual Avatar Reference** — Use a virtual character avatar from the trusted asset library</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0-fast',
  {
    image: 'https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg',
    prompt: 'The scene gently animates with subtle motion',
    aspect_ratio: '16:9',
    duration: 5,
    resolution: '720p',
    use_virtual_avatar: true,
    generate_audio: false,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0-fast",
  "input": {
    "image": "https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg",
    "prompt": "The scene gently animates with subtle motion",
    "aspect_ratio": "16:9",
    "duration": 5,
    "resolution": "720p",
    "use_virtual_avatar": true,
    "generate_audio": false
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0-fast/virtual-avatar-reference.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredmaxLength: 2000Text prompt describing the video to generate

image

`string`Reference image (HTTP(S) URL or base64 data URI) for image-to-video

reference\_video

`string`Reference video (HTTP(S) URL or base64 data URI) for style/motion guidance

last\_frame\_image

`string`Reference image (HTTP(S) URL or base64 data URI) for last-frame guidance. Only works if an image start frame is also given.

▶reference\_images\[]

`array`maxItems: 4Reference images (1-4, HTTP(S) URLs or base64 data URIs) to guide video generation for characters, avatars, clothing, or environments. Cannot be used with first/last frame images.

duration

`integer`requireddefault: 5minimum: 4maximum: 12Video duration in seconds

resolution

`string`requireddefault: 720penum: 480p, 720pVideo resolution

aspect\_ratio

`string`requireddefault: 16:9enum: 16:9, 4:3, 1:1, 3:4, 9:16, 21:9, 9:21Video aspect ratio. Ignored if an image is used.

fps

`number`requireddefault: 24const: 24Frame rate (frames per second)

camera\_fixed

`boolean`requireddefault: falseWhether to fix camera position

generate\_audio

`boolean`Whether to generate audio with the video

watermark

`boolean`requireddefault: falseWhether to add a watermark to the output video

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Random seed for reproducible generation

use\_virtual\_avatar

`boolean`requireddefault: falseRoute image reference inputs (image, reference\_images, last\_frame\_image) through ByteDance's trusted virtual avatar asset library before generation. Intended for AI-generated/virtual character avatars that would otherwise be blocked by face or deepfake detection

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-fast/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-fast/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-fast/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-fast/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-fast/#page","headline":"Seedance 2.0 Fast","description":"Faster variant of ByteDance's Seedance 2.0 video model. Trades some quality for speed while sharing the same multimodal architecture. Supports text-to-video, image-to-video, native audio generation, multimodal references (images, videos, audio), video editing, and video extension.","url":"https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-fast/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: ByteDance's compact, cost-efficient video generation model from the Seedance 2.0 family. Supports text-to-video, image-to-video, reference video, and reference audio for background music. Ideal for high-volume workloads where speed and cost matter.
title: Seedance 2.0 Mini
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)

# Seedance 2.0 Mini

Text-to-Video • ByteDance

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-mini/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bytedance/seedance-2.0-mini`

- Third-party

ByteDance's compact, cost-efficient video generation model from the Seedance 2.0 family. Supports text-to-video, image-to-video, reference video, and reference audio for background music. Ideal for high-volume workloads where speed and cost matter.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://seed.bytedance.com/en/seedance) |
| Pricing | <ul><li>Default (per second)$0.09</li><li>@480p video input (per second)$0.084</li><li>@720p video input (per second)$0.182</li><li>@480p non-video input (per second)$0.04</li><li>@720p non-video input (per second)$0.09</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0-mini',
  {
    prompt:
      'A cat sitting on a windowsill watching raindrops fall on the glass, cozy interior lighting',
    aspect_ratio: '16:9',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0-mini",
  "input": {
    "prompt": "A cat sitting on a windowsill watching raindrops fall on the glass, cozy interior lighting",
    "aspect_ratio": "16:9",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0-mini/simple-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Image to Video** — Generate video from a reference image</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0-mini',
  {
    image: 'https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg',
    prompt: 'The scene slowly comes to life with gentle movement',
    aspect_ratio: '16:9',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0-mini",
  "input": {
    "image": "https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg",
    "prompt": "The scene slowly comes to life with gentle movement",
    "aspect_ratio": "16:9",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0-mini/image-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Portrait Video with Audio** — Vertical video for social media</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0-mini',
  {
    prompt: 'A steaming coffee cup on a marble table, morning light streaming through a window',
    aspect_ratio: '9:16',
    duration: 5,
    resolution: '720p',
    generate_audio: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0-mini",
  "input": {
    "prompt": "A steaming coffee cup on a marble table, morning light streaming through a window",
    "aspect_ratio": "9:16",
    "duration": 5,
    "resolution": "720p",
    "generate_audio": true
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0-mini/portrait-video-with-audio.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Virtual Avatar Reference** — Use a virtual character avatar from the trusted asset library</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.0-mini',
  {
    image: 'https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg',
    prompt: 'The scene gently animates with subtle motion',
    aspect_ratio: '16:9',
    duration: 5,
    resolution: '720p',
    use_virtual_avatar: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.0-mini",
  "input": {
    "image": "https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg",
    "prompt": "The scene gently animates with subtle motion",
    "aspect_ratio": "16:9",
    "duration": 5,
    "resolution": "720p",
    "use_virtual_avatar": true
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.0-mini/virtual-avatar-reference.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredmaxLength: 2000Text prompt describing the video to generate

image

`string`Reference image (HTTP(S) URL or base64 data URI) for image-to-video

reference\_video

`string`Reference video (HTTP(S) URL or base64 data URI) for style/motion guidance

last\_frame\_image

`string`Reference image (HTTP(S) URL or base64 data URI) for last-frame guidance. Only works if an image start frame is also given.

▶reference\_images\[]

`array`maxItems: 4Reference images (1-4, HTTP(S) URLs or base64 data URIs) to guide video generation for characters, avatars, clothing, or environments. Cannot be used with first/last frame images.

duration

`integer`requireddefault: 5minimum: 4maximum: 12Video duration in seconds

resolution

`string`requireddefault: 720penum: 480p, 720pVideo resolution

aspect\_ratio

`string`requireddefault: 16:9enum: 16:9, 4:3, 1:1, 3:4, 9:16, 21:9, 9:21Video aspect ratio. Ignored if an image is used.

fps

`number`requireddefault: 24const: 24Frame rate (frames per second)

camera\_fixed

`boolean`requireddefault: falseWhether to fix camera position

generate\_audio

`boolean`Whether to generate audio with the video

watermark

`boolean`requireddefault: falseWhether to add a watermark to the output video

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Random seed for reproducible generation

use\_virtual\_avatar

`boolean`requireddefault: falseRoute image reference inputs (image, reference\_images, last\_frame\_image) through ByteDance's trusted virtual avatar asset library before generation. Intended for AI-generated/virtual character avatars that would otherwise be blocked by face or deepfake detection

reference\_audio

`string`Reference audio (HTTP(S) URL or base64 data:audio/... URI) to use as background music. Must be accompanied by a reference image or video.

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-mini/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-mini/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-mini/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-mini/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-mini/#page","headline":"Seedance 2.0 Mini","description":"ByteDance's compact, cost-efficient video generation model from the Seedance 2.0 family. Supports text-to-video, image-to-video, reference video, and reference audio for background music. Ideal for high-volume workloads where speed and cost matter.","url":"https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-mini/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: ByteDance's next-generation video model with a unified multimodal reference-to-video architecture. Generates video from text, up to 30 reference images, 10 reference videos, and 10 reference audio clips — including audio-only input with no image or video required. Supports first/last-frame image-to-video, video editing, video extension, intelligent duration (including automatic selection), and adaptive aspect ratio.
title: Seedance 2.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)

# Seedance 2.5

Text-to-Video • ByteDance

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bytedance/seedance-2.5`

- Third-party

ByteDance's next-generation video model with a unified multimodal reference-to-video architecture. Generates video from text, up to 30 reference images, 10 reference videos, and 10 reference audio clips — including audio-only input with no image or video required. Supports first/last-frame image-to-video, video editing, video extension, intelligent duration (including automatic selection), and adaptive aspect ratio.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://seed.bytedance.com/en/seedance2_5) |
| Pricing | <ul><li>Default (per second)$0.2312</li><li>@480p video input (per second)$0.4304</li><li>@720p video input (per second)$0.9676</li><li>@480p non-video input (per second)$0.1028</li><li>@720p non-video input (per second)$0.2312</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bytedance/seedance-2.5',
  {
    prompt: 'A golden retriever running through a field of sunflowers on a sunny day',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.5",
  "input": {
    "prompt": "A golden retriever running through a field of sunflowers on a sunny day",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.5/simple-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Cinematic Wide Shot** — Longer cinematic video with an explicit 16:9 aspect ratio</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.5',
  {
    prompt:
      'A dramatic drone shot flying through misty mountain peaks at sunrise, cinematic lighting with volumetric fog',
    aspect_ratio: '16:9',
    duration: 12,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.5",
  "input": {
    "prompt": "A dramatic drone shot flying through misty mountain peaks at sunrise, cinematic lighting with volumetric fog",
    "aspect_ratio": "16:9",
    "duration": 12,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.5/cinematic-wide-shot.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**First and Last Frame** — Generate a video that transitions between a given first-frame and last-frame image</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.5',
  {
    image: 'https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg',
    last_frame_image: 'https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic2.jpg',
    prompt: 'The character slowly turns to face the camera and smiles',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.5",
  "input": {
    "image": "https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg",
    "last_frame_image": "https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic2.jpg",
    "prompt": "The character slowly turns to face the camera and smiles",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.5/first-and-last-frame.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Portrait Video with MOV Output** — Vertical video for social media, encoded as mov for higher color fidelity</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedance-2.5',
  {
    prompt: 'Abstract ink drops spreading through water, vivid colors mixing in slow motion',
    aspect_ratio: '9:16',
    duration: 5,
    resolution: '720p',
    output_format: 'mov',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedance-2.5",
  "input": {
    "prompt": "Abstract ink drops spreading through water, vivid colors mixing in slow motion",
    "aspect_ratio": "9:16",
    "duration": 5,
    "resolution": "720p",
    "output_format": "mov"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/bytedance/seedance-2.5/portrait-video-with-mov-output.mov"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`maxLength: 2000Text prompt describing the video to generate. Optional when at least one reference image, video, or audio clip is provided (Seedance 2.5 supports audio-only input).

image

`string`First-frame reference image (HTTP(S) URL or base64 data URI) for image-to-video

last\_frame\_image

`string`Last-frame reference image (HTTP(S) URL or base64 data URI). Requires a first-frame image to also be given.

▶reference\_images\[]

`array`maxItems: 30Reference images (0-30, HTTP(S) URLs or base64 data URIs) to guide multimodal video generation, editing, or extension.

▶reference\_videos\[]

`array`maxItems: 10Reference videos (0-10, HTTP(S) URLs or base64 data URIs) for style/motion guidance, video editing, or video extension. Total duration of all reference videos must not exceed 30 seconds.

▶reference\_audios\[]

`array`maxItems: 10Reference audio clips (0-10, HTTP(S) URLs or base64 data:audio/... URIs). Supports audio-only input (no image or video required). Total duration of all audio clips must not exceed 30 seconds.

▶duration

`one of`required

resolution

`string`requireddefault: 720penum: 480p, 720pVideo resolution

aspect\_ratio

`string`requireddefault: adaptiveenum: 16:9, 4:3, 1:1, 3:4, 9:16, 21:9, adaptiveVideo aspect ratio. "adaptive" automatically matches the aspect ratio of the provided reference image or video when applicable. First/last-frame generation always uses "adaptive"; any supplied value is overridden.

fps

`number`requireddefault: 24const: 24Frame rate (frames per second)

camera\_fixed

`boolean`requireddefault: falseWhether to fix camera position. Not currently supported by the provider; has no effect.

generate\_audio

`boolean`Whether to generate audio with the video

watermark

`boolean`requireddefault: falseWhether to add a watermark to the output video

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Random seed. Passing this does not error, but reproducibility is not guaranteed and is not documented by the provider.

output\_format

`string`requireddefault: mp4enum: mp4, movOutput video container format. "mp4" offers the best compatibility and smaller file size; "mov" preserves higher color fidelity for professional post-production workflows at the cost of a larger file.

use\_virtual\_avatar

`boolean`requireddefault: falseRoute image reference inputs (image, reference\_images, last\_frame\_image) through ByteDance's trusted virtual avatar asset library before generation. Intended for AI-generated/virtual character avatars that would otherwise be blocked by face or deepfake detection

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/#page","headline":"Seedance 2.5","description":"ByteDance's next-generation video model with a unified multimodal reference-to-video architecture. Generates video from text, up to 30 reference images, 10 reference videos, and 10 reference audio clips — including audio-only input with no image or video required. Supports first/last-frame image-to-video, video editing, video extension, intelligent duration (including automatic selection), and adaptive aspect ratio.","url":"https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Seedream 4.0 is ByteDance's image creation model that combines text-to-image generation and image editing into a single architecture, offering fast, high-resolution output up to 4K.
title: Seedream 4.0
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)

# Seedream 4.0

Text-to-Image • ByteDance

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.0/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bytedance/seedream-4.0`

- Third-party

Seedream 4.0 is ByteDance's image creation model that combines text-to-image generation and image editing into a single architecture, offering fast, high-resolution output up to 4K.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://seed.bytedance.com/en/seedream4_0) |
| Pricing | <ul><li>Per image$0.03</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bytedance/seedream-4.0',
  { prompt: 'A serene mountain lake surrounded by pine trees at dawn' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-4.0",
  "input": {
    "prompt": "A serene mountain lake surrounded by pine trees at dawn"
  }
}'
```

![Simple Generation](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-4.0/simple-generation.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-4-0/021776387438887c5f50319cb4d4388d7836967b82aebe5227f8d_0.jpeg"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**High Resolution** — 4K quality image generation</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-4.0',
  {
    prompt:
      'A detailed steampunk mechanical owl with brass gears and copper feathers, intricate clockwork visible',
    aspect_ratio: '1:1',
    size: '4K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-4.0",
  "input": {
    "prompt": "A detailed steampunk mechanical owl with brass gears and copper feathers, intricate clockwork visible",
    "aspect_ratio": "1:1",
    "size": "4K"
  }
}'
```

![High Resolution](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-4.0/high-resolution.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-4-0/021776387448153c5f50319cb4d4388d7836967b82aebe5807cbc_0.jpeg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Widescreen Landscape** — Cinematic aspect ratio image</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-4.0',
  {
    prompt:
      'A vast alien desert landscape with two suns setting on the horizon, ancient ruins in the foreground',
    aspect_ratio: '21:9',
    size: '2K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-4.0",
  "input": {
    "prompt": "A vast alien desert landscape with two suns setting on the horizon, ancient ruins in the foreground",
    "aspect_ratio": "21:9",
    "size": "2K"
  }
}'
```

![Widescreen Landscape](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-4.0/widescreen-landscape.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-4-0/021776387469085c5f50319cb4d4388d7836967b82aebe5dcf17e_0.jpeg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Portrait Format** — Vertical image for portraits</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-4.0',
  {
    prompt: 'An elegant Art Deco poster featuring a jazz singer under a spotlight',
    aspect_ratio: '9:16',
    enhance_prompt: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-4.0",
  "input": {
    "prompt": "An elegant Art Deco poster featuring a jazz singer under a spotlight",
    "aspect_ratio": "9:16",
    "enhance_prompt": true
  }
}'
```

![Portrait Format](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-4.0/portrait-format.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-4-0/021776387475078c5f50319cb4d4388d7836967b82aebe5e6ec81_0.jpeg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Detailed 4K** — High-resolution detailed botanical illustration</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-4.0',
  {
    prompt: 'A detailed botanical illustration of exotic tropical flowers',
    aspect_ratio: '3:4',
    size: '4K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-4.0",
  "input": {
    "prompt": "A detailed botanical illustration of exotic tropical flowers",
    "aspect_ratio": "3:4",
    "size": "4K"
  }
}'
```

![Detailed 4K](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-4.0/detailed-4k.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-4-0/021776441662380e1f2c28e220bf76d8a56e2a46eaa08e982d37f_0.jpeg"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`enum: 1K, 2K, 4K, custom

aspect\_ratio

`string`enum: match\_input\_image, 1:1, 4:3, 3:4, 16:9, 9:16, 3:2, 2:3, 21:9

width

`integer`minimum: 1024maximum: 4096

height

`integer`minimum: 1024maximum: 4096

enhance\_prompt

`boolean`

image

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.0/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.0/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.0/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.0/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bytedance/seedream-4.0/#page","headline":"Seedream 4.0","description":"Seedream 4.0 is ByteDance's image creation model that combines text-to-image generation and image editing into a single architecture, offering fast, high-resolution output up to 4K.","url":"https://developers.cloudflare.com/ai/models/bytedance/seedream-4.0/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Seedream 4.5 builds on 4.0 with multi-reference image support, batch generation, and sequential image generation.
title: Seedream 4.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)

# Seedream 4.5

Text-to-Image • ByteDance

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bytedance/seedream-4.5`

- Third-party

Seedream 4.5 builds on 4.0 with multi-reference image support, batch generation, and sequential image generation.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://seed.bytedance.com/en/seedream4_5) |
| Pricing | <ul><li>Per image$0.04</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bytedance/seedream-4.5',
  { prompt: 'A cozy reading nook with floor-to-ceiling bookshelves and a comfortable armchair' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-4.5",
  "input": {
    "prompt": "A cozy reading nook with floor-to-ceiling bookshelves and a comfortable armchair"
  }
}'
```

![Simple Generation](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-4.5/simple-generation-0.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-4-5/0217764052077481386b9a8ed856c57501cfa946ce34c9865285c_0.jpeg"
    ]
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**High Resolution** — 4K quality image generation</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-4.5',
  {
    prompt:
      'A hyperrealistic still life painting of fresh fruit on an antique wooden table with dramatic chiaroscuro lighting',
    aspect_ratio: '4:3',
    size: '4K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-4.5",
  "input": {
    "prompt": "A hyperrealistic still life painting of fresh fruit on an antique wooden table with dramatic chiaroscuro lighting",
    "aspect_ratio": "4:3",
    "size": "4K"
  }
}'
```

![High Resolution](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-4.5/high-resolution-0.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-4-5/0217764052077581386b9a8ed856c57501cfa946ce34c985dabe3_0.jpeg"
    ]
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Image-to-Image** — Edit using reference images</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-4.5',
  {
    prompt: 'Transform this scene into a winter wonderland with snow covering everything',
    aspect_ratio: 'match_input_image',
    image_input: [
      'https://replicate.delivery/xezq/0lxxNQSg3NabCZrDiQVAPGVmjP1Q2dd7TgYCOTfI9LpyZaMLA/tmp89gopylq.jpg',
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-4.5",
  "input": {
    "prompt": "Transform this scene into a winter wonderland with snow covering everything",
    "aspect_ratio": "match_input_image",
    "image_input": [
      "https://replicate.delivery/xezq/0lxxNQSg3NabCZrDiQVAPGVmjP1Q2dd7TgYCOTfI9LpyZaMLA/tmp89gopylq.jpg"
    ]
  }
}'
```

![Image-to-Image](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-4.5/image-to-image-0.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-4-5/0217764052176861386b9a8ed856c57501cfa946ce34c98846458_0.jpeg"
    ]
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Sequential Generation** — Generate multiple related images</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-4.5',
  {
    prompt: 'A character design sheet for a fantasy warrior: front view, side view, and back view',
    aspect_ratio: '16:9',
    max_images: 3,
    sequential_image_generation: 'auto',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-4.5",
  "input": {
    "prompt": "A character design sheet for a fantasy warrior: front view, side view, and back view",
    "aspect_ratio": "16:9",
    "max_images": 3,
    "sequential_image_generation": "auto"
  }
}'
```

![Sequential Generation](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-4.5/sequential-generation-0.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-4-5/0217764052291261386b9a8ed856c57501cfa946ce34c98481db1_0.jpeg"
    ]
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Multi-Image Edit** — Combine multiple reference images</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-4.5',
  {
    prompt: 'Combine the style of the first image with the subject from the second image',
    image_input: [
      'https://replicate.delivery/xezq/TRYcLgNMrBpPJVq09ICKXWe4Z8d6olzpK5vtQPOB8O23ZaMLA/tmpaecga26m.jpg',
      'https://replicate.delivery/xezq/1SbAc0aXYXbVD9doyrdCW78hYufVefMsaJXBrETN7Lu2npxsA/tmphvkx7emy.jpg',
    ],
    size: '2K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-4.5",
  "input": {
    "prompt": "Combine the style of the first image with the subject from the second image",
    "image_input": [
      "https://replicate.delivery/xezq/TRYcLgNMrBpPJVq09ICKXWe4Z8d6olzpK5vtQPOB8O23ZaMLA/tmpaecga26m.jpg",
      "https://replicate.delivery/xezq/1SbAc0aXYXbVD9doyrdCW78hYufVefMsaJXBrETN7Lu2npxsA/tmphvkx7emy.jpg"
    ],
    "size": "2K"
  }
}'
```

![Multi-Image Edit](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-4.5/multi-image-edit-0.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-4-5/0217764052323791386b9a8ed856c57501cfa946ce34c98b2f132_0.jpeg"
    ]
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

▶image\_input\[]

`array`format: uri

size

`string`enum: 2K, 4K

aspect\_ratio

`string`enum: match\_input\_image, 1:1, 4:3, 3:4, 16:9, 9:16, 3:2, 2:3, 21:9

sequential\_image\_generation

`string`enum: disabled, auto

max\_images

`integer`minimum: 1maximum: 15

disable\_safety\_checker

`boolean`

▶images\[]

`array`minItems: 1format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedream-4.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bytedance/seedream-4.5/#page","headline":"Seedream 4.5","description":"Seedream 4.5 builds on 4.0 with multi-reference image support, batch generation, and sequential image generation.","url":"https://developers.cloudflare.com/ai/models/bytedance/seedream-4.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Seedream 5 Lite is a lighter, faster version of the Seedream 5 family with multi-reference and batch generation support.
title: Seedream 5 Lite
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)

# Seedream 5 Lite

Text-to-Image • ByteDance

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-lite/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bytedance/seedream-5-lite`

- Third-party

Seedream 5 Lite is a lighter, faster version of the Seedream 5 family with multi-reference and batch generation support.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://seed.bytedance.com/en/seedream5_0_lite) |
| Pricing | <ul><li>Per image$0.035</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bytedance/seedream-5-lite',
  { prompt: 'A cute robot watering plants in a sunny greenhouse' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-5-lite",
  "input": {
    "prompt": "A cute robot watering plants in a sunny greenhouse"
  }
}'
```

![Simple Generation](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-5-lite/simple-generation-0.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://ark-acg-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-5-0/021776405291656e8ad6f8fac80a9b78040141fa10ae51dc262e8_0.jpeg"
    ]
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**High Resolution PNG** — 3K quality with PNG output</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-5-lite',
  {
    prompt:
      'A detailed technical blueprint of a futuristic spacecraft with annotations and measurements',
    aspect_ratio: '16:9',
    output_format: 'png',
    size: '3K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-5-lite",
  "input": {
    "prompt": "A detailed technical blueprint of a futuristic spacecraft with annotations and measurements",
    "aspect_ratio": "16:9",
    "output_format": "png",
    "size": "3K"
  }
}'
```

![High Resolution PNG](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-5-lite/high-resolution-png-0.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://ark-acg-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-5-0/021776405293188e8ad6f8fac80a9b78040141fa10ae51d8ac521_0.png"
    ]
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Portrait Photo** — JPEG output for photographs</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-5-lite',
  {
    prompt:
      'A professional headshot portrait with soft studio lighting and a neutral gray background',
    aspect_ratio: '3:4',
    output_format: 'jpeg',
    size: '2K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-5-lite",
  "input": {
    "prompt": "A professional headshot portrait with soft studio lighting and a neutral gray background",
    "aspect_ratio": "3:4",
    "output_format": "jpeg",
    "size": "2K"
  }
}'
```

![Portrait Photo](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-5-lite/portrait-photo-0.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://ark-acg-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-5-0/021776405322247e8ad6f8fac80a9b78040141fa10ae51db518ee_0.jpeg"
    ]
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Sequential Comic** — Generate sequential comic panels</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-5-lite',
  {
    prompt:
      'A four-panel comic strip showing a cat discovering a cardboard box and deciding to sit in it',
    aspect_ratio: '4:3',
    max_images: 4,
    sequential_image_generation: 'auto',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-5-lite",
  "input": {
    "prompt": "A four-panel comic strip showing a cat discovering a cardboard box and deciding to sit in it",
    "aspect_ratio": "4:3",
    "max_images": 4,
    "sequential_image_generation": "auto"
  }
}'
```

![Sequential Comic](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-5-lite/sequential-comic-0.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://ark-acg-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-5-0/0217764053440971386b9a8ed856c57501cfa946ce34c987bb335_0.jpeg"
    ]
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Image Variation** — Create variation from reference</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-5-lite',
  {
    prompt: 'Create a variation of this image in a watercolor painting style',
    aspect_ratio: 'match_input_image',
    image_input: [
      'https://replicate.delivery/xezq/jCypj4MeXYUiRyq7nfgm8z1OvFZF81wh4FznutDsZOuJz0YWA/tmp1iukn307.jpg',
    ],
    size: '2K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-5-lite",
  "input": {
    "prompt": "Create a variation of this image in a watercolor painting style",
    "aspect_ratio": "match_input_image",
    "image_input": [
      "https://replicate.delivery/xezq/jCypj4MeXYUiRyq7nfgm8z1OvFZF81wh4FznutDsZOuJz0YWA/tmp1iukn307.jpg"
    ],
    "size": "2K"
  }
}'
```

![Image Variation](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/bytedance__seedream-5-lite/image-variation-0.jpeg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "images": [
      "https://ark-acg-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream-5-0/0217764053505731386b9a8ed856c57501cfa946ce34c989ba40c_0.jpeg"
    ]
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

▶image\_input\[]

`array`maxItems: 14format: uri

size

`string`enum: 2K, 3K

aspect\_ratio

`string`enum: match\_input\_image, 1:1, 4:3, 3:4, 16:9, 9:16, 3:2, 2:3, 21:9

sequential\_image\_generation

`string`enum: disabled, auto

max\_images

`integer`minimum: 1maximum: 15

output\_format

`string`enum: png, jpeg

▶images\[]

`array`minItems: 1format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-lite/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-lite/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-lite/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-lite/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bytedance/seedream-5-lite/#page","headline":"Seedream 5 Lite","description":"Seedream 5 Lite is a lighter, faster version of the Seedream 5 family with multi-reference and batch generation support.","url":"https://developers.cloudflare.com/ai/models/bytedance/seedream-5-lite/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Seedream 5 Pro is ByteDance's high-quality image generation and editing model with text prompts, up to 10 reference images, and 1K, 2K, or explicit pixel-size output controls.
title: Seedream 5 Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ByteDance logo](https://developers.cloudflare.com/_astro/bytedance.T1uiROQ6.svg)

# Seedream 5 Pro

Text-to-Image • ByteDance

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`bytedance/seedream-5-pro`

- Third-party

Seedream 5 Pro is ByteDance's high-quality image generation and editing model with text prompts, up to 10 reference images, and 1K, 2K, or explicit pixel-size output controls.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://ark.ap-southeast.bytepluses.com/api/v3/images/generations) |
| Pricing | <ul><li>Per image$0.045</li><li>Per input image$0.03</li><li>Default (per second)$0.045</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'bytedance/seedream-5-pro',
  {
    prompt:
      'Premium studio product render of a transparent mechanical wristwatch suspended above matte black stone, visible gears, sapphire reflections, razor-sharp lighting, luxury advertising style',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-5-pro",
  "input": {
    "prompt": "Premium studio product render of a transparent mechanical wristwatch suspended above matte black stone, visible gears, sapphire reflections, razor-sharp lighting, luxury advertising style"
  }
}'
```

![Mechanical Watch](https://examples.aig.cloudflare.com/bytedance/seedream-5-pro/mechanical-watch-0.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "images": [
      "https://examples.aig.cloudflare.com/bytedance/seedream-5-pro/mechanical-watch-0.jpeg"
    ]
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Red Panda Bakery** — Whimsical illustrated scene with a very different visual style.</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-5-pro',
  {
    prompt:
      "A cozy children's book illustration of a red panda baker frosting moon-shaped cakes inside a tiny snowy mountain bakery, soft gouache texture, warm window light",
    size: '1536x864',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-5-pro",
  "input": {
    "prompt": "A cozy children'\''s book illustration of a red panda baker frosting moon-shaped cakes inside a tiny snowy mountain bakery, soft gouache texture, warm window light",
    "size": "1536x864"
  }
}'
```

![Red Panda Bakery](https://examples.aig.cloudflare.com/bytedance/seedream-5-pro/red-panda-bakery-0.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "images": [
      "https://examples.aig.cloudflare.com/bytedance/seedream-5-pro/red-panda-bakery-0.jpeg"
    ]
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Claymation Reference** — Use a reference image for a claymation-style transformation.</summary>



```ts
const response = await env.AI.run(
  'bytedance/seedream-5-pro',
  {
    image: 'https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg',
    prompt:
      'Transform this reference into a handcrafted claymation diorama, rounded clay forms, visible fingerprints, miniature set lighting, playful stop-motion film look',
    size: '1K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "bytedance/seedream-5-pro",
  "input": {
    "image": "https://ark-doc.tos-ap-southeast-1.bytepluses.com/doc_image/r2v_tea_pic1.jpg",
    "prompt": "Transform this reference into a handcrafted claymation diorama, rounded clay forms, visible fingerprints, miniature set lighting, playful stop-motion film look",
    "size": "1K"
  }
}'
```

![Claymation Reference](https://examples.aig.cloudflare.com/bytedance/seedream-5-pro/claymation-reference-0.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "images": [
      "https://examples.aig.cloudflare.com/bytedance/seedream-5-pro/claymation-reference-0.jpeg"
    ]
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`required

▶image

`one of`

size

`string`

watermark

`boolean`requireddefault: falseWhether to add an AI-generated watermark to the output image

▶images\[]

`array`minItems: 1format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/#page","headline":"Seedream 5 Pro","description":"Seedream 5 Pro is ByteDance's high-quality image generation and editing model with text prompts, up to 10 reference images, and 1K, 2K, or explicit pixel-size output controls.","url":"https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: DeepSeek V4 Pro is a high-capability reasoning model from DeepSeek, served via Fireworks infrastructure for production-grade inference.
title: DeepSeek V4 Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

d

# DeepSeek V4 Pro

Text Generation • deepseek

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/deepseek/deepseek-v4-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`deepseek/deepseek-v4-pro`

- Third-party

DeepSeek V4 Pro is a high-capability reasoning model from DeepSeek, served via Fireworks infrastructure for production-grade inference.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 131,072 tokens |
| More information | [link ↗](https://api-docs.deepseek.com) |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$1.74</li><li>Output (per 1M tokens)$3.48</li><li>Cached input (per 1M tokens)$0.145</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'deepseek/deepseek-v4-pro',
  {
    messages: [{ content: 'What is the capital of France?', role: 'user' }],
    model: 'deepseek/deepseek-v4-pro',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "deepseek/deepseek-v4-pro",
  "messages": [
    {
      "content": "What is the capital of France?",
      "role": "user"
    }
  ]
}'
```

```
The capital of France is **Paris**.
```

```json
{
  "id": "chatcmpl-3a08845344c942108c3ab7b29112f012",
  "object": "chat.completion",
  "created": 1781047641,
  "model": "deepseek/deepseek-v4-pro",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The capital of France is **Paris**.",
        "reasoning_content": "We need to answer the question: \"What is the capital of France?\" This is straightforward. The capital of France is Paris. I should answer concisely."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 11,
    "completion_tokens": 43,
    "total_tokens": 54,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'deepseek/deepseek-v4-pro',
  {
    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' },
    ],
    model: 'deepseek/deepseek-v4-pro',
    temperature: 0.3,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "deepseek/deepseek-v4-pro",
  "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"
    }
  ],
  "temperature": 0.3
}'
```

````
To read a JSON file in Python, you use the built-in `json` module. The most common approach is `json.load()` which reads directly from a file object.

### Basic example
```python
import json

with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

print(data)
```

### Key points
- **`json.load(file)`** – parses JSON from a file-like object.
- **`json.loads(string)`** – parses JSON from a string (useful if you already have JSON data in memory).
- Always open the file in read mode (`'r'`) and specify the correct encoding (usually `'utf-8'`).
- The result is a Python dictionary (if the JSON is an object) or a list (if it’s an array).

### Handling errors
Wrap the loading in a `try`/`except` to catch malformed JSON or file issues:
```python
import json

try:
    with open('data.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
except FileNotFoundError:
    print("File not found.")
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")
```

### Reading from a string
If you already have a JSON string:
```python
json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)
```

That’s it! Let me know if you need help with writing JSON or more advanced usage.
````

```json
{
  "id": "chatcmpl-1aecff3044dc4e349362b9237f0e63b4",
  "object": "chat.completion",
  "created": 1781047642,
  "model": "deepseek/deepseek-v4-pro",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "To read a JSON file in Python, you use the built-in `json` module. The most common approach is `json.load()` which reads directly from a file object.\n\n### Basic example\n```python\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as f:\n    data = json.load(f)\n\nprint(data)\n```\n\n### Key points\n- **`json.load(file)`** – parses JSON from a file-like object.\n- **`json.loads(string)`** – parses JSON from a string (useful if you already have JSON data in memory).\n- Always open the file in read mode (`'r'`) and specify the correct encoding (usually `'utf-8'`).\n- The result is a Python dictionary (if the JSON is an object) or a list (if it’s an array).\n\n### Handling errors\nWrap the loading in a `try`/`except` to catch malformed JSON or file issues:\n```python\nimport json\n\ntry:\n    with open('data.json', 'r', encoding='utf-8') as f:\n        data = json.load(f)\nexcept FileNotFoundError:\n    print(\"File not found.\")\nexcept json.JSONDecodeError as e:\n    print(f\"Invalid JSON: {e}\")\n```\n\n### Reading from a string\nIf you already have a JSON string:\n```python\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)\n```\n\nThat’s it! Let me know if you need help with writing JSON or more advanced usage.",
        "reasoning_content": "We need to provide a clear, concise answer on how to read a JSON file in Python. The user likely wants to know the standard method using the `json` module. We'll explain opening the file, using `json.load()` for file objects, and `json.loads()` for strings. Also mention error handling, encoding, and maybe a simple example. Keep it friendly and informative."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 24,
    "completion_tokens": 413,
    "total_tokens": 437,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'deepseek/deepseek-v4-pro',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    model: 'deepseek/deepseek-v4-pro',
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "deepseek/deepseek-v4-pro",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

````
Recursion is a programming technique where a function calls itself to solve a smaller version of the same problem. Each recursive call works on a simpler input, and there’s always a **base case** that stops the recursion, preventing an infinite loop.

### The Two Essential Parts
1. **Base case** – the simplest scenario that can be answered directly (no more recursive calls).
2. **Recursive case** – the function calls itself with a smaller/simpler argument, moving toward the base case.

### Simple Example: Factorial
The factorial of a non-negative integer `n` (written `n!`) is the product of all positive integers up to `n`.  
Definition:  
- `0! = 1` (base case)  
- `n! = n × (n−1)!` for `n > 0` (recursive case)

#### Python implementation
```python
def factorial(n):
    if n == 0:          # base case
        return 1
    else:               # recursive case
        return n * factorial(n - 1)
```

#### How it works step-by-step for `factorial(3)`
```
factorial(3)
  → 3 * factorial(2)           # waiting for factorial(2)
        → 2 * factorial(1)     # waiting for factorial(1)
              → 1 * factorial(0)
                    → 0 == 0? → return 1   # base case reached
              → 1 * 1 = 1
        → 2 * 1 = 2
  → 3 * 2 = 6
```
The calls "stack up" until the base case is hit, then they resolve in reverse order, multiplying as they go.

### Key Takeaways
- Recursion breaks a problem into self-similar subproblems.
- Every recursive function needs a stopping condition (base case).
- Without a base case, you get infinite recursion (eventually a stack overflow).
- It’s especially natural for problems with a recursive structure (trees, sorting, divide-and-conquer, etc.).
````

```json
[
  {
    "id": "chatcmpl-cf0a764075534f728f55b99dacf898ba",
    "object": "chat.completion.chunk",
    "created": 1781047647,
    "model": "accounts/fireworks/models/deepseek-v4-pro",
    "choices": [
      {
        "index": 0,
        "delta": {
          "role": "assistant"
        },
        "finish_reason": null,
        "raw_output": null
      }
    ],
    "usage": null
  },
  {
    "id": "chatcmpl-cf0a764075534f728f55b99dacf898ba",
    "object": "chat.completion.chunk",
    "created": 1781047647,
    "model": "accounts/fireworks/models/deepseek-v4-pro",
    "choices": [
      {
        "index": 0,
        "delta": {
          "reasoning_content": "We"
        },
        "finish_reason": null,
        "raw_output": null
      }
    ],
    "usage": null
  },
  "... 606 more chunks omitted ...",
  {
    "id": "chatcmpl-cf0a764075534f728f55b99dacf898ba",
    "object": "chat.completion.chunk",
    "created": 1781047647,
    "model": "accounts/fireworks/models/deepseek-v4-pro",
    "choices": [],
    "usage": {
      "prompt_tokens": 14,
      "total_tokens": 622,
      "completion_tokens": 608,
      "prompt_tokens_details": {
        "cached_tokens": 0
      }
    }
  }
]
```

</details>

## Parameters

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/deepseek/deepseek-v4-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/deepseek/deepseek-v4-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/deepseek/deepseek-v4-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/deepseek/deepseek-v4-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/deepseek/deepseek-v4-pro/#page","headline":"DeepSeek V4 Pro","description":"DeepSeek V4 Pro is a high-capability reasoning model from DeepSeek, served via Fireworks infrastructure for production-grade inference.","url":"https://developers.cloudflare.com/ai/models/deepseek/deepseek-v4-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: ElevenLabs' low-latency Flash v2.5 text-to-speech model for fast multilingual speech generation.
title: Eleven Flash v2.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ElevenLabs logo](https://developers.cloudflare.com/_astro/elevenlabs.0RXw7U95.svg)

# Eleven Flash v2.5

Text-to-Speech • ElevenLabs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-flash-v2-5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`elevenlabs/eleven-flash-v2-5`

- Third-party

ElevenLabs' low-latency Flash v2.5 text-to-speech model for fast multilingual speech generation.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://elevenlabs.io/terms) |
| More information | [link ↗](https://elevenlabs.io/docs/api-reference/text-to-speech/convert) |
| Pricing | <ul><li>Per character$0.00005</li><li>Default (per second)$0.00005</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'elevenlabs/eleven-flash-v2-5',
  {
    text: 'Thanks for contacting Cloudflare AI Gateway support. I can help you compare providers, review request logs, or troubleshoot model routing.',
    voice_id: 'JBFqnCBsd6RMkjVDRZzb',
    output_format: 'mp3_44100_128',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "elevenlabs/eleven-flash-v2-5",
  "input": {
    "text": "Thanks for contacting Cloudflare AI Gateway support. I can help you compare providers, review request logs, or troubleshoot model routing.",
    "voice_id": "JBFqnCBsd6RMkjVDRZzb",
    "output_format": "mp3_44100_128"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "audio": "https://examples.aig.cloudflare.com/elevenlabs/eleven-flash-v2-5/ai-gateway-assistant.mp3"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

text

`string`requiredminLength: 1maxLength: 10000The text to convert into speech.

voice\_id

`string`requiredminLength: 1The ElevenLabs voice ID to use for generation.

output\_format

`string`enum: mp3\_22050\_32, mp3\_24000\_48, mp3\_44100\_128, mp3\_44100\_192, mp3\_44100\_32, mp3\_44100\_64, mp3\_44100\_96, opus\_48000\_128, opus\_48000\_192, opus\_48000\_32, opus\_48000\_64, opus\_48000\_96

language\_code

`string`ISO 639-1 language code to enforce.

▶voice\_settings{}

`object`

seed

`integer`minimum: 0maximum: 4294967295

previous\_text

`string`

next\_text

`string`

apply\_text\_normalization

`string`enum: auto, on, off

audio

`string`URL to the generated audio file.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-flash-v2-5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-flash-v2-5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-flash-v2-5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-flash-v2-5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/elevenlabs/eleven-flash-v2-5/#page","headline":"Eleven Flash v2.5","description":"ElevenLabs' low-latency Flash v2.5 text-to-speech model for fast multilingual speech generation.","url":"https://developers.cloudflare.com/ai/models/elevenlabs/eleven-flash-v2-5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: ElevenLabs' multilingual text-to-speech model for generating natural speech across many languages with ElevenLabs voices.
title: Eleven Multilingual v2
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ElevenLabs logo](https://developers.cloudflare.com/_astro/elevenlabs.0RXw7U95.svg)

# Eleven Multilingual v2

Text-to-Speech • ElevenLabs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-multilingual-v2/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`elevenlabs/eleven-multilingual-v2`

- Third-party

ElevenLabs' multilingual text-to-speech model for generating natural speech across many languages with ElevenLabs voices.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://elevenlabs.io/terms) |
| More information | [link ↗](https://elevenlabs.io/docs/api-reference/text-to-speech/convert) |
| Pricing | <ul><li>Per character$0.0001</li><li>Default (per second)$0.0001</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'elevenlabs/eleven-multilingual-v2',
  {
    text: 'Bonjour et bienvenue dans Cloudflare AI Gateway. Suivez vos requetes, vos couts et les performances de vos modeles depuis une seule interface.',
    voice_id: 'JBFqnCBsd6RMkjVDRZzb',
    language_code: 'fr',
    output_format: 'mp3_44100_128',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "elevenlabs/eleven-multilingual-v2",
  "input": {
    "text": "Bonjour et bienvenue dans Cloudflare AI Gateway. Suivez vos requetes, vos couts et les performances de vos modeles depuis une seule interface.",
    "voice_id": "JBFqnCBsd6RMkjVDRZzb",
    "language_code": "fr",
    "output_format": "mp3_44100_128"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "audio": "https://examples.aig.cloudflare.com/elevenlabs/eleven-multilingual-v2/french-ai-gateway-speech.mp3"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

text

`string`requiredminLength: 1maxLength: 10000The text to convert into speech.

voice\_id

`string`requiredminLength: 1The ElevenLabs voice ID to use for generation.

output\_format

`string`enum: mp3\_22050\_32, mp3\_24000\_48, mp3\_44100\_128, mp3\_44100\_192, mp3\_44100\_32, mp3\_44100\_64, mp3\_44100\_96, opus\_48000\_128, opus\_48000\_192, opus\_48000\_32, opus\_48000\_64, opus\_48000\_96

language\_code

`string`ISO 639-1 language code to enforce.

▶voice\_settings{}

`object`

seed

`integer`minimum: 0maximum: 4294967295

previous\_text

`string`

next\_text

`string`

apply\_text\_normalization

`string`enum: auto, on, off

audio

`string`URL to the generated audio file.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-multilingual-v2/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-multilingual-v2/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-multilingual-v2/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-multilingual-v2/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/elevenlabs/eleven-multilingual-v2/#page","headline":"Eleven Multilingual v2","description":"ElevenLabs' multilingual text-to-speech model for generating natural speech across many languages with ElevenLabs voices.","url":"https://developers.cloudflare.com/ai/models/elevenlabs/eleven-multilingual-v2/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: ElevenLabs' Turbo v2.5 text-to-speech model balancing high-quality voice generation with low latency across 32 languages.
title: Eleven Turbo v2.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ElevenLabs logo](https://developers.cloudflare.com/_astro/elevenlabs.0RXw7U95.svg)

# Eleven Turbo v2.5

Text-to-Speech • ElevenLabs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-turbo-v2-5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`elevenlabs/eleven-turbo-v2-5`

- Third-party

ElevenLabs' Turbo v2.5 text-to-speech model balancing high-quality voice generation with low latency across 32 languages.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://elevenlabs.io/terms) |
| More information | [link ↗](https://elevenlabs.io/docs/api-reference/text-to-speech/convert) |
| Pricing | <ul><li>Per character$0.00005</li><li>Default (per second)$0.00005</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'elevenlabs/eleven-turbo-v2-5',
  {
    text: 'Your Cloudflare AI Gateway usage report is ready. Review provider latency, token counts, cache status, and request costs in the dashboard.',
    voice_id: 'JBFqnCBsd6RMkjVDRZzb',
    output_format: 'mp3_44100_128',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "elevenlabs/eleven-turbo-v2-5",
  "input": {
    "text": "Your Cloudflare AI Gateway usage report is ready. Review provider latency, token counts, cache status, and request costs in the dashboard.",
    "voice_id": "JBFqnCBsd6RMkjVDRZzb",
    "output_format": "mp3_44100_128"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "audio": "https://examples.aig.cloudflare.com/elevenlabs/eleven-turbo-v2-5/ai-gateway-notification.mp3"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

text

`string`requiredminLength: 1maxLength: 10000The text to convert into speech.

voice\_id

`string`requiredminLength: 1The ElevenLabs voice ID to use for generation.

output\_format

`string`enum: mp3\_22050\_32, mp3\_24000\_48, mp3\_44100\_128, mp3\_44100\_192, mp3\_44100\_32, mp3\_44100\_64, mp3\_44100\_96, opus\_48000\_128, opus\_48000\_192, opus\_48000\_32, opus\_48000\_64, opus\_48000\_96

language\_code

`string`ISO 639-1 language code to enforce.

▶voice\_settings{}

`object`

seed

`integer`minimum: 0maximum: 4294967295

previous\_text

`string`

next\_text

`string`

apply\_text\_normalization

`string`enum: auto, on, off

audio

`string`URL to the generated audio file.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-turbo-v2-5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-turbo-v2-5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-turbo-v2-5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-turbo-v2-5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/elevenlabs/eleven-turbo-v2-5/#page","headline":"Eleven Turbo v2.5","description":"ElevenLabs' Turbo v2.5 text-to-speech model balancing high-quality voice generation with low latency across 32 languages.","url":"https://developers.cloudflare.com/ai/models/elevenlabs/eleven-turbo-v2-5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: ElevenLabs' latest text-to-speech model for highly expressive, natural speech generation with advanced voice control.
title: Eleven v3
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ElevenLabs logo](https://developers.cloudflare.com/_astro/elevenlabs.0RXw7U95.svg)

# Eleven v3

Text-to-Speech • ElevenLabs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-v3/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`elevenlabs/eleven-v3`

- Third-party

ElevenLabs' latest text-to-speech model for highly expressive, natural speech generation with advanced voice control.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://elevenlabs.io/terms) |
| More information | [link ↗](https://elevenlabs.io/docs/api-reference/text-to-speech/convert) |
| Pricing | <ul><li>Per character$0.0001</li><li>Default (per second)$0.0001</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'elevenlabs/eleven-v3',
  {
    text: 'Welcome to Cloudflare AI Gateway. This is ElevenLabs speech synthesis with a natural, expressive delivery.',
    voice_id: 'JBFqnCBsd6RMkjVDRZzb',
    output_format: 'mp3_44100_128',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "elevenlabs/eleven-v3",
  "input": {
    "text": "Welcome to Cloudflare AI Gateway. This is ElevenLabs speech synthesis with a natural, expressive delivery.",
    "voice_id": "JBFqnCBsd6RMkjVDRZzb",
    "output_format": "mp3_44100_128"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "audio": "https://examples.aig.cloudflare.com/elevenlabs/eleven-v3/expressive-speech.mp3"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

text

`string`requiredminLength: 1maxLength: 10000The text to convert into speech.

voice\_id

`string`requiredminLength: 1The ElevenLabs voice ID to use for generation.

output\_format

`string`enum: mp3\_22050\_32, mp3\_24000\_48, mp3\_44100\_128, mp3\_44100\_192, mp3\_44100\_32, mp3\_44100\_64, mp3\_44100\_96, opus\_48000\_128, opus\_48000\_192, opus\_48000\_32, opus\_48000\_64, opus\_48000\_96

language\_code

`string`ISO 639-1 language code to enforce.

▶voice\_settings{}

`object`

seed

`integer`minimum: 0maximum: 4294967295

previous\_text

`string`

next\_text

`string`

apply\_text\_normalization

`string`enum: auto, on, off

audio

`string`URL to the generated audio file.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-v3/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-v3/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-v3/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/elevenlabs/eleven-v3/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/elevenlabs/eleven-v3/#page","headline":"Eleven v3","description":"ElevenLabs' latest text-to-speech model for highly expressive, natural speech generation with advanced voice control.","url":"https://developers.cloudflare.com/ai/models/elevenlabs/eleven-v3/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: ElevenLabs Music v2 composes songs and instrumental tracks from a prompt or detailed composition plan.
title: ElevenLabs Music v2
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![ElevenLabs logo](https://developers.cloudflare.com/_astro/elevenlabs.0RXw7U95.svg)

# ElevenLabs Music v2

Music Generation • ElevenLabs

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/elevenlabs/music-v2/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`elevenlabs/music-v2`

- Third-party

ElevenLabs Music v2 composes songs and instrumental tracks from a prompt or detailed composition plan.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://elevenlabs.io/terms) |
| More information | [link ↗](https://elevenlabs.io/docs/api-reference/music/compose) |
| Pricing | <ul><li>output audio seconds$0.0025</li><li>Default (per second)$0.0025</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'elevenlabs/music-v2',
  {
    prompt: 'A warm cinematic ambient track with soft piano, subtle strings, and a hopeful mood',
    music_length_ms: 30000,
    force_instrumental: true,
    output_format: 'mp3_48000_192',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "elevenlabs/music-v2",
  "input": {
    "prompt": "A warm cinematic ambient track with soft piano, subtle strings, and a hopeful mood",
    "music_length_ms": 30000,
    "force_instrumental": true,
    "output_format": "mp3_48000_192"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "audio": "https://examples.aig.cloudflare.com/elevenlabs/music-v2/cinematic-instrumental.mp3"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

prompt

`string`minLength: 1

▶composition\_plan{}

`object`

music\_length\_ms

`integer`minimum: 3000maximum: 600000

output\_format

`string`enum: auto, mp3\_48000\_128, mp3\_48000\_192, mp3\_48000\_240, mp3\_48000\_320, mp3\_22050\_32, mp3\_24000\_48, mp3\_44100\_32, mp3\_44100\_64, mp3\_44100\_96, mp3\_44100\_128, mp3\_44100\_192, opus\_48000\_32, opus\_48000\_64, opus\_48000\_96, opus\_48000\_128, opus\_48000\_192

seed

`integer`minimum: 0maximum: 4294967295

force\_instrumental

`boolean`

store\_for\_inpainting

`boolean`

sign\_with\_c2pa

`boolean`

audio

`string`URL to the generated music file.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/elevenlabs/music-v2/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/elevenlabs/music-v2/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/elevenlabs/music-v2/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/elevenlabs/music-v2/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/elevenlabs/music-v2/#page","headline":"ElevenLabs Music v2","description":"ElevenLabs Music v2 composes songs and instrumental tracks from a prompt or detailed composition plan.","url":"https://developers.cloudflare.com/ai/models/elevenlabs/music-v2/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Google's fast multimodal Gemini 2.5 model with strong reasoning and a 1M token context window.
title: Gemini 2.5 Flash
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 2.5 Flash

Text Generation • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-2.5-flash`

- Third-party
- Zero data retention

Google's fast multimodal Gemini 2.5 model with strong reasoning and a 1M token context window.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/gemini/) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.30</li><li>Output (per 1M tokens)$2.50</li><li>Cached input (per 1M tokens)$0.03</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-2.5-flash',
  { contents: [{ parts: [{ text: 'What are the three laws of thermodynamics?' }], role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the three laws of thermodynamics?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
The three laws of thermodynamics are fundamental principles that govern how energy is transferred and transformed in physical systems. They are:

1.  **The First Law of Thermodynamics (Law of Conservation of Energy)**
    *   **Statement:** Energy cannot be created or destroyed in an isolated system; it can only be transformed from one form to another.
    *   **Explanation:** This law means that the total amount of energy in the universe remains constant. When energy appears to be "lost," it has merely changed into a different form (e.g., chemical energy into heat, electrical energy into light and heat). Mathematically, for a closed system, it's often expressed as: $\Delta U = Q - W$, where $\Delta U$ is the change in the 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 (Law of Entropy Increase)**
    *   **Statement:** The total entropy of an isolated system can only increase over time, or remain constant in ideal cases; it never decreases.
    *   **Explanation:** Entropy is a measure of disorder or randomness within a system. This law essentially states that natural processes tend to move towards a state of greater disorder or randomness. For example, a broken glass won't spontaneously reassemble, and heat naturally flows from a hotter object to a colder one, not the other way around. This law also implies that no heat engine can be 100% efficient because some energy will always be lost to increasing the entropy of the surroundings (often as waste heat).

3.  **The Third Law of Thermodynamics**
    *   **Statement:** As a system approaches absolute zero, its entropy approaches a constant minimum value. For a perfect crystal at absolute zero (0 Kelvin or -273.15 °C), the entropy is exactly zero.
    *   **Explanation:** This law provides a fundamental reference point for the measurement of entropy. It means that at absolute zero, all molecular motion would cease, and the system would be in its most ordered possible state (a perfect crystal with no defects). In practice, reaching absolute zero is impossible, as doing so would require an infinite number of steps, each becoming progressively harder.

These three laws are cornerstones of physics and chemistry, explaining a vast range of phenomena from the operation of engines to the direction of chemical reactions and the very evolution of the universe.
```

```json
{
  "candidates": [
    {
      "avgLogprobs": -0.7025290479937804,
      "content": {
        "parts": [
          {
            "text": "The three laws of thermodynamics are fundamental principles that govern how energy is transferred and transformed in physical systems. They are:\n\n1.  **The First Law of Thermodynamics (Law of Conservation of Energy)**\n    *   **Statement:** Energy cannot be created or destroyed in an isolated system; it can only be transformed from one form to another.\n    *   **Explanation:** This law means that the total amount of energy in the universe remains constant. When energy appears to be \"lost,\" it has merely changed into a different form (e.g., chemical energy into heat, electrical energy into light and heat). Mathematically, for a closed system, it's often expressed as: $\\Delta U = Q - W$, where $\\Delta U$ is the change in the internal energy of the system, $Q$ is the heat added to the system, and $W$ is the work done *by* the system.\n\n2.  **The Second Law of Thermodynamics (Law of Entropy Increase)**\n    *   **Statement:** The total entropy of an isolated system can only increase over time, or remain constant in ideal cases; it never decreases.\n    *   **Explanation:** Entropy is a measure of disorder or randomness within a system. This law essentially states that natural processes tend to move towards a state of greater disorder or randomness. For example, a broken glass won't spontaneously reassemble, and heat naturally flows from a hotter object to a colder one, not the other way around. This law also implies that no heat engine can be 100% efficient because some energy will always be lost to increasing the entropy of the surroundings (often as waste heat).\n\n3.  **The Third Law of Thermodynamics**\n    *   **Statement:** As a system approaches absolute zero, its entropy approaches a constant minimum value. For a perfect crystal at absolute zero (0 Kelvin or -273.15 °C), the entropy is exactly zero.\n    *   **Explanation:** This law provides a fundamental reference point for the measurement of entropy. It means that at absolute zero, all molecular motion would cease, and the system would be in its most ordered possible state (a perfect crystal with no defects). In practice, reaching absolute zero is impossible, as doing so would require an infinite number of steps, each becoming progressively harder.\n\nThese three laws are cornerstones of physics and chemistry, explaining a vast range of phenomena from the operation of engines to the direction of chemical reactions and the very evolution of the universe."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP"
    }
  ],
  "createTime": "2026-04-28T19:34:47.652835Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-flash",
  "responseId": "1wvxaaPsJ8CG998Pn665-Ag",
  "usageMetadata": {
    "candidatesTokenCount": 515,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 515
      }
    ],
    "promptTokenCount": 8,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 8
      }
    ],
    "thoughtsTokenCount": 1020,
    "totalTokenCount": 1543,
    "trafficType": "ON_DEMAND"
  }
}
```

## Examples

<details>

<summary>**With System Instruction** — Using a system instruction to set context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-2.5-flash',
  {
    contents: [{ parts: [{ text: 'How do I read a JSON file in Python?' }], role: 'user' }],
    generationConfig: { temperature: 0.3 },
    systemInstruction: {
      parts: [{ text: 'You are a helpful coding assistant specializing in Python.' }],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "How do I read a JSON file in Python?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "temperature": 0.3
    },
    "systemInstruction": {
      "parts": [
        {
          "text": "You are a helpful coding assistant specializing in Python."
        }
      ]
    }
  }
}'
```

````
Reading a JSON (JavaScript Object Notation) file in Python is straightforward, thanks to the built-in `json` module.

Here's a step-by-step guide with examples:

---

### 1. The `json` Module

Python's `json` module provides methods for working with JSON data. The two primary methods you'll use for reading are:

*   **`json.load()`**: Reads JSON data from a file-like object (e.g., a file opened with `open()`).
*   **`json.loads()`**: Reads JSON data from a string.

---

### 2. Example: Reading a JSON File (`json.load()`)

This is the most common way to read a JSON file.

**Step 1: Create a sample JSON file**

Let's create a file named `data.json` with the following content:

```json
{
  "name": "Alice",
  "age": 30,
  "isStudent": false,
  "courses": [
    {"title": "Math", "credits": 3},
    {"title": "Science", "credits": 4}
  ],
  "address": null
}
```

**Step 2: Python code to read the file**

```python
import json

file_path = 'data.json'

try:
    # Open the JSON file in read mode ('r')
    # The 'with' statement ensures the file is properly closed even if errors occur.
    with open(file_path, 'r', encoding='utf-8') as file:
        # Use json.load() to parse the JSON data from the file
        data = json.load(file)

    print("JSON data successfully loaded:")
    print(data)
    print(f"\nType of loaded data: {type(data)}")

    # You can now access the data like a Python dictionary or list
    print(f"Name: {data['name']}")
    print(f"Age: {data['age']}")
    print(f"First course title: {data['courses'][0]['title']}")

except FileNotFoundError:
    print(f"Error: The file '{file_path}' was not found.")
except json.JSONDecodeError:
    print(f"Error: Could not decode JSON from '{file_path}'. Check its format.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

```

**Explanation:**

1.  **`import json`**: Imports the necessary module.
2.  **`with open(file_path, 'r', encoding='utf-8') as file:`**:
    *   Opens the file specified by `file_path`.
    *   `'r'` indicates read mode.
    *   `encoding='utf-8'` is a good practice, especially if your JSON might contain non-ASCII characters.
    *   The `with` statement is a context manager that ensures the file is automatically closed when the block is exited, even if errors occur.
3.  **`data = json.load(file)`**: This is the core line. It reads the entire content of the `file` object, parses it as JSON, and converts it into a corresponding Python object (usually a dictionary or a list).
4.  **Error Handling**: The `try...except` block is crucial for robust code:
    *   `FileNotFoundError`: Catches the error if the specified file doesn't exist.
    *   `json.JSONDecodeError`: Catches errors if the file content is not valid JSON.
    *   `Exception as e`: Catches any other unexpected errors.

---

### 3. Example: Reading JSON from a String (`json.loads()`)

Sometimes, you might receive JSON data as a string (e.g., from a web API response). In such cases, you use `json.loads()`.

```python
import json

json_string_data = '''
{
  "product": "Laptop",
  "price": 1200.50,
  "inStock": true,
  "features": ["lightweight", "fast processor"]
}
'''

try:
    # Use json.loads() to parse the JSON data from a string
    data_from_string = json.loads(json_string_data)

    print("\nJSON data from string successfully loaded:")
    print(data_from_string)
    print(f"Type of loaded data: {type(data_from_string)}")

    print(f"Product: {data_from_string['product']}")
    print(f"Price: ${data_from_string['price']}")

except json.JSONDecodeError:
    print("Error: Could not decode JSON from the string. Check its format.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
```

---

### 4. JSON to Python Type Conversion

When `json.load()` or `json.loads()` parses JSON, it converts JSON data types to their corresponding Python types:

| JSON Type     | Python Type     |
| :------------ | :-------------- |
| object        | `dict`          |
| array         | `list`          |
| string        | `str`           |
| number        | `int` or `float` |
| boolean       | `bool`          |
| null          | `None`          |

---

### Best Practices:

*   **Always use `with open(...)`**: It's safer and handles file closing automatically.
*   **Include `encoding='utf-8'`**: This prevents issues with character encoding, especially for international data.
*   **Implement Error Handling**: Use `try...except` blocks to gracefully handle `FileNotFoundError` and `json.JSONDecodeError`.
*   **Understand `load` vs. `loads`**: Use `load` for file objects and `loads` for strings.
````

```json
{
  "candidates": [
    {
      "avgLogprobs": -0.20984612667199337,
      "content": {
        "parts": [
          {
            "text": "Reading a JSON (JavaScript Object Notation) file in Python is straightforward, thanks to the built-in `json` module.\n\nHere's a step-by-step guide with examples:\n\n---\n\n### 1. The `json` Module\n\nPython's `json` module provides methods for working with JSON data. The two primary methods you'll use for reading are:\n\n*   **`json.load()`**: Reads JSON data from a file-like object (e.g., a file opened with `open()`).\n*   **`json.loads()`**: Reads JSON data from a string.\n\n---\n\n### 2. Example: Reading a JSON File (`json.load()`)\n\nThis is the most common way to read a JSON file.\n\n**Step 1: Create a sample JSON file**\n\nLet's create a file named `data.json` with the following content:\n\n```json\n{\n  \"name\": \"Alice\",\n  \"age\": 30,\n  \"isStudent\": false,\n  \"courses\": [\n    {\"title\": \"Math\", \"credits\": 3},\n    {\"title\": \"Science\", \"credits\": 4}\n  ],\n  \"address\": null\n}\n```\n\n**Step 2: Python code to read the file**\n\n```python\nimport json\n\nfile_path = 'data.json'\n\ntry:\n    # Open the JSON file in read mode ('r')\n    # The 'with' statement ensures the file is properly closed even if errors occur.\n    with open(file_path, 'r', encoding='utf-8') as file:\n        # Use json.load() to parse the JSON data from the file\n        data = json.load(file)\n\n    print(\"JSON data successfully loaded:\")\n    print(data)\n    print(f\"\\nType of loaded data: {type(data)}\")\n\n    # You can now access the data like a Python dictionary or list\n    print(f\"Name: {data['name']}\")\n    print(f\"Age: {data['age']}\")\n    print(f\"First course title: {data['courses'][0]['title']}\")\n\nexcept FileNotFoundError:\n    print(f\"Error: The file '{file_path}' was not found.\")\nexcept json.JSONDecodeError:\n    print(f\"Error: Could not decode JSON from '{file_path}'. Check its format.\")\nexcept Exception as e:\n    print(f\"An unexpected error occurred: {e}\")\n\n```\n\n**Explanation:**\n\n1.  **`import json`**: Imports the necessary module.\n2.  **`with open(file_path, 'r', encoding='utf-8') as file:`**:\n    *   Opens the file specified by `file_path`.\n    *   `'r'` indicates read mode.\n    *   `encoding='utf-8'` is a good practice, especially if your JSON might contain non-ASCII characters.\n    *   The `with` statement is a context manager that ensures the file is automatically closed when the block is exited, even if errors occur.\n3.  **`data = json.load(file)`**: This is the core line. It reads the entire content of the `file` object, parses it as JSON, and converts it into a corresponding Python object (usually a dictionary or a list).\n4.  **Error Handling**: The `try...except` block is crucial for robust code:\n    *   `FileNotFoundError`: Catches the error if the specified file doesn't exist.\n    *   `json.JSONDecodeError`: Catches errors if the file content is not valid JSON.\n    *   `Exception as e`: Catches any other unexpected errors.\n\n---\n\n### 3. Example: Reading JSON from a String (`json.loads()`)\n\nSometimes, you might receive JSON data as a string (e.g., from a web API response). In such cases, you use `json.loads()`.\n\n```python\nimport json\n\njson_string_data = '''\n{\n  \"product\": \"Laptop\",\n  \"price\": 1200.50,\n  \"inStock\": true,\n  \"features\": [\"lightweight\", \"fast processor\"]\n}\n'''\n\ntry:\n    # Use json.loads() to parse the JSON data from a string\n    data_from_string = json.loads(json_string_data)\n\n    print(\"\\nJSON data from string successfully loaded:\")\n    print(data_from_string)\n    print(f\"Type of loaded data: {type(data_from_string)}\")\n\n    print(f\"Product: {data_from_string['product']}\")\n    print(f\"Price: ${data_from_string['price']}\")\n\nexcept json.JSONDecodeError:\n    print(\"Error: Could not decode JSON from the string. Check its format.\")\nexcept Exception as e:\n    print(f\"An unexpected error occurred: {e}\")\n```\n\n---\n\n### 4. JSON to Python Type Conversion\n\nWhen `json.load()` or `json.loads()` parses JSON, it converts JSON data types to their corresponding Python types:\n\n| JSON Type     | Python Type     |\n| :------------ | :-------------- |\n| object        | `dict`          |\n| array         | `list`          |\n| string        | `str`           |\n| number        | `int` or `float` |\n| boolean       | `bool`          |\n| null          | `None`          |\n\n---\n\n### Best Practices:\n\n*   **Always use `with open(...)`**: It's safer and handles file closing automatically.\n*   **Include `encoding='utf-8'`**: This prevents issues with character encoding, especially for international data.\n*   **Implement Error Handling**: Use `try...except` blocks to gracefully handle `FileNotFoundError` and `json.JSONDecodeError`.\n*   **Understand `load` vs. `loads`**: Use `load` for file objects and `loads` for strings."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP"
    }
  ],
  "createTime": "2026-04-28T19:34:48.848405Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-flash",
  "responseId": "2AvxaZXkM5mA6tkPxraQ6Qg",
  "usageMetadata": {
    "candidatesTokenCount": 1320,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 1320
      }
    ],
    "promptTokenCount": 20,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 20
      }
    ],
    "thoughtsTokenCount": 1357,
    "totalTokenCount": 2697,
    "trafficType": "ON_DEMAND"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-2.5-flash',
  {
    contents: [
      {
        parts: [{ text: 'I need help planning a road trip from San Francisco to Los Angeles.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "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: 'model',
      },
      { parts: [{ text: 'Yes, what are some good places to stop?' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 2048 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I need help planning a road trip from San Francisco to Los Angeles."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "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": "model"
      },
      {
        "parts": [
          {
            "text": "Yes, what are some good places to stop?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 2048
    }
  }
}'
```

```
Okay, you've got two main routes, each with its own character and fantastic stops
```

```json
{
  "candidates": [
    {
      "avgLogprobs": -10.623407151963976,
      "content": {
        "parts": [
          {
            "text": "Okay, you've got two main routes, each with its own character and fantastic stops"
          }
        ],
        "role": "model"
      },
      "finishReason": "MAX_TOKENS"
    }
  ],
  "createTime": "2026-04-28T19:34:57.011971Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-flash",
  "responseId": "4QvxacNd9bf33w-WuK35Ag",
  "usageMetadata": {
    "candidatesTokenCount": 18,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 18
      }
    ],
    "promptTokenCount": 64,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 64
      }
    ],
    "thoughtsTokenCount": 478,
    "totalTokenCount": 560,
    "trafficType": "ON_DEMAND"
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'google/gemini-2.5-flash',
  {
    contents: [
      {
        parts: [{ text: 'Write a short story opening about a detective finding an unusual clue.' }],
        role: 'user',
      },
    ],
    generationConfig: { maxOutputTokens: 1500, temperature: 0.8 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a short story opening about a detective finding an unusual clue."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 1500,
      "temperature": 0.8
    }
  }
}'
```

```
The rain had been a relentless drumbeat against
```

```json
{
  "candidates": [
    {
      "avgLogprobs": -13.157335069444445,
      "content": {
        "parts": [
          {
            "text": "The rain had been a relentless drumbeat against"
          }
        ],
        "role": "model"
      },
      "finishReason": "MAX_TOKENS"
    }
  ],
  "createTime": "2026-04-28T19:35:01.318796Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-flash",
  "responseId": "5Qvxacy6E6CV9LsP2P_v0Ak",
  "usageMetadata": {
    "candidatesTokenCount": 9,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 9
      }
    ],
    "promptTokenCount": 13,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 13
      }
    ],
    "thoughtsTokenCount": 287,
    "totalTokenCount": 309,
    "trafficType": "ON_DEMAND"
  }
}
```

</details>

## Parameters

Schema variant

Generate ContentChat Completions

▶contents\[]

`array`required

▶systemInstruction{}

`object`

▶generationConfig{}

`object`

▶safetySettings\[]

`array`

▶tools\[]

`array`

toolConfig

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶candidates\[]

`array`

▶usageMetadata{}

`object`

modelVersion

`string`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash/#page","headline":"Gemini 2.5 Flash","description":"Google's fast multimodal Gemini 2.5 model with strong reasoning and a 1M token context window.","url":"https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Google's lightest and most cost-efficient Gemini 2.5 model for high-throughput tasks.
title: Gemini 2.5 Flash Lite
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 2.5 Flash Lite

Text Generation • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash-lite/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-2.5-flash-lite`

- Third-party
- Zero data retention

Google's lightest and most cost-efficient Gemini 2.5 model for high-throughput tasks.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/gemini/) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.10</li><li>Output (per 1M tokens)$0.40</li><li>Cached input (per 1M tokens)$0.01</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-2.5-flash-lite',
  { contents: [{ parts: [{ text: 'What are the three laws of thermodynamics?' }], role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-flash-lite",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the three laws of thermodynamics?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
The three laws of thermodynamics are fundamental principles that describe the behavior of energy and matter. Here they are:

1.  **The Zeroth Law of Thermodynamics:**
    *   **Statement:** If two systems are each in thermal equilibrium with a third system, then they are in thermal equilibrium with each other.
    *   **In simpler terms:** This law essentially defines the concept of temperature. If object A is the same temperature as object B, and object B is the same temperature as object C, then object A must also be the same temperature as object C. It allows us to use thermometers to measure temperature, as they achieve thermal equilibrium with the object being measured.

2.  **The First Law of Thermodynamics (Conservation of Energy):**
    *   **Statement:** Energy cannot be created or destroyed, only transferred or changed from one form to another. In a closed system, the total energy remains constant.
    *   **In simpler terms:** This is the law of conservation of energy. It means that the amount of energy in the universe is fixed. You can't get energy out of nowhere, and you can't make energy disappear. It can be converted, for example, from chemical energy in fuel to heat and kinetic energy in a car engine, but the total amount of energy stays the same.
    *   **Mathematical representation:** $\Delta U = Q - W$
        *   $\Delta U$ is the change in internal energy of the system.
        *   $Q$ is the heat added to the system.
        *   $W$ is the work done by the system.

3.  **The Second Law of Thermodynamics (Entropy):**
    *   **Statement:** In any isolated system, the total entropy (a measure of disorder or randomness) can only increase over time, or remain constant in ideal cases where the system is in a steady state or undergoing a reversible process. It never decreases.
    *   **In simpler terms:** This law explains why certain processes happen spontaneously and others don't. It's often described as "things tend to get messier." Heat naturally flows from hotter objects to colder objects, never the other way around spontaneously. Engines are never 100% efficient because some energy is always lost as unusable heat, increasing the overall entropy of the universe.
    *   **Implications:**
        *   It dictates the direction of spontaneous processes.
        *   It explains why perpetual motion machines of the second kind (which would convert all heat into work without any losses) are impossible.
        *   It suggests that the universe is heading towards a state of maximum entropy, often referred to as "heat death."

These three laws are fundamental to understanding how energy works in everything from chemical reactions and engines to living organisms and the universe as a whole.
```

```json
{
  "candidates": [
    {
      "avgLogprobs": -0.2047232930570739,
      "content": {
        "parts": [
          {
            "text": "The three laws of thermodynamics are fundamental principles that describe the behavior of energy and matter. Here they are:\n\n1.  **The Zeroth Law of Thermodynamics:**\n    *   **Statement:** If two systems are each in thermal equilibrium with a third system, then they are in thermal equilibrium with each other.\n    *   **In simpler terms:** This law essentially defines the concept of temperature. If object A is the same temperature as object B, and object B is the same temperature as object C, then object A must also be the same temperature as object C. It allows us to use thermometers to measure temperature, as they achieve thermal equilibrium with the object being measured.\n\n2.  **The First Law of Thermodynamics (Conservation of Energy):**\n    *   **Statement:** Energy cannot be created or destroyed, only transferred or changed from one form to another. In a closed system, the total energy remains constant.\n    *   **In simpler terms:** This is the law of conservation of energy. It means that the amount of energy in the universe is fixed. You can't get energy out of nowhere, and you can't make energy disappear. It can be converted, for example, from chemical energy in fuel to heat and kinetic energy in a car engine, but the total amount of energy stays the same.\n    *   **Mathematical representation:** $\\Delta U = Q - W$\n        *   $\\Delta U$ is the change in internal energy of the system.\n        *   $Q$ is the heat added to the system.\n        *   $W$ is the work done by the system.\n\n3.  **The Second Law of Thermodynamics (Entropy):**\n    *   **Statement:** In any isolated system, the total entropy (a measure of disorder or randomness) can only increase over time, or remain constant in ideal cases where the system is in a steady state or undergoing a reversible process. It never decreases.\n    *   **In simpler terms:** This law explains why certain processes happen spontaneously and others don't. It's often described as \"things tend to get messier.\" Heat naturally flows from hotter objects to colder objects, never the other way around spontaneously. Engines are never 100% efficient because some energy is always lost as unusable heat, increasing the overall entropy of the universe.\n    *   **Implications:**\n        *   It dictates the direction of spontaneous processes.\n        *   It explains why perpetual motion machines of the second kind (which would convert all heat into work without any losses) are impossible.\n        *   It suggests that the universe is heading towards a state of maximum entropy, often referred to as \"heat death.\"\n\nThese three laws are fundamental to understanding how energy works in everything from chemical reactions and engines to living organisms and the universe as a whole."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP"
    }
  ],
  "createTime": "2026-04-28T19:34:41.622271Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-flash-lite",
  "responseId": "0Qvxab_9Jc-R9LsPkdy1uAo",
  "usageMetadata": {
    "candidatesTokenCount": 586,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 586
      }
    ],
    "promptTokenCount": 8,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 8
      }
    ],
    "totalTokenCount": 594,
    "trafficType": "ON_DEMAND"
  }
}
```

## Examples

<details>

<summary>**With System Instruction** — Using a system instruction to set context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-2.5-flash-lite',
  {
    contents: [{ parts: [{ text: 'How do I read a JSON file in Python?' }], role: 'user' }],
    generationConfig: { temperature: 0.3 },
    systemInstruction: {
      parts: [{ text: 'You are a helpful coding assistant specializing in Python.' }],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-flash-lite",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "How do I read a JSON file in Python?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "temperature": 0.3
    },
    "systemInstruction": {
      "parts": [
        {
          "text": "You are a helpful coding assistant specializing in Python."
        }
      ]
    }
  }
}'
```

````
Reading a JSON file in Python is a straightforward process thanks to the built-in `json` module. Here's a breakdown of how to do it, along with explanations and examples:

**The Core Concept**

JSON (JavaScript Object Notation) is a lightweight data-interchange format. Python's `json` module provides functions to:

*   **`json.load()`**: Reads a JSON document from a file-like object and parses it into a Python object (dictionaries, lists, strings, numbers, booleans, and `None`).
*   **`json.loads()`**: Reads a JSON document from a string and parses it into a Python object.

Since you're asking about reading from a file, `json.load()` is the function you'll primarily use.

**Steps to Read a JSON File**

1.  **Import the `json` module:**
    ```python
    import json
    ```

2.  **Open the JSON file:** You need to open the file in read mode (`'r'`). It's best practice to use a `with` statement, which ensures the file is automatically closed even if errors occur.
    ```python
    with open('your_file.json', 'r') as f:
        # File operations will go here
    ```
    Replace `'your_file.json'` with the actual path to your JSON file.

3.  **Load the JSON data:** Use `json.load()` to read the content from the opened file object and convert it into a Python data structure.
    ```python
    with open('your_file.json', 'r') as f:
        data = json.load(f)
    ```

**Example**

Let's assume you have a JSON file named `data.json` with the following content:

```json
{
  "name": "Alice",
  "age": 30,
  "isStudent": false,
  "courses": [
    {"title": "Math", "credits": 3},
    {"title": "Science", "credits": 4}
  ],
  "address": {
    "street": "123 Main St",
    "city": "Anytown"
  }
}
```

Here's the Python code to read this file:

```python
import json

try:
    with open('data.json', 'r') as f:
        data = json.load(f)

    # Now 'data' is a Python dictionary
    print(f"Name: {data['name']}")
    print(f"Age: {data['age']}")
    print(f"Is Student: {data['isStudent']}")
    print("Courses:")
    for course in data['courses']:
        print(f"  - {course['title']} ({course['credits']} credits)")
    print(f"City: {data['address']['city']}")

except FileNotFoundError:
    print("Error: The file 'data.json' was not found.")
except json.JSONDecodeError:
    print("Error: Could not decode JSON from the file. Please check its format.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
```

**Explanation of the Example:**

*   **`import json`**: Imports the necessary module.
*   **`with open('data.json', 'r') as f:`**: Opens `data.json` in read mode. The file object is assigned to the variable `f`.
*   **`data = json.load(f)`**: Reads the entire content of the file `f` and parses it. The resulting Python object (in this case, a dictionary) is stored in the `data` variable.
*   **Accessing Data**: You can then access the data using standard Python dictionary and list indexing:
    *   `data['name']` accesses the value associated with the "name" key.
    *   `data['courses']` accesses the list of courses.
    *   `data['courses'][0]` accesses the first course dictionary.
    *   `data['courses'][0]['title']` accesses the title of the first course.
*   **Error Handling**: The `try...except` block is crucial for robust code.
    *   `FileNotFoundError`: Catches the case where `data.json` doesn't exist.
    *   `json.JSONDecodeError`: Catches errors if the file's content is not valid JSON.
    *   `Exception`: A general catch-all for any other unexpected errors.

**Reading JSON from a String**

If you have JSON data as a string (e.g., from an API response), you'd use `json.loads()`:

```python
import json

json_string = """
{
  "product": "Laptop",
  "price": 1200.50,
  "inStock": true
}
"""

try:
    data = json.loads(json_string)
    print(f"Product: {data['product']}")
    print(f"Price: ${data['price']:.2f}")
    print(f"In Stock: {data['inStock']}")
except json.JSONDecodeError:
    print("Error: Could not decode JSON from the string.")
```

**Key Considerations:**

*   **File Encoding:** By default, `open()` uses the system's default encoding. If your JSON file uses a different encoding (like UTF-8, which is common), you should specify it:
    ```python
    with open('your_file.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    ```
*   **JSON Structure:** The `json.load()` function will convert JSON data types to their Python equivalents:
    *   JSON objects (`{}`) become Python dictionaries (`dict`).
    *   JSON arrays (`[]`) become Python lists (`list`).
    *   JSON strings (`"..."`) become Python strings (`str`).
    *   JSON numbers (integers and floats) become Python integers (`int`) or floats (`float`).
    *   JSON booleans (`true`, `false`) become Python booleans (`True`, `False`).
    *   JSON `null` becomes Python `None`.
*   **Error Handling is Essential:** Always include error handling to gracefully manage situations where the file is missing or contains invalid JSON.

By following these steps, you can effectively read and work with JSON data in your Python applications.
````

```json
{
  "candidates": [
    {
      "avgLogprobs": -0.05239303652533901,
      "content": {
        "parts": [
          {
            "text": "Reading a JSON file in Python is a straightforward process thanks to the built-in `json` module. Here's a breakdown of how to do it, along with explanations and examples:\n\n**The Core Concept**\n\nJSON (JavaScript Object Notation) is a lightweight data-interchange format. Python's `json` module provides functions to:\n\n*   **`json.load()`**: Reads a JSON document from a file-like object and parses it into a Python object (dictionaries, lists, strings, numbers, booleans, and `None`).\n*   **`json.loads()`**: Reads a JSON document from a string and parses it into a Python object.\n\nSince you're asking about reading from a file, `json.load()` is the function you'll primarily use.\n\n**Steps to Read a JSON File**\n\n1.  **Import the `json` module:**\n    ```python\n    import json\n    ```\n\n2.  **Open the JSON file:** You need to open the file in read mode (`'r'`). It's best practice to use a `with` statement, which ensures the file is automatically closed even if errors occur.\n    ```python\n    with open('your_file.json', 'r') as f:\n        # File operations will go here\n    ```\n    Replace `'your_file.json'` with the actual path to your JSON file.\n\n3.  **Load the JSON data:** Use `json.load()` to read the content from the opened file object and convert it into a Python data structure.\n    ```python\n    with open('your_file.json', 'r') as f:\n        data = json.load(f)\n    ```\n\n**Example**\n\nLet's assume you have a JSON file named `data.json` with the following content:\n\n```json\n{\n  \"name\": \"Alice\",\n  \"age\": 30,\n  \"isStudent\": false,\n  \"courses\": [\n    {\"title\": \"Math\", \"credits\": 3},\n    {\"title\": \"Science\", \"credits\": 4}\n  ],\n  \"address\": {\n    \"street\": \"123 Main St\",\n    \"city\": \"Anytown\"\n  }\n}\n```\n\nHere's the Python code to read this file:\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r') as f:\n        data = json.load(f)\n\n    # Now 'data' is a Python dictionary\n    print(f\"Name: {data['name']}\")\n    print(f\"Age: {data['age']}\")\n    print(f\"Is Student: {data['isStudent']}\")\n    print(\"Courses:\")\n    for course in data['courses']:\n        print(f\"  - {course['title']} ({course['credits']} credits)\")\n    print(f\"City: {data['address']['city']}\")\n\nexcept FileNotFoundError:\n    print(\"Error: The file 'data.json' was not found.\")\nexcept json.JSONDecodeError:\n    print(\"Error: Could not decode JSON from the file. Please check its format.\")\nexcept Exception as e:\n    print(f\"An unexpected error occurred: {e}\")\n```\n\n**Explanation of the Example:**\n\n*   **`import json`**: Imports the necessary module.\n*   **`with open('data.json', 'r') as f:`**: Opens `data.json` in read mode. The file object is assigned to the variable `f`.\n*   **`data = json.load(f)`**: Reads the entire content of the file `f` and parses it. The resulting Python object (in this case, a dictionary) is stored in the `data` variable.\n*   **Accessing Data**: You can then access the data using standard Python dictionary and list indexing:\n    *   `data['name']` accesses the value associated with the \"name\" key.\n    *   `data['courses']` accesses the list of courses.\n    *   `data['courses'][0]` accesses the first course dictionary.\n    *   `data['courses'][0]['title']` accesses the title of the first course.\n*   **Error Handling**: The `try...except` block is crucial for robust code.\n    *   `FileNotFoundError`: Catches the case where `data.json` doesn't exist.\n    *   `json.JSONDecodeError`: Catches errors if the file's content is not valid JSON.\n    *   `Exception`: A general catch-all for any other unexpected errors.\n\n**Reading JSON from a String**\n\nIf you have JSON data as a string (e.g., from an API response), you'd use `json.loads()`:\n\n```python\nimport json\n\njson_string = \"\"\"\n{\n  \"product\": \"Laptop\",\n  \"price\": 1200.50,\n  \"inStock\": true\n}\n\"\"\"\n\ntry:\n    data = json.loads(json_string)\n    print(f\"Product: {data['product']}\")\n    print(f\"Price: ${data['price']:.2f}\")\n    print(f\"In Stock: {data['inStock']}\")\nexcept json.JSONDecodeError:\n    print(\"Error: Could not decode JSON from the string.\")\n```\n\n**Key Considerations:**\n\n*   **File Encoding:** By default, `open()` uses the system's default encoding. If your JSON file uses a different encoding (like UTF-8, which is common), you should specify it:\n    ```python\n    with open('your_file.json', 'r', encoding='utf-8') as f:\n        data = json.load(f)\n    ```\n*   **JSON Structure:** The `json.load()` function will convert JSON data types to their Python equivalents:\n    *   JSON objects (`{}`) become Python dictionaries (`dict`).\n    *   JSON arrays (`[]`) become Python lists (`list`).\n    *   JSON strings (`\"...\"`) become Python strings (`str`).\n    *   JSON numbers (integers and floats) become Python integers (`int`) or floats (`float`).\n    *   JSON booleans (`true`, `false`) become Python booleans (`True`, `False`).\n    *   JSON `null` becomes Python `None`.\n*   **Error Handling is Essential:** Always include error handling to gracefully manage situations where the file is missing or contains invalid JSON.\n\nBy following these steps, you can effectively read and work with JSON data in your Python applications."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP"
    }
  ],
  "createTime": "2026-04-28T19:34:41.673305Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-flash-lite",
  "responseId": "0QvxaZmMKdSNq8YPyLuh0AQ",
  "usageMetadata": {
    "candidatesTokenCount": 1438,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 1438
      }
    ],
    "promptTokenCount": 20,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 20
      }
    ],
    "totalTokenCount": 1458,
    "trafficType": "ON_DEMAND"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-2.5-flash-lite',
  {
    contents: [
      {
        parts: [{ text: 'I need help planning a road trip from San Francisco to Los Angeles.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "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: 'model',
      },
      { parts: [{ text: 'Yes, what are some good places to stop?' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 2048 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-flash-lite",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I need help planning a road trip from San Francisco to Los Angeles."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "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": "model"
      },
      {
        "parts": [
          {
            "text": "Yes, what are some good places to stop?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 2048
    }
  }
}'
```

```
Absolutely! The drive from San Francisco to Los Angeles offers a variety of stunning scenery and charming towns. Here are some of the most popular and highly recommended stops, depending on your interests and how much time you have:

**The Classic Coastal Route (Highway 1 - the most scenic, but can be slower):**

This is the iconic drive for a reason! Expect breathtaking ocean views, dramatic cliffs, and charming seaside towns. Be aware that sections of Highway 1 can be prone to closures due to landslides, so always check road conditions before you go (Caltrans is your friend!).

*   **Monterey:**
    *   **Monterey Bay Aquarium:** World-renowned and a must-visit. Plan for at least 2-3 hours.
    *   **Cannery Row:** Historic waterfront street, now filled with shops, restaurants, and hotels.
    *   **Old Fisherman's Wharf:** Great for whale watching tours, seafood, and souvenirs.
    *   **17-Mile Drive (Pebble Beach):** A private toll road with stunning coastal scenery, iconic golf courses, and the Lone Cypress.
*   **Carmel-by-the-Sea:**
    *   **Charming Village:** Wander through art galleries, boutiques, and quaint cottages.
    *   **Carmel Beach:** Beautiful white sand beach, perfect for a stroll.
    *   **Mission San Carlos Borroméo del río Carmelo:** A historic Spanish mission.
*   **Big Sur:** This is the heart of the coastal beauty.
    *   **Bixby Creek Bridge:** An iconic photo opportunity.
    *   **McWay Falls (Julia Pfeiffer Burns State Park):** A waterfall that cascades onto the beach.
    *   **Point Reyes Lighthouse (requires a detour, but worth it for lighthouse lovers):** Dramatic views.
    *   **Hiking trails:** Numerous options for all skill levels.
    *   **Nepenthe:** A famous restaurant with incredible ocean views, perfect for a lunch or drink.
*   **Hearst Castle (San Simeon):**
    *   **Opulent Estate:** A fascinating glimpse into the life of William Randolph Hearst. Book tours in advance, as they often sell out.
*   **Cambria:**
    *   **Moonstone Beach:** Known for its smooth, colorful "moonstones."
    *
```

```json
{
  "candidates": [
    {
      "avgLogprobs": -0.2926192626953125,
      "content": {
        "parts": [
          {
            "text": "Absolutely! The drive from San Francisco to Los Angeles offers a variety of stunning scenery and charming towns. Here are some of the most popular and highly recommended stops, depending on your interests and how much time you have:\n\n**The Classic Coastal Route (Highway 1 - the most scenic, but can be slower):**\n\nThis is the iconic drive for a reason! Expect breathtaking ocean views, dramatic cliffs, and charming seaside towns. Be aware that sections of Highway 1 can be prone to closures due to landslides, so always check road conditions before you go (Caltrans is your friend!).\n\n*   **Monterey:**\n    *   **Monterey Bay Aquarium:** World-renowned and a must-visit. Plan for at least 2-3 hours.\n    *   **Cannery Row:** Historic waterfront street, now filled with shops, restaurants, and hotels.\n    *   **Old Fisherman's Wharf:** Great for whale watching tours, seafood, and souvenirs.\n    *   **17-Mile Drive (Pebble Beach):** A private toll road with stunning coastal scenery, iconic golf courses, and the Lone Cypress.\n*   **Carmel-by-the-Sea:**\n    *   **Charming Village:** Wander through art galleries, boutiques, and quaint cottages.\n    *   **Carmel Beach:** Beautiful white sand beach, perfect for a stroll.\n    *   **Mission San Carlos Borroméo del río Carmelo:** A historic Spanish mission.\n*   **Big Sur:** This is the heart of the coastal beauty.\n    *   **Bixby Creek Bridge:** An iconic photo opportunity.\n    *   **McWay Falls (Julia Pfeiffer Burns State Park):** A waterfall that cascades onto the beach.\n    *   **Point Reyes Lighthouse (requires a detour, but worth it for lighthouse lovers):** Dramatic views.\n    *   **Hiking trails:** Numerous options for all skill levels.\n    *   **Nepenthe:** A famous restaurant with incredible ocean views, perfect for a lunch or drink.\n*   **Hearst Castle (San Simeon):**\n    *   **Opulent Estate:** A fascinating glimpse into the life of William Randolph Hearst. Book tours in advance, as they often sell out.\n*   **Cambria:**\n    *   **Moonstone Beach:** Known for its smooth, colorful \"moonstones.\"\n    *   "
          }
        ],
        "role": "model"
      },
      "finishReason": "MAX_TOKENS"
    }
  ],
  "createTime": "2026-04-28T19:34:45.059845Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-flash-lite",
  "responseId": "1QvxacXTA6iaq8YP8M2gkAc",
  "usageMetadata": {
    "candidatesTokenCount": 500,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 500
      }
    ],
    "promptTokenCount": 64,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 64
      }
    ],
    "totalTokenCount": 564,
    "trafficType": "ON_DEMAND"
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'google/gemini-2.5-flash-lite',
  {
    contents: [
      {
        parts: [{ text: 'Write a short story opening about a detective finding an unusual clue.' }],
        role: 'user',
      },
    ],
    generationConfig: { maxOutputTokens: 1500, temperature: 0.8 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-flash-lite",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a short story opening about a detective finding an unusual clue."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 1500,
      "temperature": 0.8
    }
  }
}'
```

```
The air in the cramped apartment hung thick with the scent of stale cigarettes and something vaguely floral, a cloying perfume that did little to mask the metallic tang of dried blood. Detective Miles Corbin, a man whose trench coat seemed permanently etched with the grime of a thousand city streets, surveyed the scene with weary eyes. Another Tuesday, another victim. But this one, a young woman named Clara Bellweather, had left behind more than just a messy end to her life.

Miles knelt beside the overturned coffee table, its polished surface marred by a dark, sticky stain. He’d seen plenty of overturned furniture, plenty of blood. What made him pause, what pricked at his seasoned detective’s intuition, was the object nestled amidst the shattered ceramic mug and scattered papers. It was a single, perfectly preserved peacock feather.

Not just any feather, either. This one shimmered with an iridescent blues and greens, its eye a mesmerizing swirl of sapphire and emerald. It was impossibly vibrant, almost glowing against the drab carpet. Miles had seen exotic pets, he’d even seen a crime scene once that involved a boa constrictor, but never, in all his years, had he encountered a peacock feather at a homicide. And not just a stray one, mind you. This looked…placed. Deliberately. As if the killer, in their haste or their madness, had left behind a calling card of pure, unadulterated strangeness.
```

```json
{
  "candidates": [
    {
      "avgLogprobs": -0.5958368333719545,
      "content": {
        "parts": [
          {
            "text": "The air in the cramped apartment hung thick with the scent of stale cigarettes and something vaguely floral, a cloying perfume that did little to mask the metallic tang of dried blood. Detective Miles Corbin, a man whose trench coat seemed permanently etched with the grime of a thousand city streets, surveyed the scene with weary eyes. Another Tuesday, another victim. But this one, a young woman named Clara Bellweather, had left behind more than just a messy end to her life.\n\nMiles knelt beside the overturned coffee table, its polished surface marred by a dark, sticky stain. He’d seen plenty of overturned furniture, plenty of blood. What made him pause, what pricked at his seasoned detective’s intuition, was the object nestled amidst the shattered ceramic mug and scattered papers. It was a single, perfectly preserved peacock feather.\n\nNot just any feather, either. This one shimmered with an iridescent blues and greens, its eye a mesmerizing swirl of sapphire and emerald. It was impossibly vibrant, almost glowing against the drab carpet. Miles had seen exotic pets, he’d even seen a crime scene once that involved a boa constrictor, but never, in all his years, had he encountered a peacock feather at a homicide. And not just a stray one, mind you. This looked…placed. Deliberately. As if the killer, in their haste or their madness, had left behind a calling card of pure, unadulterated strangeness."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP"
    }
  ],
  "createTime": "2026-04-28T19:34:46.279307Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-flash-lite",
  "responseId": "1gvxaYuGEZafq8YP873hkQQ",
  "usageMetadata": {
    "candidatesTokenCount": 295,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 295
      }
    ],
    "promptTokenCount": 13,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 13
      }
    ],
    "totalTokenCount": 308,
    "trafficType": "ON_DEMAND"
  }
}
```

</details>

## Parameters

Schema variant

Generate ContentChat Completions

▶contents\[]

`array`required

▶systemInstruction{}

`object`

▶generationConfig{}

`object`

▶safetySettings\[]

`array`

▶tools\[]

`array`

toolConfig

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶candidates\[]

`array`

▶usageMetadata{}

`object`

modelVersion

`string`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash-lite/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash-lite/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash-lite/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash-lite/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash-lite/#page","headline":"Gemini 2.5 Flash Lite","description":"Google's lightest and most cost-efficient Gemini 2.5 model for high-throughput tasks.","url":"https://developers.cloudflare.com/ai/models/google/gemini-2.5-flash-lite/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Google's most capable Gemini 2.5 model with strong reasoning, thinking support, and a 1M token context window.
title: Gemini 2.5 Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 2.5 Pro

Text Generation • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-2.5-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-2.5-pro`

- Third-party
- Zero data retention

Google's most capable Gemini 2.5 model with strong reasoning, thinking support, and a 1M token context window.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/gemini/) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$1.25</li><li>Output (per 1M tokens)$10.00</li><li>Cached input (per 1M tokens)$0.125</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-2.5-pro',
  { contents: [{ parts: [{ text: 'What are the three laws of thermodynamics?' }], role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-pro",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the three laws of thermodynamics?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
Of course! The three laws of thermodynamics are fundamental principles in physics that describe the relationships between heat, energy, and work.

Here they are, explained from a simple "catchphrase" summary to a more detailed breakdown.

***

### A Quick Summary (The "Gambling" Analogy)

A popular, easy way to remember the laws is to think of them in terms of a game:

1.  **First Law:** You can't win. (You can't get more energy out than you put in.)
2.  **Second Law:** You can't break even. (You can't even get back the energy you put in, in a perfectly useful form.)
3.  **Third Law:** You can't quit the game. (You can't reach absolute zero and stop all energy.)

***

### The Detailed Explanation

Before the three main laws, it's helpful to understand the **Zeroth Law**, which was formulated after the others but is more fundamental.

#### The Zeroth Law of Thermodynamics: Defines Temperature
*   **Simple Statement:** Objects in thermal equilibrium are at the same temperature.
*   **Explanation:** If two systems are each in thermal equilibrium with a third system, then they are also in thermal equilibrium with each other. This law sounds obvious, but it's what makes thermometers work. When you put a thermometer in a cup of coffee, the thermometer and coffee reach thermal equilibrium. If you then use that thermometer on another cup and it gives the same reading, you know both cups are the same temperature without them ever having touched.

---

### 1. The First Law of Thermodynamics: Conservation of Energy

*   **Simple Statement:** Energy cannot be created or destroyed, only converted from one form to another.
*   **Explanation:** This is the thermodynamic version of the law of conservation of energy. It means that the total energy in a closed system is constant. If you add energy to a system (e.g., by heating it), that energy doesn't disappear. It either increases the system's internal energy (making it hotter) or is used by the system to do work on its surroundings (like a piston moving). You can't get free energy out of nothing.
*   **Everyday Example:** When you eat food, the chemical energy stored in the food is converted by your body into thermal energy (to keep you warm) and kinetic energy (to move your muscles). The energy isn't created; it's just transformed.

---

### 2. The Second Law of Thermodynamics: The Increase of Entropy

*   **Simple Statement:** The total entropy (disorder) of the universe always increases over time.
*   **Explanation:** This is arguably the most profound of the laws. It states that natural processes tend to move towards a state of greater disorder or randomness (entropy). Heat will always spontaneously flow from a hotter object to a colder object, never the other way around. This flow increases the overall entropy because the energy becomes more spread out and less "organized." Because of this law, no energy transfer is 100% efficient; some energy is always lost as waste heat, increasing the overall disorder of the universe.
*   **Everyday Example:** A hot cup of coffee will always cool down to room temperature. The concentrated heat (an ordered state) will spread out into the cooler, larger room (a more disordered state). You will never see a room-temperature cup of coffee spontaneously become hot by drawing heat from the air. Similarly, an ice cube melts in a warm room, moving from an ordered crystal structure to a disordered liquid.

---

### 3. The Third Law of Thermodynamics: Absolute Zero is Unreachable

*   **Simple Statement:** The entropy of a system approaches a minimum value as the temperature approaches absolute zero. It is impossible to reach absolute zero in a finite number of steps.
*   **Explanation:** Absolute zero (0 Kelvin or -273.15°C / -459.67°F) is the theoretical temperature at which all particle motion would completely stop. The Third Law states that as you get colder and closer to this temperature, the entropy of a perfect crystal becomes zero. However, the law also implies that it's physically impossible to ever reach absolute zero. Each step you take to cool a system gets you closer, but the effort required to remove the next bit of heat increases exponentially. You can get incredibly close, but you can never take that final step to get there.
*   **Everyday Example:** This law is less intuitive in daily life as it deals with extreme cold. But you can think of it like trying to create a perfect vacuum by pumping all the air out of a container. With each pump, you remove a fraction of the remaining air, so you get closer and closer to a perfect vacuum but never fully achieve it because there will always be *some* molecules left. Reaching absolute zero is a similar process of diminishing returns.

| Law | Simple Statement | Key Concept |
| :--- | :--- | :--- |
| **Zeroth** | Defines temperature. | Thermal Equilibrium |
| **First** | Energy is conserved. | Conservation of Energy |
| **Second**| Disorder (entropy) increases. | Entropy & The Arrow of Time |
| **Third** | Absolute zero is unreachable. | Absolute Zero & Minimum Entropy |
```

```json
{
  "candidates": [
    {
      "avgLogprobs": -0.3830967711048414,
      "content": {
        "parts": [
          {
            "text": "Of course! The three laws of thermodynamics are fundamental principles in physics that describe the relationships between heat, energy, and work.\n\nHere they are, explained from a simple \"catchphrase\" summary to a more detailed breakdown.\n\n***\n\n### A Quick Summary (The \"Gambling\" Analogy)\n\nA popular, easy way to remember the laws is to think of them in terms of a game:\n\n1.  **First Law:** You can't win. (You can't get more energy out than you put in.)\n2.  **Second Law:** You can't break even. (You can't even get back the energy you put in, in a perfectly useful form.)\n3.  **Third Law:** You can't quit the game. (You can't reach absolute zero and stop all energy.)\n\n***\n\n### The Detailed Explanation\n\nBefore the three main laws, it's helpful to understand the **Zeroth Law**, which was formulated after the others but is more fundamental.\n\n#### The Zeroth Law of Thermodynamics: Defines Temperature\n*   **Simple Statement:** Objects in thermal equilibrium are at the same temperature.\n*   **Explanation:** If two systems are each in thermal equilibrium with a third system, then they are also in thermal equilibrium with each other. This law sounds obvious, but it's what makes thermometers work. When you put a thermometer in a cup of coffee, the thermometer and coffee reach thermal equilibrium. If you then use that thermometer on another cup and it gives the same reading, you know both cups are the same temperature without them ever having touched.\n\n---\n\n### 1. The First Law of Thermodynamics: Conservation of Energy\n\n*   **Simple Statement:** Energy cannot be created or destroyed, only converted from one form to another.\n*   **Explanation:** This is the thermodynamic version of the law of conservation of energy. It means that the total energy in a closed system is constant. If you add energy to a system (e.g., by heating it), that energy doesn't disappear. It either increases the system's internal energy (making it hotter) or is used by the system to do work on its surroundings (like a piston moving). You can't get free energy out of nothing.\n*   **Everyday Example:** When you eat food, the chemical energy stored in the food is converted by your body into thermal energy (to keep you warm) and kinetic energy (to move your muscles). The energy isn't created; it's just transformed.\n\n---\n\n### 2. The Second Law of Thermodynamics: The Increase of Entropy\n\n*   **Simple Statement:** The total entropy (disorder) of the universe always increases over time.\n*   **Explanation:** This is arguably the most profound of the laws. It states that natural processes tend to move towards a state of greater disorder or randomness (entropy). Heat will always spontaneously flow from a hotter object to a colder object, never the other way around. This flow increases the overall entropy because the energy becomes more spread out and less \"organized.\" Because of this law, no energy transfer is 100% efficient; some energy is always lost as waste heat, increasing the overall disorder of the universe.\n*   **Everyday Example:** A hot cup of coffee will always cool down to room temperature. The concentrated heat (an ordered state) will spread out into the cooler, larger room (a more disordered state). You will never see a room-temperature cup of coffee spontaneously become hot by drawing heat from the air. Similarly, an ice cube melts in a warm room, moving from an ordered crystal structure to a disordered liquid.\n\n---\n\n### 3. The Third Law of Thermodynamics: Absolute Zero is Unreachable\n\n*   **Simple Statement:** The entropy of a system approaches a minimum value as the temperature approaches absolute zero. It is impossible to reach absolute zero in a finite number of steps.\n*   **Explanation:** Absolute zero (0 Kelvin or -273.15°C / -459.67°F) is the theoretical temperature at which all particle motion would completely stop. The Third Law states that as you get colder and closer to this temperature, the entropy of a perfect crystal becomes zero. However, the law also implies that it's physically impossible to ever reach absolute zero. Each step you take to cool a system gets you closer, but the effort required to remove the next bit of heat increases exponentially. You can get incredibly close, but you can never take that final step to get there.\n*   **Everyday Example:** This law is less intuitive in daily life as it deals with extreme cold. But you can think of it like trying to create a perfect vacuum by pumping all the air out of a container. With each pump, you remove a fraction of the remaining air, so you get closer and closer to a perfect vacuum but never fully achieve it because there will always be *some* molecules left. Reaching absolute zero is a similar process of diminishing returns.\n\n| Law | Simple Statement | Key Concept |\n| :--- | :--- | :--- |\n| **Zeroth** | Defines temperature. | Thermal Equilibrium |\n| **First** | Energy is conserved. | Conservation of Energy |\n| **Second**| Disorder (entropy) increases. | Entropy & The Arrow of Time |\n| **Third** | Absolute zero is unreachable. | Absolute Zero & Minimum Entropy |"
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP"
    }
  ],
  "createTime": "2026-04-28T19:34:08.655096Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-pro",
  "responseId": "sAvxafj9J8aA9LsP4fWlkAs",
  "usageMetadata": {
    "candidatesTokenCount": 1127,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 1127
      }
    ],
    "promptTokenCount": 8,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 8
      }
    ],
    "thoughtsTokenCount": 1631,
    "totalTokenCount": 2766,
    "trafficType": "ON_DEMAND"
  }
}
```

## Examples

<details>

<summary>**With System Instruction** — Using a system instruction to set context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-2.5-pro',
  {
    contents: [{ parts: [{ text: 'How do I read a JSON file in Python?' }], role: 'user' }],
    generationConfig: { temperature: 0.3 },
    systemInstruction: {
      parts: [{ text: 'You are a helpful coding assistant specializing in Python.' }],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-pro",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "How do I read a JSON file in Python?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "temperature": 0.3
    },
    "systemInstruction": {
      "parts": [
        {
          "text": "You are a helpful coding assistant specializing in Python."
        }
      ]
    }
  }
}'
```

````
Of course! Reading a JSON file in Python is a common task, and the built-in `json` module makes it very straightforward.

Here is the most common and recommended way to do it.

### The Short & Sweet Answer

Use the `json.load()` function along with a `with open()` context manager.

```python
import json

# The name of your JSON file
filename = 'data.json'

# Use a 'with' statement for safe file handling
with open(filename, 'r') as file:
    # Load the JSON data from the file into a Python object
    data = json.load(file)

# Now 'data' is a Python dictionary (or list) that you can work with
print("Successfully loaded JSON data!")
print(data)

# Example of accessing data
print("\nAccessing specific data:")
print("Name:", data['name'])
print("First skill:", data['skills'][0])
```

---

### Step-by-Step Explanation

Let's break down the code above with a complete, runnable example.

#### 1. Create a Sample JSON File

First, let's create a JSON file to read. Save the following content in a file named `data.json` in the same directory as your Python script.

**`data.json`**
```json
{
  "name": "Alex",
  "id": 12345,
  "is_active": true,
  "email": null,
  "skills": [
    "Python",
    "Data Analysis",
    "Machine Learning"
  ],
  "projects": {
    "project_a": "In Progress",
    "project_b": "Completed"
  }
}
```
> **Note:** JSON requires double quotes `"` for all keys and string values. Single quotes `'` will cause an error.

#### 2. Write the Python Script

Now, let's look at the Python code in detail.

**`read_file.py`**
```python
# Step 1: Import the json module
# This module is built into Python, so no installation is needed.
import json

# Step 2: Open the JSON file for reading
# The 'with' statement is highly recommended because it automatically
# handles closing the file, even if errors occur.
# 'r' stands for "read mode".
with open('data.json', 'r') as f:
    
    # Step 3: Load the data using json.load()
    # The json.load() function reads from a file-like object (f),
    # parses the JSON data, and converts it into a Python object.
    data = json.load(f)

# Step 4: Work with your new Python object
# The 'data' variable now holds the content of the JSON file.
# JSON objects are converted to Python dictionaries.
# JSON arrays are converted to Python lists.

print("The data type is:", type(data))
print("---")
print("Full data:", data)
print("---")

# You can now access the data just like any other Python dictionary
print("User's name:", data['name'])
print("User's skills:", data['skills'])

# Loop through the list of skills
print("\nSkills:")
for skill in data['skills']:
    print("-", skill)
```

#### How JSON Types Map to Python Types

When you use `json.load()`, the data is converted as follows:

| JSON | Python |
| :--- | :--- |
| object | `dict` |
| array | `list` |
| string | `str` |
| number (int) | `int` |
| number (real) | `float` |
| `true` | `True` |
| `false` | `False` |
| `null` | `None` |

---

### Common Issues and Solutions

1.  **`FileNotFoundError`**: This happens if Python can't find your file.
    *   **Solution**: Make sure the file name is spelled correctly and the file is in the same directory as your script. If it's in a different directory, provide the full or relative path (e.g., `'data/my_file.json'`).

2.  **`json.JSONDecodeError`**: This means your file is not valid JSON.
    *   **Solution**: Check your `.json` file for syntax errors. The most common mistakes are:
        *   Using single quotes (`'`) instead of double quotes (`"`).
        *   Having a trailing comma after the last item in an object or list.
        *   Missing commas between elements.

3.  **Character Encoding Issues**: If your file contains special characters (like `é` or `ü`), you might get a `UnicodeDecodeError`.
    *   **Solution**: Specify the encoding when opening the file. UTF-8 is the most common and is standard for JSON.
    ```python
    with open('data.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
    ```

### Reading a JSON String vs. a JSON File

It's important to know the difference between `json.load()` and `json.loads()`.

*   `json.load()`: Reads from a **file object**.
*   `json.loads()`: Reads from a **string**. (The 's' stands for "string").

**Example using `json.loads()`:**

```python
import json

json_string = """
{
  "name": "Brenda",
  "city": "New York"
}
"""

# Load data from the string
data = json.loads(json_string)

print(data['city'])  # Output: New York
```
````

```json
{
  "candidates": [
    {
      "avgLogprobs": -0.18925412299094185,
      "content": {
        "parts": [
          {
            "text": "Of course! Reading a JSON file in Python is a common task, and the built-in `json` module makes it very straightforward.\n\nHere is the most common and recommended way to do it.\n\n### The Short & Sweet Answer\n\nUse the `json.load()` function along with a `with open()` context manager.\n\n```python\nimport json\n\n# The name of your JSON file\nfilename = 'data.json'\n\n# Use a 'with' statement for safe file handling\nwith open(filename, 'r') as file:\n    # Load the JSON data from the file into a Python object\n    data = json.load(file)\n\n# Now 'data' is a Python dictionary (or list) that you can work with\nprint(\"Successfully loaded JSON data!\")\nprint(data)\n\n# Example of accessing data\nprint(\"\\nAccessing specific data:\")\nprint(\"Name:\", data['name'])\nprint(\"First skill:\", data['skills'][0])\n```\n\n---\n\n### Step-by-Step Explanation\n\nLet's break down the code above with a complete, runnable example.\n\n#### 1. Create a Sample JSON File\n\nFirst, let's create a JSON file to read. Save the following content in a file named `data.json` in the same directory as your Python script.\n\n**`data.json`**\n```json\n{\n  \"name\": \"Alex\",\n  \"id\": 12345,\n  \"is_active\": true,\n  \"email\": null,\n  \"skills\": [\n    \"Python\",\n    \"Data Analysis\",\n    \"Machine Learning\"\n  ],\n  \"projects\": {\n    \"project_a\": \"In Progress\",\n    \"project_b\": \"Completed\"\n  }\n}\n```\n> **Note:** JSON requires double quotes `\"` for all keys and string values. Single quotes `'` will cause an error.\n\n#### 2. Write the Python Script\n\nNow, let's look at the Python code in detail.\n\n**`read_file.py`**\n```python\n# Step 1: Import the json module\n# This module is built into Python, so no installation is needed.\nimport json\n\n# Step 2: Open the JSON file for reading\n# The 'with' statement is highly recommended because it automatically\n# handles closing the file, even if errors occur.\n# 'r' stands for \"read mode\".\nwith open('data.json', 'r') as f:\n    \n    # Step 3: Load the data using json.load()\n    # The json.load() function reads from a file-like object (f),\n    # parses the JSON data, and converts it into a Python object.\n    data = json.load(f)\n\n# Step 4: Work with your new Python object\n# The 'data' variable now holds the content of the JSON file.\n# JSON objects are converted to Python dictionaries.\n# JSON arrays are converted to Python lists.\n\nprint(\"The data type is:\", type(data))\nprint(\"---\")\nprint(\"Full data:\", data)\nprint(\"---\")\n\n# You can now access the data just like any other Python dictionary\nprint(\"User's name:\", data['name'])\nprint(\"User's skills:\", data['skills'])\n\n# Loop through the list of skills\nprint(\"\\nSkills:\")\nfor skill in data['skills']:\n    print(\"-\", skill)\n```\n\n#### How JSON Types Map to Python Types\n\nWhen you use `json.load()`, the data is converted as follows:\n\n| JSON | Python |\n| :--- | :--- |\n| object | `dict` |\n| array | `list` |\n| string | `str` |\n| number (int) | `int` |\n| number (real) | `float` |\n| `true` | `True` |\n| `false` | `False` |\n| `null` | `None` |\n\n---\n\n### Common Issues and Solutions\n\n1.  **`FileNotFoundError`**: This happens if Python can't find your file.\n    *   **Solution**: Make sure the file name is spelled correctly and the file is in the same directory as your script. If it's in a different directory, provide the full or relative path (e.g., `'data/my_file.json'`).\n\n2.  **`json.JSONDecodeError`**: This means your file is not valid JSON.\n    *   **Solution**: Check your `.json` file for syntax errors. The most common mistakes are:\n        *   Using single quotes (`'`) instead of double quotes (`\"`).\n        *   Having a trailing comma after the last item in an object or list.\n        *   Missing commas between elements.\n\n3.  **Character Encoding Issues**: If your file contains special characters (like `é` or `ü`), you might get a `UnicodeDecodeError`.\n    *   **Solution**: Specify the encoding when opening the file. UTF-8 is the most common and is standard for JSON.\n    ```python\n    with open('data.json', 'r', encoding='utf-8') as file:\n        data = json.load(file)\n    ```\n\n### Reading a JSON String vs. a JSON File\n\nIt's important to know the difference between `json.load()` and `json.loads()`.\n\n*   `json.load()`: Reads from a **file object**.\n*   `json.loads()`: Reads from a **string**. (The 's' stands for \"string\").\n\n**Example using `json.loads()`:**\n\n```python\nimport json\n\njson_string = \"\"\"\n{\n  \"name\": \"Brenda\",\n  \"city\": \"New York\"\n}\n\"\"\"\n\n# Load data from the string\ndata = json.loads(json_string)\n\nprint(data['city'])  # Output: New York\n```"
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP"
    }
  ],
  "createTime": "2026-04-28T19:34:08.614146Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-pro",
  "responseId": "sAvxaYK-JZmA6tkPxraQ6Qg",
  "usageMetadata": {
    "candidatesTokenCount": 1292,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 1292
      }
    ],
    "promptTokenCount": 20,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 20
      }
    ],
    "thoughtsTokenCount": 1582,
    "totalTokenCount": 2894,
    "trafficType": "ON_DEMAND"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-2.5-pro',
  {
    contents: [
      {
        parts: [{ text: 'I need help planning a road trip from San Francisco to Los Angeles.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "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: 'model',
      },
      { parts: [{ text: 'Yes, what are some good places to stop?' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 2048 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-pro",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I need help planning a road trip from San Francisco to Los Angeles."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "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": "model"
      },
      {
        "parts": [
          {
            "text": "Yes, what are some good places to stop?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 2048
    }
  }
}'
```

```
Of course! The drive from San Francisco to Los Angeles offers two very different experiences, depending on
```

```json
{
  "candidates": [
    {
      "avgLogprobs": -5.178282888312089,
      "content": {
        "parts": [
          {
            "text": "Of course! The drive from San Francisco to Los Angeles offers two very different experiences, depending on"
          }
        ],
        "role": "model"
      },
      "finishReason": "MAX_TOKENS"
    }
  ],
  "createTime": "2026-04-28T19:34:34.916567Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-pro",
  "responseId": "ygvxadf4N5TIodAPqsDhyQk",
  "usageMetadata": {
    "candidatesTokenCount": 19,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 19
      }
    ],
    "promptTokenCount": 64,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 64
      }
    ],
    "thoughtsTokenCount": 477,
    "totalTokenCount": 560,
    "trafficType": "ON_DEMAND"
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'google/gemini-2.5-pro',
  {
    contents: [
      {
        parts: [{ text: 'Write a short story opening about a detective finding an unusual clue.' }],
        role: 'user',
      },
    ],
    generationConfig: { maxOutputTokens: 1500, temperature: 0.8 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-pro",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a short story opening about a detective finding an unusual clue."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 1500,
      "temperature": 0.8
    }
  }
}'
```

```
The stale, metallic tang of blood was the first
```

```json
{
  "candidates": [
    {
      "avgLogprobs": -7.117010498046875,
      "content": {
        "parts": [
          {
            "text": "The stale, metallic tang of blood was the first"
          }
        ],
        "role": "model"
      },
      "finishReason": "MAX_TOKENS"
    }
  ],
  "createTime": "2026-04-28T19:34:36.902347Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-pro",
  "responseId": "zAvxacuJN-fHodAP8o2RyQ4",
  "usageMetadata": {
    "candidatesTokenCount": 10,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 10
      }
    ],
    "promptTokenCount": 13,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 13
      }
    ],
    "thoughtsTokenCount": 286,
    "totalTokenCount": 309,
    "trafficType": "ON_DEMAND"
  }
}
```

</details>

## Parameters

Schema variant

Generate ContentChat Completions

▶contents\[]

`array`required

▶systemInstruction{}

`object`

▶generationConfig{}

`object`

▶safetySettings\[]

`array`

▶tools\[]

`array`

toolConfig

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶candidates\[]

`array`

▶usageMetadata{}

`object`

modelVersion

`string`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-2.5-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-2.5-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-2.5-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-2.5-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-2.5-pro/#page","headline":"Gemini 2.5 Pro","description":"Google's most capable Gemini 2.5 model with strong reasoning, thinking support, and a 1M token context window.","url":"https://developers.cloudflare.com/ai/models/google/gemini-2.5-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Gemini 3 Flash is Google's fast multimodal model with frontier intelligence, superior search, and grounding capabilities.
title: Gemini 3 Flash
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 3 Flash

Text Generation • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-3-flash/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-3-flash`

- Third-party
- Zero data retention

Gemini 3 Flash is Google's fast multimodal model with frontier intelligence, superior search, and grounding capabilities.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/gemini/) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input <=200k (per 1M)$0.50</li><li>Cached input <=200k (per 1M)$0.05</li><li>Output <=200k (per 1M)$3.00</li><li>Input >200k (per 1M)$0.50</li><li>Cached input >200k (per 1M)$0.05</li><li>Output >200k (per 1M)$3.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-3-flash',
  { contents: [{ parts: [{ text: 'What are the three laws of thermodynamics?' }], role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the three laws of thermodynamics?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
While there are technically four laws (starting with the "Zeroth Law"), the **Three Laws of Thermodynamics** are the fundamental principles that describe how energy, heat, and matter behave.

Here is a breakdown of the three laws:

---

### 1. The First Law: Conservation of Energy
**Definition:** Energy cannot be created or destroyed, only transformed from one form to another. The total energy of an isolated system remains constant.

*   **In simple terms:** You can't get something for nothing.
*   **The Equation:** $\Delta U = Q - W$
    *   ($\Delta U$ is the change in internal energy, $Q$ is heat added, and $W$ is work done by the system).
*   **Example:** In a car engine, the chemical energy of the gasoline is converted into heat and then into mechanical work to move the car.

### 2. The Second Law: Entropy
**Definition:** The total entropy (disorder) of an isolated system can never decrease over time; it can only remain constant or increase. This law dictates the "arrow of time."

*   **In simple terms:** Things tend to get messy and disorganized over time. Heat always flows spontaneously from a hotter object to a colder object, never the other way around without adding work.
*   **Key Concept:** This law explains why 100% efficiency is impossible—some energy is always "lost" as waste heat.
*   **Example:** If you place a hot cup of coffee in a cold room, the coffee cools down as heat spreads into the room. The heat will never spontaneously jump back from the room into the coffee to make it boil again.

### 3. The Third Law: Absolute Zero
**Definition:** As the temperature of a system approaches absolute zero ($0$ Kelvin or $-273.15^\circ$ Celsius), the entropy of a perfect crystal approaches a constant minimum (usually zero).

*   **In simple terms:** You can’t reach absolute zero.
*   **Key Concept:** As atoms get colder, they slow down. At absolute zero, all molecular motion would essentially stop. However, because moving heat requires a temperature difference, it is physically impossible to reach a temperature of exactly zero Kelvin in a finite number of steps.
*   **Example:** Scientists use advanced lasers and magnets to get atoms within billionths of a degree of absolute zero, but they can never quite hit the "stop" button entirely.

---

### Summary Mnemonic
There is a famous (and slightly cynical) way to remember these laws, often called **"Ginsberg’s Theorem"**:

1.  **First Law:** You can't win. (You can't get more energy out than you put in).
2.  **Second Law:** You can't break even. (You always lose some energy to entropy).
3.  **Third Law:** You can't get out of the game. (You can't reach absolute zero to stop the process).

***

**Note on the Zeroth Law:** If you ever hear about a "Zeroth Law," it simply states that if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This is the law that allows us to use thermometers.
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "While there are technically four laws (starting with the \"Zeroth Law\"), the **Three Laws of Thermodynamics** are the fundamental principles that describe how energy, heat, and matter behave.\n\nHere is a breakdown of the three laws:\n\n---\n\n### 1. The First Law: Conservation of Energy\n**Definition:** Energy cannot be created or destroyed, only transformed from one form to another. The total energy of an isolated system remains constant.\n\n*   **In simple terms:** You can't get something for nothing.\n*   **The Equation:** $\\Delta U = Q - W$\n    *   ($\\Delta U$ is the change in internal energy, $Q$ is heat added, and $W$ is work done by the system).\n*   **Example:** In a car engine, the chemical energy of the gasoline is converted into heat and then into mechanical work to move the car.\n\n### 2. The Second Law: Entropy\n**Definition:** The total entropy (disorder) of an isolated system can never decrease over time; it can only remain constant or increase. This law dictates the \"arrow of time.\"\n\n*   **In simple terms:** Things tend to get messy and disorganized over time. Heat always flows spontaneously from a hotter object to a colder object, never the other way around without adding work.\n*   **Key Concept:** This law explains why 100% efficiency is impossible—some energy is always \"lost\" as waste heat.\n*   **Example:** If you place a hot cup of coffee in a cold room, the coffee cools down as heat spreads into the room. The heat will never spontaneously jump back from the room into the coffee to make it boil again.\n\n### 3. The Third Law: Absolute Zero\n**Definition:** As the temperature of a system approaches absolute zero ($0$ Kelvin or $-273.15^\\circ$ Celsius), the entropy of a perfect crystal approaches a constant minimum (usually zero).\n\n*   **In simple terms:** You can’t reach absolute zero.\n*   **Key Concept:** As atoms get colder, they slow down. At absolute zero, all molecular motion would essentially stop. However, because moving heat requires a temperature difference, it is physically impossible to reach a temperature of exactly zero Kelvin in a finite number of steps.\n*   **Example:** Scientists use advanced lasers and magnets to get atoms within billionths of a degree of absolute zero, but they can never quite hit the \"stop\" button entirely.\n\n---\n\n### Summary Mnemonic\nThere is a famous (and slightly cynical) way to remember these laws, often called **\"Ginsberg’s Theorem\"**:\n\n1.  **First Law:** You can't win. (You can't get more energy out than you put in).\n2.  **Second Law:** You can't break even. (You always lose some energy to entropy).\n3.  **Third Law:** You can't get out of the game. (You can't reach absolute zero to stop the process).\n\n***\n\n**Note on the Zeroth Law:** If you ever hear about a \"Zeroth Law,\" it simply states that if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This is the law that allows us to use thermometers.",
            "thoughtSignature": "AY89a1+RdEkQqSCfe6KTvKWMknfIBywa5lOKfzJSDw4DHkMrF7/+jEpXKC9RABDVwVPQKy7Q9lCrPUvMBcuV858jRzDwHe88wDTSzoCgfjF7ztathjHzYzjkUyPg61Eg46vOVPb2f5Ca/bCUkdl4tvbk04gv/GueV57KO0wJbnF2oBjX/estVrz2k9mQCX/oSEEQDUIYg4BwjzqAlK7vQaIePTbsapXiEBugPRd2/rfscLbiEnwvx66ZmpCsxRpnzWIuw8biuQBTmqU5tzA8eJ7wez0w1O6KX+kcrnA9wEAqT0MF+S2qhF3Sc28320v9a6JoFbSdzUL7MccJ75M1ruo25NgnBFzckrPCBtjFGJXKssdBtmCKCfZrKFa7s8y72DjpJyUqcg4rilk+WiBMFmUulrUpFXu+F2VedL0tSvAOx7ih0y5DWoNmzClQBuF/aoUROy1ey7Kq0HD0eySV2yK0dy2TN28XITvGhhq7I6w+TUMNiOjprZN5mGx97l/WpZ0KI+lDjqabo7QAJY7a/Oe2hi6Fycfq/vNj5ntB2geJZqqtrI2MZF3g6mJg4D4pf1nfUMPJvESuubqHTbHEeIgXqIpE/k/z6R6ffQNg/8ACLBQHP+dGcC8gIx3rMOt6e02RvzlJAOh0rFTKiAckjCZ3SOF/8QLXdaEQ2kmaXw6j+uMp5WWJpDFu7ReWlhtwQbCFIcgrkwSfXPjwl50tUAYJQ6UnVIPItrd6bNd260QRUJTqJjFV7aISbqRWbZL1qXGGGKSuSkRv5C2srVxY7emv03AbH+NFYCenLsPgLkf2zFOT3+H9rl+MAO/gtnAc8IELv+cH89fIDjhBOWNIPItNCVlnIAmMufQY5NmdzqhWrt6h2ZsOOIEwjTci4m3K/bBuuHrLp9fybz4ubaiWBJCsFIBrVzt5j6GJoduMHJ+98uJ0woNl0EkcmClV7mKa4KR7WrN0lU6EB/lCkleHMRn0zWvXIqNetPqYijeYB8rsCyRi/ujqFZAWmveLRx2UBbgvtcNRruxGY+mg7aGXGsGbPdQLOGMPbjhpH0YXTeS6rMPglF4zOq2nvkISug5NxUIOK6OiupZYar/6aDrXODsPBr45HhrYz4JMJA+9JzzYHgueMMu5Iw+KL+bPGgXXoBvO/XrNMnO9rTevi6eVHD/0jrJHCu6fG87lTCBDYjF0JQYekrqkTf4WbBfEpyVPKm2SP4lgLdyLN/E2rieXDi3srBr6NP1C6JDyQlDXuWPVd27npP1Zbtfm2nUnq73OmMJKIzQEmRSSok0SFg2YvOw1gAe4D/smJTjU+1pwQXQlqQxwkjJ1DuC2IYwPR9hIfxex0aZqY0gXmhDotHIClRD8uPCpW82kLcy69evbvjRdMy6bDG3ytIhOiQNeBy5VMJ1tkPtGXcAgZPcGnV56+tTwbuChI75Vonk8kGZRK7c79+CbP3Hm+FYe2R53k+uPGOJgRiCYNjRzuS66R7u3NvzNnz/F1FKPTW/cosrusLx3ghPcfvhawu7O9xUDhP6uyUgN3n62gluc7TXHbRRiUQFF33A7noDGZC8X1M2BpvYivm/IMeFlBDsJDiGQgVNK5fYCWz+rjfxC7Q6eFFcrs9TEwvKnsrTtxjuAIVC5eng6sH/bjYpexZ0egORleQOQ+MpGqVx7lhK9ILLtXNkbhIpyvc7RgDyckCt8ei9HvG5kp1HZ6GNn3AE+MoCpVO+0HTNCV8f3SKuXI+SEHR1/2DyXq1h8MDCYLrrEDiyhylPsZ5wOQqrNRtxQQ8hBTG8TB8/dK9WbPn9d9uzEMxJ0FuCVW+phxy30wfrfPgK1VF+h44LG4ouCDXXn3ulIBpdVPGo2oZJFOuLtcJSreXyHklkQX9nVT6HmUtRafT82+78DWAm5chkZ933SJsSabovTAj2uVuMXgDD30Gpk7oJ6wuSKw8vjbPk/0i6Ep8L21Mv++Kuj3WskXQlEtXgujOiQx/CdpTmlTbjeQ6hv0/bagQVuEN1RtNRAS6lmyCqcuo2VuaUqwDvGjRT6+/OM/7memyezkWmJAufx7vgvV+BmlIMUCcNQKRFT"
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 8,
    "candidatesTokenCount": 697,
    "totalTokenCount": 1107,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 8
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 697
      }
    ],
    "thoughtsTokenCount": 402
  },
  "modelVersion": "gemini-3-flash-preview",
  "createTime": "2026-07-24T21:49:35.132185Z",
  "responseId": "791jatmICOSg3dAPo6eioAg",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Instruction** — Using a system instruction to set context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3-flash',
  {
    contents: [{ parts: [{ text: 'How do I read a JSON file in Python?' }], role: 'user' }],
    generationConfig: { temperature: 0.3 },
    systemInstruction: {
      parts: [{ text: 'You are a helpful coding assistant specializing in Python.' }],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "How do I read a JSON file in Python?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "temperature": 0.3
    },
    "systemInstruction": {
      "parts": [
        {
          "text": "You are a helpful coding assistant specializing in Python."
        }
      ]
    }
  }
}'
```

````
To read a JSON file in Python, you use the built-in `json` module.

Here is the most common and recommended way to do it:

### The Standard Method
```python
import json

# Open the file and load the data
with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)

# Now 'data' is a Python dictionary or list
print(data)
```

### Breakdown of the code:
1.  **`import json`**: Imports Python’s built-in JSON library.
2.  **`with open(...)`**: This is a "context manager." It ensures the file is properly closed after you are done reading it, even if an error occurs.
3.  **`'r'`**: Opens the file in **read** mode.
4.  **`encoding='utf-8'`**: This is optional but highly recommended to ensure special characters (like emojis or non-English letters) are handled correctly.
5.  **`json.load(file)`**: This function takes the file object and converts the JSON data into a Python object (usually a `dict` or a `list`).

---

### `json.load()` vs `json.loads()`
It is easy to confuse these two functions:
*   **`json.load()`** (no 's'): Used to read from a **file object**.
*   **`json.loads()`** (stands for "load string"): Used to parse a **string** containing JSON data.

**Example of `json.loads()`:**
```python
import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)

print(data["name"]) # Output: Alice
```

---

### Handling Errors
If the file doesn't exist or the JSON is formatted incorrectly, your program will crash. You can wrap the code in a `try-except` block to handle this gracefully:

```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
except FileNotFoundError:
    print("The file was not found.")
except json.JSONDecodeError:
    print("The file is not a valid JSON format.")
```

### Pro Tip: Using Pandas (for Data Science)
If your JSON file contains a list of records (like a table), the **Pandas** library is often much faster and easier:

```python
import pandas as pd

df = pd.read_json('data.json')
print(df.head())
```
````

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "To read a JSON file in Python, you use the built-in `json` module.\n\nHere is the most common and recommended way to do it:\n\n### The Standard Method\n```python\nimport json\n\n# Open the file and load the data\nwith open('data.json', 'r', encoding='utf-8') as file:\n    data = json.load(file)\n\n# Now 'data' is a Python dictionary or list\nprint(data)\n```\n\n### Breakdown of the code:\n1.  **`import json`**: Imports Python’s built-in JSON library.\n2.  **`with open(...)`**: This is a \"context manager.\" It ensures the file is properly closed after you are done reading it, even if an error occurs.\n3.  **`'r'`**: Opens the file in **read** mode.\n4.  **`encoding='utf-8'`**: This is optional but highly recommended to ensure special characters (like emojis or non-English letters) are handled correctly.\n5.  **`json.load(file)`**: This function takes the file object and converts the JSON data into a Python object (usually a `dict` or a `list`).\n\n---\n\n### `json.load()` vs `json.loads()`\nIt is easy to confuse these two functions:\n*   **`json.load()`** (no 's'): Used to read from a **file object**.\n*   **`json.loads()`** (stands for \"load string\"): Used to parse a **string** containing JSON data.\n\n**Example of `json.loads()`:**\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)\n\nprint(data[\"name\"]) # Output: Alice\n```\n\n---\n\n### Handling Errors\nIf the file doesn't exist or the JSON is formatted incorrectly, your program will crash. You can wrap the code in a `try-except` block to handle this gracefully:\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r') as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"The file was not found.\")\nexcept json.JSONDecodeError:\n    print(\"The file is not a valid JSON format.\")\n```\n\n### Pro Tip: Using Pandas (for Data Science)\nIf your JSON file contains a list of records (like a table), the **Pandas** library is often much faster and easier:\n\n```python\nimport pandas as pd\n\ndf = pd.read_json('data.json')\nprint(df.head())\n```",
            "thoughtSignature": "AY89a19gXBYi6TaPLwfAGabkFykrt/VT0/7TNJg4gxnDwsvi+dRCrWduSfukGMbFawR9yTOOOX0pGghcixRX1DIU/Itu9t80Igw3jfw9rKDQS7mB9K+wmeEyqLlL7J5x2mIuhvvjkgFwXGWGlkTWXe4DX+701K79JeiDVgvOVoa0E0aWUXz/4FInnHCc3FhgEpjXnHSsvXS1jVfOgYrfxnJb5FaQ4C4rWI7Y7q+xdH8kD37tiPBc4hLo/4OOR92ufuOY/hPkQfdyGXm9FOg6jSFD5NOnIC/S+6yaDwrj9Ruvgig9Y7wxikcXLfT68sR3x3ekEO+awkk69xbo42AJ7g9WxOKImcUQVZv7mpPLrKRwH5NZnmZTSowsbZ7rnMtbhiiTqbULB2irj9orfaCUpNISpU7eXn37LD5E5mWcI2zkhfLgUAj2H487UTnCUOX7GassWppELpwE5UrRf4SraDKsYyL28tqYThLtX2TB+G5Qku8zPqApKoERXYW376q8tRws/SA3uBLNovZtc3ihERcb5CfptNebVFTZjG3vfPuErVOLk4wpQKyVMcrR7TWH/COhP/Y6oDRl5etAsHHhVZV3M46J71eGFrni61zqlm/6dOl/BMreovZ2lvQVy6Zf8SXMZwXxvOyoUBxltPrFzSpRq+ju6sRHO3JKsE6wFXjWfzjHy/5fISMrLgr7pTUsDG8Y4GlUXiY/WMFw2gldNnMWSjAxKJNl9mJQuKmIQpfYgbfUeKa8eHnXVohl4u0oD9RcRx/1UTpvt57nKL8KfOhTWUyn32gw6Y0jvil+jZfiV6vvI9kSFIfWqXqyuld/3xou8+4Pdg9oxc/enc4EEtOor+0vl0d05+DhnDUPe4o2gt6N8/xpRGdMUYtx2twut6NHPVrZzt6lhqw0Rh/1+LMPgwgkQOaAg86MDcAQOE63DxPaubbWVIvswQX/cCQ1TQT1SVnas1KG3HNQhYZfSrrgXeDp7OYntzKAoaNd1wtry6ZB88NYC9R48AI05bWaduwnTWHJv/n2q64p5KYlOMrnRPsmvNvDhHQfIeGL8k4IVc2v6XqL5mkTwBRxla1d3U/rZGiGF3Pt9SXpZtZKw2WfPxn4T938FrblqrDMy0tNF0Wesao0b0IGyiS75J5RFWtZFXNKZrEyd1/mUkQOhgIQqSuRU9lrMLJEgyKRgjv9nQy/bcpuP1fZhLQBo/BE/e2yuBy7k7MyKZLQTuntqQNrastY6/z9UV/Gv7KIe8L7KNaN1ljVHWHDnBgrlq3xL6VY4Mtgb8zCi372eKRQl/E2EPW/aRngzYj1q0k+G+O58wSebWusR52vpMpdQ7VHSudS14Dvqxap3Fz69CL7UOqEJ4A="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 20,
    "candidatesTokenCount": 582,
    "totalTokenCount": 875,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 20
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 582
      }
    ],
    "thoughtsTokenCount": 273
  },
  "modelVersion": "gemini-3-flash-preview",
  "createTime": "2026-07-24T21:49:42.962953Z",
  "responseId": "9t1jaonjOoGL3dAPnayyuA0",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3-flash',
  {
    contents: [
      {
        parts: [{ text: 'I need help planning a road trip from San Francisco to Los Angeles.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "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: 'model',
      },
      { parts: [{ text: 'Yes, what are some good places to stop?' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 2048 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I need help planning a road trip from San Francisco to Los Angeles."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "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": "model"
      },
      {
        "parts": [
          {
            "text": "Yes, what are some good places to stop?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 2048
    }
  }
}'
```

```
The stops you choose will depend entirely on which route you take. Since I mentioned the 5-6 hour timeframe earlier, that usually refers to the **I-5 (Inland)** route, but most people prefer the **Highway 1 (Coastal)** route for a "road trip" experience.

Here are the best stops for the three most common routes:

### 1. The Scenic Route: Highway 1 (Pacific Coast Highway)
*Best for: Incredible views, photo ops, and a multi-day trip.*
* **Santa Cruz:** Walk the historic Beach Boardwalk or see the Redwood trees at Roaring Camp.
* **Monterey & Carmel-by-the-Sea:** Visit the world-famous Monterey Bay Aquarium and drive the "17-Mile Drive" for views of Pebble Beach.
* **Big Sur:** Cross the iconic **Bixby Creek Bridge** and stop at **McWay Falls** (a waterfall that drops right onto the beach).
* **San Simeon:** Tour **Hearst Castle**, the massive estate of William Randolph Hearst, or see the Elephant Seal Rookery at Piedras Blancas.
* **Solvang:** A charming, "Little Denmark" village known for Dutch architecture and bakeries.
* **Santa Barbara:** Known as the "American Riviera," it has beautiful Spanish architecture and great shopping on State Street.

### 2. The Middle Ground: US-101
*Best for: A balance of speed and scenery (approx. 6–7 hours).*
* **Paso Robles:** If you like wine, this is one of California’s premier wine regions with beautiful rolling hills.
* **San Luis Obispo (SLO):** Visit the historic mission, walk through the "Bubblegum Alley," or hike Bishop Peak.
* **Pismo Beach:** Famous for its wide sandy beaches and "Clam Chowder" at Splash Café.
* **Ventura:** A great spot to see the pier and grab fresh seafood before hitting the LA traffic.

### 3. The Quickest Route: I-5 (The Grapevine)
*Best for: Getting there as fast as possible (approx. 5–6 hours).*
* **Harris Ranch (Coalinga):** A famous landmark and massive ranch. It's the best place for a high-quality steak dinner or a deli sandwich in the middle of the valley.
* **Bravo Farms (Kettleman City):** A fun, kitschy stop with a petting zoo, ice cream, nuts, and a "seven-story" treehouse for kids to climb.
* **Tejon Ranch Outlets:** Located at the base of "The Grapevine," it’s great for discount designer shopping before the final stretch into LA.

---

### A few "Pro Tips" for your drive:
1.  **Check for Closures:** If you take **Highway 1 (Big Sur)**, check Caltrans before you go. That road is prone to landslides and parts are occasionally closed for repairs.
2.  **The "Grapevine":** If taking the I-5, you will pass over a high mountain ridge called the Grapevine. In winter, it can occasionally close due to snow; in summer, keep an eye on your engine temperature as it's a long, steep climb.
3.  **LA Traffic:** Try to time your arrival in Los Angeles either before 2:00 PM or after 8:00 PM to avoid the worst of the gridlock.

**Which route sounds more like your style?** I can give you more specific recommendations for food or hotels once you choose!
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "The stops you choose will depend entirely on which route you take. Since I mentioned the 5-6 hour timeframe earlier, that usually refers to the **I-5 (Inland)** route, but most people prefer the **Highway 1 (Coastal)** route for a \"road trip\" experience.\n\nHere are the best stops for the three most common routes:\n\n### 1. The Scenic Route: Highway 1 (Pacific Coast Highway)\n*Best for: Incredible views, photo ops, and a multi-day trip.*\n* **Santa Cruz:** Walk the historic Beach Boardwalk or see the Redwood trees at Roaring Camp.\n* **Monterey & Carmel-by-the-Sea:** Visit the world-famous Monterey Bay Aquarium and drive the \"17-Mile Drive\" for views of Pebble Beach.\n* **Big Sur:** Cross the iconic **Bixby Creek Bridge** and stop at **McWay Falls** (a waterfall that drops right onto the beach).\n* **San Simeon:** Tour **Hearst Castle**, the massive estate of William Randolph Hearst, or see the Elephant Seal Rookery at Piedras Blancas.\n* **Solvang:** A charming, \"Little Denmark\" village known for Dutch architecture and bakeries.\n* **Santa Barbara:** Known as the \"American Riviera,\" it has beautiful Spanish architecture and great shopping on State Street.\n\n### 2. The Middle Ground: US-101\n*Best for: A balance of speed and scenery (approx. 6–7 hours).*\n* **Paso Robles:** If you like wine, this is one of California’s premier wine regions with beautiful rolling hills.\n* **San Luis Obispo (SLO):** Visit the historic mission, walk through the \"Bubblegum Alley,\" or hike Bishop Peak.\n* **Pismo Beach:** Famous for its wide sandy beaches and \"Clam Chowder\" at Splash Café.\n* **Ventura:** A great spot to see the pier and grab fresh seafood before hitting the LA traffic.\n\n### 3. The Quickest Route: I-5 (The Grapevine)\n*Best for: Getting there as fast as possible (approx. 5–6 hours).*\n* **Harris Ranch (Coalinga):** A famous landmark and massive ranch. It's the best place for a high-quality steak dinner or a deli sandwich in the middle of the valley.\n* **Bravo Farms (Kettleman City):** A fun, kitschy stop with a petting zoo, ice cream, nuts, and a \"seven-story\" treehouse for kids to climb.\n* **Tejon Ranch Outlets:** Located at the base of \"The Grapevine,\" it’s great for discount designer shopping before the final stretch into LA.\n\n---\n\n### A few \"Pro Tips\" for your drive:\n1.  **Check for Closures:** If you take **Highway 1 (Big Sur)**, check Caltrans before you go. That road is prone to landslides and parts are occasionally closed for repairs.\n2.  **The \"Grapevine\":** If taking the I-5, you will pass over a high mountain ridge called the Grapevine. In winter, it can occasionally close due to snow; in summer, keep an eye on your engine temperature as it's a long, steep climb.\n3.  **LA Traffic:** Try to time your arrival in Los Angeles either before 2:00 PM or after 8:00 PM to avoid the worst of the gridlock.\n\n**Which route sounds more like your style?** I can give you more specific recommendations for food or hotels once you choose!",
            "thoughtSignature": "AY89a18g36sZRh+Pkcx44HM9xe+oWxW+72aPQAgy/pq2tFRR5EibMnmQ139NS4U7oPxzJkFUwjJdbm38RO3dXjkgYa4M/uozNMf7qBetFFh4UsifSuFminxMUvwAiwSPXBJpzOeBMaPcwVz0RolsIxcW2OBmnfBdFmPnyqTt51CE6ARYWB1r4rB6N87WSxlj7pcuGqXk7TpnFgAtAoFUjInjo1+1T3HFZhI7d2d9Un2vS+3Vte4a060IW1g2GWAe26pK1s26Th6e7S/W25YdfrUfLZtaHybnQZSptiFG9yjFFzw9vgJ3rqnAGfRRlDz1SDeCEiN1yp0I3FQO/5/HmztZGmSQsWwrGZ6dB2wXXqWwvC9yUyGHOb4yX4QKNKjioCus1ANFuEOj6Njc3qydKSZU/apCbEER+ZsB7ZYTbKM23YLUaXKLC8FScLSEjEzDKSMz1n6xeBWuH9I4am/y5fXkcE0yTLdWjhQwRRd1oY6E8Nf5hj2BXGZQmO/frGcTphWZx/oodWl2tG5hwkAens/KUtN1afuJ+MAXYlzgZRF7Jd4AfyF0E+u00ZS590R9ihGGftu+MBkLacCJl+GlvjKl2Es3M3ocXiVYzQVs0K2jSfZnkVIXcwrAfAG+HrWyaQ23TloRy9OzMY855JU3/iOo8XPzp1810vynU+wtdunnRWDUJUppek7ubNj6xXKMg9nvC5qQObbIWwnliu79ZgA+97LKrW27LYX/BHoe120j/INocH3N4B306qXIuIfnFzktueyrIOtgcUv53g9PWUZiZ0rJa5aVlGXGIf/odEuhEJaUxsbrdDlQ2Db3ujavHFlq7phU95D7ITkYpVN4513CrOPTpFHYIxDmMTvJDGqmZWE/JMXd7SuJaA+3klHs/WXMntCalde0guhGqbz52Ibpq9WgixQXhs8isDmxfi2AP63armMiJoAu0BEn8G367x+0n14xD0DzWiQgHXeDlagpV04OGmnNUfLtqhr7q+c3tNMn0rDUc37IRm1JZv+DaItndKMWgRSW8MsvHCObjGnjXgbeVEfGTUyMRLy6EKmO7tcOkkVK+eKJw4xxXQ/YApKTNhwmOHKiySvZJrCtn+I/ts/brXueZyZOQ2DhUsi1i9tKuQdeInh1UTjtCu0g5WSlTFq/jNRQxI3oVpiZJBiFyYbD4zHh4e6rHGbrjwKnYqi92uAsMvun3wN0TehOIu+wxjfvqOAbkXArzg1vhfUGFdeQB1o20sICiOa7V6b+Fg2XuTAn8iVliIPicOLKq5OlaDVPC27ZOkRptkwND2JSzZY0L+XDKkfACJBNuv6jAMiMq678vfa8mH50y6q9B48pDRnffmXLRwg6ZF0zOsbdZy3A/l3834l3IXBqZe2VXfhjXJ2KT6YWofmlfIWCwYuD4D5wtT3CAvT9MXiYlDtIkuDTecI5fI4XWQr3+dJmuM9KukreJjFv9628dPZWMkDIt4rD/LrbluGyJELXEKOgb8ODnuc/JGyXC1aVH7g2a6aEvkh1TdxINFvt2KG2L1tjR1mcnzKDHUt/6ZgzYrNUT6iUmu+bwBupBKclZuimHPeQAuxTA03CEThsaLE21bkQzZ0oROl2VQgZtHHF6KvQPZ6Xp+CiAbXo/6wYfZF6CV+k7xpMG2ffwCzplrhtXfWoEXm62F79cj3lmHTGUcL//TGACs8FK560ilI+n1c3jVcMgFxfuuljzo6S9beFPfKNFcBdeB2QGoQV6JBL3XaLX+rE4h8uNsJmc64oLEdxRcrqAOsAXdwXksNCZ9xzZFSLhy9dErvQj2BPbzchvS/JTuwZ2SKMxcKmJ40rms4STfP2YkF5CzTak5v7VsWEODE+G1M2uLvRxPd03FWIpP8eoY0BdDyWp9phQrHSoHiYc4GDzvYl7kodzsuONbWny8AtDlheRqzYJCbnkF5dl8A2J9UE+LWbwUtXICFtWWgDgHVGU+7Ni3GVwAN5oHtYtMDXgEv1/Lait5VpH0nvLhuD76na48QFFVXwDpwOdEiJFP/PNLcrs2lrdYiJR3Q9c3W1oH7keMdLzVfVwuAWZ/UW03eiDua73mLOU3uKKgjf1vzZeMmpLQf3uwOAK2mpz2dwWAkj+WmTclFzR2O50T33giUuVSDTgF3dugEqc+Onfz//gko3FPudS8maM8uwSwmeNk1O3eQm40EYMmfZO3YD9P3piAdNTc+x9pCxk1Fpu+dK824MTP+3jsZxaooSHqwa+VTZLq1h2+D0rbo+3+b+1M3ubaZjxYzA/ALb+5W4b2MQT3b/eWZFVc2Y29f+6cRiZPHyEF8Vi7l9OvsW4SzxMAwrXWmETB/f/TXfJpn6LXf2pd3uMIJFdUxoyo5/i4F8ttzS/4ClYWX0O2CT7DXVfSudd8b7L60gClaohG40dbsKIh3DVGsvuNokS00PBY8yGjAywoFjgprOdIZK20EsBjODlSgOaWxgPSZIzamg47X/npLvployPx51pTd1IMG0kKFTDXx0EmI7JFTN9IaeZJLp7wtYJPay0WAZGdVK7r2c"
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 64,
    "candidatesTokenCount": 762,
    "totalTokenCount": 1356,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 64
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 762
      }
    ],
    "thoughtsTokenCount": 530
  },
  "modelVersion": "gemini-3-flash-preview",
  "createTime": "2026-07-24T21:49:48.502515Z",
  "responseId": "_N1javPVHrSk3dAP45z02AQ",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3-flash',
  {
    contents: [
      {
        parts: [{ text: 'Write a short story opening about a detective finding an unusual clue.' }],
        role: 'user',
      },
    ],
    generationConfig: { maxOutputTokens: 4096, temperature: 0.8 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a short story opening about a detective finding an unusual clue."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 4096,
      "temperature": 0.8
    }
  }
}'
```

```
The humidity in the room was wrong. That was the first thing Detective Elias Thorne noticed. It wasn’t the metallic tang of blood or the heavy stillness of a man who had stopped breathing three hours ago. It was the smell of a thunderstorm in a room with no open windows.

Julian Vane, a man who had made millions selling security software, sat slumped in his designer leather chair. His throat had been opened with surgical precision, but Thorne’s eyes didn't linger on the gore. They were drawn to the mahogany desk, where a small, silver saucer sat perfectly centered.

In the middle of the saucer was a single, glowing sugar cube.

Thorne leaned in, his shadow stretching long across the Persian rug. He didn’t reach for his tweezers yet. The cube wasn't just white; it pulsed with a soft, rhythmic violet light, timed exactly to the pace of a resting human heartbeat. 

"Miller," Thorne called out without looking back at his partner. "Tell me the victim had a penchant for bioluminescent snacks."

"He was a hedge fund manager, Elias," Miller replied, snapping photos of the entryway. "The most exotic thing he consumed was unpasteurized goat cheese."

Thorne pulled a magnifying loupe from his coat pocket. As he peered through the glass, his breath hitched. Inside the crystalline structure of the sugar, frozen like a prehistoric insect in amber, was a microscopic set of brass gears. They were no larger than a grain of dust, and they were turning slowly in reverse.

It wasn't just a clue. It was a piece of machinery that shouldn't exist, ticking away inside a condiment. 

"Get the lead-lined evidence bag," Thorne whispered, the hair on his arms standing up as the violet pulse of the cube suddenly skipped a beat, matching his own racing heart. "I don't think we're looking for a murderer anymore. I think we're looking for a clockmaker."
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "The humidity in the room was wrong. That was the first thing Detective Elias Thorne noticed. It wasn’t the metallic tang of blood or the heavy stillness of a man who had stopped breathing three hours ago. It was the smell of a thunderstorm in a room with no open windows.\n\nJulian Vane, a man who had made millions selling security software, sat slumped in his designer leather chair. His throat had been opened with surgical precision, but Thorne’s eyes didn't linger on the gore. They were drawn to the mahogany desk, where a small, silver saucer sat perfectly centered.\n\nIn the middle of the saucer was a single, glowing sugar cube.\n\nThorne leaned in, his shadow stretching long across the Persian rug. He didn’t reach for his tweezers yet. The cube wasn't just white; it pulsed with a soft, rhythmic violet light, timed exactly to the pace of a resting human heartbeat. \n\n\"Miller,\" Thorne called out without looking back at his partner. \"Tell me the victim had a penchant for bioluminescent snacks.\"\n\n\"He was a hedge fund manager, Elias,\" Miller replied, snapping photos of the entryway. \"The most exotic thing he consumed was unpasteurized goat cheese.\"\n\nThorne pulled a magnifying loupe from his coat pocket. As he peered through the glass, his breath hitched. Inside the crystalline structure of the sugar, frozen like a prehistoric insect in amber, was a microscopic set of brass gears. They were no larger than a grain of dust, and they were turning slowly in reverse.\n\nIt wasn't just a clue. It was a piece of machinery that shouldn't exist, ticking away inside a condiment. \n\n\"Get the lead-lined evidence bag,\" Thorne whispered, the hair on his arms standing up as the violet pulse of the cube suddenly skipped a beat, matching his own racing heart. \"I don't think we're looking for a murderer anymore. I think we're looking for a clockmaker.\"",
            "thoughtSignature": "AY89a18uipJRkTss/UkZqyfwi6x82MixOXaO/uk3eCy64EV7aK4ttUgHP/GuCy87VIrRh2pBSFfaCIIgvg2Z0XXmG5k/oDbEIPlNbZjr7vrmMXRAeRatL+26MGjPoTkScvjCzzPACLHFVI4yuFtPLJgA6wKc+VnbldWtibzoIYW8pnja28iaIsV45zyQdP4OVlcG2zM79rLT5gdijGgyvXax6o4ddAYrkbmbguVQaigAYAoZscjdnDbsof72g7TspNIz2Cg84eCBk1OEJ9yJNsbzyMWDOlvXYFHnt+ZdQ2e+NMP+EvoxLfzyafvufBe8PoFy1nQezOtLUHjh8kzsvS3MbBfjylLF+REUMCKryJ9TbSmR2kvGvKZO+SAiImB9qfnFDw7IlqFBVRug8Xwa/FWZVZ5/Xj0ZPik+jpkA6ZP2jIcAp65natEzK3+EQDNeZVcVWomI5E2KCEgk5NeT6FqSsW326YpMnJQ+H6zCMzZgNZ/mVutbkiuXmdNVevVhT7I7UG0rbvARhvqsVZ5cRVktoY0vHAgjeqR1H46TiL3Km6QE2Dv21VA0udMMvLwZJVKLFppJc2leyUXi9NY34iKXWwWVllE4MrdULFUAnY/lrcpnCUGGWobryA8Tv7VvFPjGU/vqLdM88M2+9E91xyfR5Ud9tq47ZjDAqNFPhMIk6ZbzHbzXWgZWfF0qDRTBe711nl63mW6YaB2D7ORB9P5nb0YeIj1J9drnZeE/MqPuVLR5UZZ0nv76Nj36EIAsDjjYG2SWEjGpWD9rYhQP5OsyqwasD7Ug7/I7hFEWNs+qUMk82tOlH+nwGX+y/fNdkvUIY6cqn/tyVQXOpxJlSC77qPncwh/yMWZVNnWC0W6YxRwhM0XkcUsVNgAq5W1ogsLuo8q3R4DHp6sY+3D2DsUDzAw5OJKT0j7DjQ/ewJbhzN48boclWAWXGEGaiLukT+RkwEEL0lJLT1wyIbYfwHbjHgR2x6mh8n+zmzmXpnc030mLgj0WGn7ad2zrVBYH9s2evp0iFofgVHlIpvP1f3oLmn9WdC4gsJSFD38qqVHz7a/yfRl5enlJneD0gIGBgh7+KM7GL6zL317ouFxl09YZlApIK8r4s//Mz4MWIgDvM7jBAemSHoKpGwf9KdzWfXcoiWISUKOSWgUwybhIP1KHAwiBdr+1pbRKKzLa+VWa3z1EqtQ0Tf7a3LSAau2wy6g62M5hbtKEG10JEPqON13wihmzy4szC2pRTBIw67hhqT6pjYBDDGjDiGAZVucs+mo+gkC57ZSooNkXrIGMmoWfmYyD/efE4RbcPaO8Fb/TmkJex4rRd3+/6NmhhEuD1Q5U4nrTo9+pvkE5rC85ghMr+ZmT05xJsC1U2JZIHD4gPA6Lmx0QXg90emB7HwLoqadr99xtm8ZNaWjkzXKfZzJeCvtdwmX7kUTuzTRO/QNogqZbw0pJgAqGg0+raZumw9Cf3pXQARmoRW+UycAhO53d3jCjR3ofTdAsHmcuENGcP3Aa3m0rjvrSR4ZwvJ3DMc4F1wkdHnEfidYAYywq/L8CXJLPRW6mij21cbIpOICww4h0hWSeFSdqgUjKbDWMvF+eXj6XqW2OTeGxdgRaNneCrpCJzhCWZznL1GYQfTXGuWE/MuA6eTofdcBXbpPK9wtCDaEvglAMydRDtqXgloE+ETx3b2VbBwoFjn1tvx00DmuHlq+JwzMj0WtLk8JjNe87pOj9nRh1tp7SYWIrJCy5KjuygdK7bqZazwn7UeHlRcHPSzbfJvKALpNRFSXtq/+aDHTWlxFcLU/BLGVIWmQyVRfs4Xvmyjw8n0L0i6olwymAuSbvs0QkDpGH16kQ0eXnXm+jdtl/eQtVNagF2pc8DtS0AvvXKUHxFwGZvofxTeNIMR2SLxJPE53669keIKkA5aXSIk1XG/53mt13WhI1Z70Nq5EwrkQQwBXMc46/zB0HdfIG6hxcLiw++WSE7JvgucoEYt7rUYzKpoHyAXtME+bVTSVABXI9gxQcKB7fc3O0v76XOEr5UBVPJk6YTInmbD8AJrTmsoEI67yhIaPPKHMS7i2CJKjzQXPXuLUd2SURi/pAf95TIZiBB2jk3ziE3We1N7oIfeWKgaJk1aR76u3Jtm/qmtXK6ihoUdhhIoUlz+Fz0nm+P8guqsNtt1vqAS4dR1xJbrU5gPkXh4uMuC/O1hbed7cr48nts0WoxJz+dOQ0JUcic1g40zucicF8Wtrb9d1a3MCtLHgcAVwUY7HwsRY5YyddNeOalfTnAtvnaETfMKyX34CE6rwWLvMH4UhfuXELOK17R7eWC3zGZEblW5Tw2Ay4TOCKshPprc78Ss/+1bPC2S0sOyuEv70eoPcO11nJC6ThFzOf6SzrFZ8LbP0il6h7G1/+KseRqR+QjX+OONsxZhd/ZE0vQMl0mTMx2aWoBN/yqJmI6W2MIfMRVqmWR+xL+kibfu8j7zvWWN6hDkP+aYGEfmd18BBKnIfQLH/WM3L6zaCe/+En1aA57ssqupxk/Og1SMbWube/IKOJ3EFqAo25Uofw2sK3P2WRCUwFkXWoMSKzDvUHVW9dSH6hgOb4n/vwEewAOdtuxLcL8xO9uUsVee7VDaLE9lqw+rYOavCDTxICJPWKf9ndUW6YQBchhiQ0KAS+C10FyPVKiNsV9iFaGv1QYPGhKvuQxr2+vYisLNv1nctMkPpEzHC/7yDrxCGgHB3acAb+eS7QzKbh0U26ou46Bqbyoj38Ht6mTAlT6bb8JO1vP4+qfy+a+bvJ8kPMSNzjxobN7lNw+rzMK7xaLKW+hr4pZnPPAeuf9fRyOtvqn5sd4NUc/WilloSwFXkvylDz3eX/j1M8OZQkKEr6hPawHBhftonhWu/j0xoMZ/OcDf2Kut3+/l0rmk5gc2M8x1yrnCuOrJL9Z1fvFU0ftefJD7e3lPS95uTgBx0o2RpsOExCoVFABogSzTrMJ6uLnu98PT28XiipCaojsAk34idQWOiQTEfFUrSIkX0lH9EP1auHexa+EUMTLJfGj4B24OJZqzn6827TcfiGqDcQQrv6iElNOsbCac1FI7Wv6ChrlBYHXhBQqqruxH2KDfaDekHSbsJyXq1rEKSvqow363/hUznI03ftV3bXH73w2rRZoxl+3jSTRYm0bhMMVkkk/iH9Kz5RSdRJlLPMZFYHAibSlIJ2QxM8Z/vZwgUy7MqUQfa0mQjhGOXZJiPCOYwYsKPJYzBF8SFt/sybVIQEtHLGvFFokm6921EQuLTp+OpASHLQjZml2gY9ZNhK2HGICYykdRQOiLT3M79V4UaRFo1tjRQBCiAO/dJ24EP2Dmjw3rI66SLX6s+jHAs5rC3rzhDKQ3rreRvnglvG1R1BseenbfB9q8wq/ckLZ9laeEfBcWsLOfio/vr9wIFpDSlHWzGgE7z1hh6m2GhzqBJBTicgqWioAoNSTgTWGgI7SJ+ZVjW+lSRWszassATLb/LFljPc5OLl+hsMWNPTjk2YtbloJ4ueImJP8pmQE774NppcuDG8Uy8RzALjq8eOVsCREqaHQA8hQXgyCFqZ1hDdzfhcCfQv6u6z522CNTtuKVuv/qN3819C5QU9v4D1LBH/ZEcAC584eEWmLkfH9EMoL4Or6Q2ZY6cC692dMReaBFJz3bu1mzC/DImbgE8dzZqfyhTHsHBLVnk39b7mMZc0HkQh+J9Y+LxemXPcIjRXJcpXjgbpcD7TkJBgcwawE9rI57nrtufVWsjyyGxz5r4MBBy2NcvssAPsgUN1n2fGam+DhmDmdc6KLTaeE0K+1CEeDaXQN7pInGeurIY85WzB35oO94zAS6u10ZKluhedOAlDZCMTZ/CknJ5Mm4SNZJ6MoBrMy2DYymZjzUI3D3AeUbZjLUpEfaqplhMwP9gzoUpTuisQuRDkcLhm56q5tL9GyFROSUc9GV9bgXN66CbIr9vkz7fa+fu5YhCzyFsoFcboXgv2vKxTPRdVd4L+T4zzo7ujbbMV5hDprsZviND9ncmeiAWL8fh1PpRWy5g4Z229YopJdBjL0MaF+bMaEtnYvoN2BhXjVmZl7GfpTezZU2ACXZfToEZ/IAfnxzYX+h1+YbhXaQBINtcVRborON84vub45TH7A0l69ZA08gkayegb0L70oFXOH7izvVHS5utLrEE/clA/Bq0GI2QADAp6qEgnEP3XpFKxJjCpBfGtpX31Fx2ouZPQq/fp87ASCgvbuXFmtySuPr1ceC+mXy+TJJ58wk9bRkR7GXU6HwMUlOpKBgf0xiBw6fxu2uQGbIbEc0kuM+gIUdi6NvJpishm/as5buesjvq4u2r3Y1AtW5j+tgMuH8bk+i8CvmXqBR3adUJfNbQxpIp7liWMSBenPrH/7ETubYwmjFg9uw/lWfEkrFJuaRVD4H1WYG7Wwyki7Zt/nJTCZWC0LgOVJZ1vmpwqTnAml7VJBLlAP2xdBDWjSdFHxWCCNNCUpz8kjQpbGn06h/gfOYQYG9GnBS/MzQy7lzrXFTsEbf/fB6HsSU2g/t4ooreVF+sSPhfyOsLyfr61YG+DUYf5uIPtUBf5WSA8eUu0zJTPTRILNFaqMnhxOMA7limeCZPG+Yzwww=="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 13,
    "candidatesTokenCount": 409,
    "totalTokenCount": 1275,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 13
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 409
      }
    ],
    "thoughtsTokenCount": 853
  },
  "modelVersion": "gemini-3-flash-preview",
  "createTime": "2026-07-24T23:10:39.662413Z",
  "responseId": "7_Bjao23KPaH3dAP_vWlwAY",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

Generate ContentChat Completions

▶contents\[]

`array`required

▶systemInstruction{}

`object`

▶generationConfig{}

`object`

▶safetySettings\[]

`array`

▶tools\[]

`array`

toolConfig

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶candidates\[]

`array`

▶usageMetadata{}

`object`

modelVersion

`string`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-3-flash/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3-flash/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-3-flash/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3-flash/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3-flash/#page","headline":"Gemini 3 Flash","description":"Gemini 3 Flash is Google's fast multimodal model with frontier intelligence, superior search, and grounding capabilities.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3-flash/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Google's lightest and most cost-efficient Gemini model for high-throughput tasks.
title: Gemini 3.1 Flash Lite
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 3.1 Flash Lite

Text Generation • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-lite/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-3.1-flash-lite`

- Third-party
- Zero data retention

Google's lightest and most cost-efficient Gemini model for high-throughput tasks.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/gemini/) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input <=200k (per 1M)$0.25</li><li>Cached input <=200k (per 1M)$0.03</li><li>Output <=200k (per 1M)$1.50</li><li>Input >200k (per 1M)$0.25</li><li>Cached input >200k (per 1M)$0.03</li><li>Output >200k (per 1M)$1.50</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-3.1-flash-lite',
  { contents: [{ parts: [{ text: 'What are the three laws of thermodynamics?' }], role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-flash-lite",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the three laws of thermodynamics?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
The three laws of thermodynamics (along with the "zeroth" law, which is foundational) describe how energy moves, transforms, and behaves in physical systems.

Here is a breakdown of the laws:

### 0. The Zeroth Law (The Law of Equilibrium)
Before the first three were established, scientists realized there needed to be a rule about temperature.
*   **The Law:** If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.
*   **What it means:** This is the scientific basis for the thermometer. It allows us to define "temperature" as a measurable property.

---

### 1. The First Law (The Law of Conservation of Energy)
*   **The Law:** Energy cannot be created or destroyed in an isolated system; it can only be transferred or converted from one form to another.
*   **What it means:** The total amount of energy in the universe is constant. If you put energy into a system (as heat or work), it must either increase the system's internal energy or be released as work. You cannot get more energy out of a system than you put into it (this rules out "perpetual motion machines of the first kind").

---

### 2. The Second Law (The Law of Entropy)
*   **The Law:** The total entropy (disorder) of an isolated system can never decrease over time; it can only remain constant or increase.
*   **What it means:** Heat always flows naturally from a hotter object to a colder object, never the other way around unless external work is performed. Because energy spreads out and becomes less "useful" (it degrades into heat), no process is 100% efficient. This law provides an "arrow of time," explaining why things break down rather than spontaneously putting themselves back together.

---

### 3. The Third Law (The Law of Absolute Zero)
*   **The Law:** As the temperature of a system approaches absolute zero (0 Kelvin), the entropy of a perfect crystal approaches zero.
*   **What it means:** It is impossible to reach absolute zero through any finite number of processes. At absolute zero, all atomic motion stops, and the system reaches its state of minimum possible energy and perfect order.

***

### Summary for easy memory:
*   **Zeroth Law:** You have to play by the rules (there is such a thing as temperature).
*   **First Law:** You can't win (you can't create energy).
*   **Second Law:** You can't break even (you always lose some energy to entropy).
*   **Third Law:** You can't get out of the game (you can't reach absolute zero).
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "The three laws of thermodynamics (along with the \"zeroth\" law, which is foundational) describe how energy moves, transforms, and behaves in physical systems.\n\nHere is a breakdown of the laws:\n\n### 0. The Zeroth Law (The Law of Equilibrium)\nBefore the first three were established, scientists realized there needed to be a rule about temperature.\n*   **The Law:** If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.\n*   **What it means:** This is the scientific basis for the thermometer. It allows us to define \"temperature\" as a measurable property.\n\n---\n\n### 1. The First Law (The Law of Conservation of Energy)\n*   **The Law:** Energy cannot be created or destroyed in an isolated system; it can only be transferred or converted from one form to another.\n*   **What it means:** The total amount of energy in the universe is constant. If you put energy into a system (as heat or work), it must either increase the system's internal energy or be released as work. You cannot get more energy out of a system than you put into it (this rules out \"perpetual motion machines of the first kind\").\n\n---\n\n### 2. The Second Law (The Law of Entropy)\n*   **The Law:** The total entropy (disorder) of an isolated system can never decrease over time; it can only remain constant or increase.\n*   **What it means:** Heat always flows naturally from a hotter object to a colder object, never the other way around unless external work is performed. Because energy spreads out and becomes less \"useful\" (it degrades into heat), no process is 100% efficient. This law provides an \"arrow of time,\" explaining why things break down rather than spontaneously putting themselves back together.\n\n---\n\n### 3. The Third Law (The Law of Absolute Zero)\n*   **The Law:** As the temperature of a system approaches absolute zero (0 Kelvin), the entropy of a perfect crystal approaches zero.\n*   **What it means:** It is impossible to reach absolute zero through any finite number of processes. At absolute zero, all atomic motion stops, and the system reaches its state of minimum possible energy and perfect order.\n\n***\n\n### Summary for easy memory:\n*   **Zeroth Law:** You have to play by the rules (there is such a thing as temperature).\n*   **First Law:** You can't win (you can't create energy).\n*   **Second Law:** You can't break even (you always lose some energy to entropy).\n*   **Third Law:** You can't get out of the game (you can't reach absolute zero).",
            "thoughtSignature": "AY89a19nds/5ZNrEilIoIIOsW4vmEKmo5R0rba/I6ZZTI9ml+6YrCI65LXveEZ/d/f0="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 8,
    "candidatesTokenCount": 579,
    "totalTokenCount": 587,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 8
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 579
      }
    ]
  },
  "modelVersion": "gemini-3.1-flash-lite",
  "createTime": "2026-07-21T16:29:03.710695Z",
  "responseId": "T55faqewK4Wq8sYPycj20Q0",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Instruction** — Using a system instruction to set context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.1-flash-lite',
  {
    contents: [{ parts: [{ text: 'How do I read a JSON file in Python?' }], role: 'user' }],
    generationConfig: { temperature: 0.3 },
    systemInstruction: {
      parts: [{ text: 'You are a helpful coding assistant specializing in Python.' }],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-flash-lite",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "How do I read a JSON file in Python?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "temperature": 0.3
    },
    "systemInstruction": {
      "parts": [
        {
          "text": "You are a helpful coding assistant specializing in Python."
        }
      ]
    }
  }
}'
```

````
To read a JSON file in Python, you use the built-in `json` module.

Here is the standard way to do it:

### The Basic Approach
```python
import json

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

# Now 'data' is a Python dictionary or list
print(data)
```

### Breakdown of the code:
1.  **`import json`**: Imports Python's built-in library for handling JSON.
2.  **`with open(...)`**: This is a "context manager." It is the best practice because it ensures the file is automatically closed after you are done reading it, even if an error occurs.
3.  **`json.load(file)`**: This function parses the file content and converts it into the corresponding Python object (e.g., a JSON object becomes a `dict`, and a JSON array becomes a `list`).

---

### Handling Common Scenarios

#### 1. What if the file is empty or malformed?
If the file is not valid JSON, `json.load()` will raise a `json.JSONDecodeError`. You can handle this with a `try-except` block:

```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
except json.JSONDecodeError:
    print("The file contains invalid JSON.")
except FileNotFoundError:
    print("The file was not found.")
```

#### 2. Reading a JSON string instead of a file
If you have the JSON data as a **string** (not a file), use `json.loads()` (the 's' stands for "string"):

```python
import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)

print(data["name"]) # Output: Alice
```

### Summary: Which one to use?
*   Use **`json.load(file_object)`** when reading from an actual **file** on your disk.
*   Use **`json.loads(string)`** when reading from a **string** variable.
````

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "To read a JSON file in Python, you use the built-in `json` module.\n\nHere is the standard way to do it:\n\n### The Basic Approach\n```python\nimport json\n\n# Open the file and load the data\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\n# Now 'data' is a Python dictionary or list\nprint(data)\n```\n\n### Breakdown of the code:\n1.  **`import json`**: Imports Python's built-in library for handling JSON.\n2.  **`with open(...)`**: This is a \"context manager.\" It is the best practice because it ensures the file is automatically closed after you are done reading it, even if an error occurs.\n3.  **`json.load(file)`**: This function parses the file content and converts it into the corresponding Python object (e.g., a JSON object becomes a `dict`, and a JSON array becomes a `list`).\n\n---\n\n### Handling Common Scenarios\n\n#### 1. What if the file is empty or malformed?\nIf the file is not valid JSON, `json.load()` will raise a `json.JSONDecodeError`. You can handle this with a `try-except` block:\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r') as file:\n        data = json.load(file)\nexcept json.JSONDecodeError:\n    print(\"The file contains invalid JSON.\")\nexcept FileNotFoundError:\n    print(\"The file was not found.\")\n```\n\n#### 2. Reading a JSON string instead of a file\nIf you have the JSON data as a **string** (not a file), use `json.loads()` (the 's' stands for \"string\"):\n\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)\n\nprint(data[\"name\"]) # Output: Alice\n```\n\n### Summary: Which one to use?\n*   Use **`json.load(file_object)`** when reading from an actual **file** on your disk.\n*   Use **`json.loads(string)`** when reading from a **string** variable.",
            "thoughtSignature": "AY89a1/+8Xbo6oiWplrPfjrfXblH509xYguBbs/SHNqslfm3tKk50KPOszVUx9++ro8="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 20,
    "candidatesTokenCount": 496,
    "totalTokenCount": 516,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 20
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 496
      }
    ]
  },
  "modelVersion": "gemini-3.1-flash-lite",
  "createTime": "2026-07-21T16:29:06.645326Z",
  "responseId": "Up5fas6xJ9jY8sYPgtSd8Ag",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.1-flash-lite',
  {
    contents: [
      {
        parts: [{ text: 'I need help planning a road trip from San Francisco to Los Angeles.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "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: 'model',
      },
      { parts: [{ text: 'Yes, what are some good places to stop?' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 2048 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-flash-lite",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I need help planning a road trip from San Francisco to Los Angeles."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "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": "model"
      },
      {
        "parts": [
          {
            "text": "Yes, what are some good places to stop?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 2048
    }
  }
}'
```

```
To give you the best recommendations, it helps to know which route you plan to take. There are two primary ways to drive from San Francisco to LA:

### 1. The Scenic Route: Highway 1 (Pacific Coast Highway)
This is the "bucket list" drive. It takes **8–10+ hours of pure driving time**, so it’s best done over 2–3 days. If you have the time, this is the way to go.

*   **Santa Cruz:** A classic surf town with a vintage boardwalk and amusement park.
*   **Monterey & Carmel-by-the-Sea:** Visit the famous Monterey Bay Aquarium, then drive the **17-Mile Drive** into the fairytale-like village of Carmel.
*   **Big Sur:** The crown jewel of the trip. Stop at **Bixby Creek Bridge** for photos and **Pfeiffer Big Sur State Park** for redwoods. 
    *   *Note: Check Caltrans for road closures, as landslides occasionally affect parts of Highway 1.*
*   **Hearst Castle (San Simeon):** A stunning, opulent estate built by William Randolph Hearst. Be sure to stop at the nearby **Elephant Seal Vista Point** to see hundreds of seals lounging on the beach.
*   **San Luis Obispo & Pismo Beach:** Great spots for a lunch break. If you like wine, detour slightly inland to the **Paso Robles** wine region.
*   **Santa Barbara:** Known as the "American Riviera," it has beautiful Spanish architecture, great seafood on the pier, and excellent shopping.

---

### 2. The Efficient Route: I-5
If you need to get to LA quickly (5–6 hours), you’ll take I-5. It is mostly farmland and not particularly scenic, but there are a few interesting pit stops:

*   **Harris Ranch (Coalinga):** A famous halfway point. It’s a massive cattle ranch and steakhouse. You’ll smell it before you see it, but it’s a quintessential California road trip stop for a burger.
*   **Tejon Outlets:** Located near the bottom of the Grapevine (the mountain pass into LA), it’s a good place to stretch your legs and do some shopping before hitting the LA traffic.
*   **Valencia/Magic Mountain:** If you’re a thrill-seeker, Six Flags Magic Mountain is right off the freeway just as you enter the LA area.

---

### A "Hybrid" Option (The Best of Both Worlds)
If you want some scenery without committing to the full winding coastal road, do this:
1.  Take **US-101 South** out of San Francisco.
2.  Stop in **San Luis Obispo**.
3.  Cut over to the coast to drive through **Santa Barbara** and **Malibu** as you enter Los Angeles. This avoids the slowest parts of the central coast while still giving you that beautiful Pacific ocean view for the final leg of the trip.

**A few tips for your trip:**
*   **Traffic:** Try to time your arrival into Los Angeles to avoid rush hour (7–10 AM or 3–7 PM). If you hit the LA freeway system during those times, your trip could easily double in length.
*   **Direction:** Driving North-to-South (SF to LA) is actually better for the scenic route because you are in the lane closest to the ocean, making it easier to pull over into lookout points.

**Do you have a specific number of days in mind for the trip, or are you looking for a particular vibe (e.g., foodie spots, nature, or shopping)?**
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "To give you the best recommendations, it helps to know which route you plan to take. There are two primary ways to drive from San Francisco to LA:\n\n### 1. The Scenic Route: Highway 1 (Pacific Coast Highway)\nThis is the \"bucket list\" drive. It takes **8–10+ hours of pure driving time**, so it’s best done over 2–3 days. If you have the time, this is the way to go.\n\n*   **Santa Cruz:** A classic surf town with a vintage boardwalk and amusement park.\n*   **Monterey & Carmel-by-the-Sea:** Visit the famous Monterey Bay Aquarium, then drive the **17-Mile Drive** into the fairytale-like village of Carmel.\n*   **Big Sur:** The crown jewel of the trip. Stop at **Bixby Creek Bridge** for photos and **Pfeiffer Big Sur State Park** for redwoods. \n    *   *Note: Check Caltrans for road closures, as landslides occasionally affect parts of Highway 1.*\n*   **Hearst Castle (San Simeon):** A stunning, opulent estate built by William Randolph Hearst. Be sure to stop at the nearby **Elephant Seal Vista Point** to see hundreds of seals lounging on the beach.\n*   **San Luis Obispo & Pismo Beach:** Great spots for a lunch break. If you like wine, detour slightly inland to the **Paso Robles** wine region.\n*   **Santa Barbara:** Known as the \"American Riviera,\" it has beautiful Spanish architecture, great seafood on the pier, and excellent shopping.\n\n---\n\n### 2. The Efficient Route: I-5\nIf you need to get to LA quickly (5–6 hours), you’ll take I-5. It is mostly farmland and not particularly scenic, but there are a few interesting pit stops:\n\n*   **Harris Ranch (Coalinga):** A famous halfway point. It’s a massive cattle ranch and steakhouse. You’ll smell it before you see it, but it’s a quintessential California road trip stop for a burger.\n*   **Tejon Outlets:** Located near the bottom of the Grapevine (the mountain pass into LA), it’s a good place to stretch your legs and do some shopping before hitting the LA traffic.\n*   **Valencia/Magic Mountain:** If you’re a thrill-seeker, Six Flags Magic Mountain is right off the freeway just as you enter the LA area.\n\n---\n\n### A \"Hybrid\" Option (The Best of Both Worlds)\nIf you want some scenery without committing to the full winding coastal road, do this:\n1.  Take **US-101 South** out of San Francisco.\n2.  Stop in **San Luis Obispo**.\n3.  Cut over to the coast to drive through **Santa Barbara** and **Malibu** as you enter Los Angeles. This avoids the slowest parts of the central coast while still giving you that beautiful Pacific ocean view for the final leg of the trip.\n\n**A few tips for your trip:**\n*   **Traffic:** Try to time your arrival into Los Angeles to avoid rush hour (7–10 AM or 3–7 PM). If you hit the LA freeway system during those times, your trip could easily double in length.\n*   **Direction:** Driving North-to-South (SF to LA) is actually better for the scenic route because you are in the lane closest to the ocean, making it easier to pull over into lookout points.\n\n**Do you have a specific number of days in mind for the trip, or are you looking for a particular vibe (e.g., foodie spots, nature, or shopping)?**",
            "thoughtSignature": "AY89a1+DkEptfX85ePwyRFYqv6jZiAGO5Z7gzH3IQR8a6+hYSOlBbY9Ho3m/LdqNW6M="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 64,
    "candidatesTokenCount": 778,
    "totalTokenCount": 842,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 64
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 778
      }
    ]
  },
  "modelVersion": "gemini-3.1-flash-lite",
  "createTime": "2026-07-21T16:29:09.152935Z",
  "responseId": "VZ5faueqCc3M8sYPy9OuKQ",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.1-flash-lite',
  {
    contents: [
      {
        parts: [{ text: 'Write a short story opening about a detective finding an unusual clue.' }],
        role: 'user',
      },
    ],
    generationConfig: { maxOutputTokens: 1500, temperature: 0.8 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-flash-lite",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a short story opening about a detective finding an unusual clue."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 1500,
      "temperature": 0.8
    }
  }
}'
```

```
The rain hammered against the window of the brownstone, a frantic, rhythmic drumming that did little to drown out the silence of the crime scene. Detective Elias Thorne knelt on the hardwood floor, his knees popping in the quiet room. 

The victim, a reclusive clockmaker, lay sprawled near his workbench, but Thorne’s eyes weren't on the body. They were fixed on the center of the Persian rug, where a single, pristine object sat undisturbed by the violence that had clearly unfolded here.

It was a porcelain teacup, filled to the brim with fine, dry sand. 

Thorne reached out with a gloved hand, careful not to disturb the delicate china. As he leaned closer, he saw something that made the hair on his neck prickle. Suspended in the center of the sand, perfectly vertical and defying the laws of gravity, was a single, iridescent blue feather. It wasn't resting on the surface; it was anchored deep within, as if the sand had been poured around it while it stood upright.

He clicked his flashlight on, the beam cutting through the gloom. As the light hit the feather, the sand didn't just glitter—it began to flow, like a slow-motion whirlpool, spiraling toward the base of the cup without ever spilling over the rim. 

"Well," Thorne whispered to the empty room, his breath hitching in his chest. "That’s not how physics works."
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "The rain hammered against the window of the brownstone, a frantic, rhythmic drumming that did little to drown out the silence of the crime scene. Detective Elias Thorne knelt on the hardwood floor, his knees popping in the quiet room. \n\nThe victim, a reclusive clockmaker, lay sprawled near his workbench, but Thorne’s eyes weren't on the body. They were fixed on the center of the Persian rug, where a single, pristine object sat undisturbed by the violence that had clearly unfolded here.\n\nIt was a porcelain teacup, filled to the brim with fine, dry sand. \n\nThorne reached out with a gloved hand, careful not to disturb the delicate china. As he leaned closer, he saw something that made the hair on his neck prickle. Suspended in the center of the sand, perfectly vertical and defying the laws of gravity, was a single, iridescent blue feather. It wasn't resting on the surface; it was anchored deep within, as if the sand had been poured around it while it stood upright.\n\nHe clicked his flashlight on, the beam cutting through the gloom. As the light hit the feather, the sand didn't just glitter—it began to flow, like a slow-motion whirlpool, spiraling toward the base of the cup without ever spilling over the rim. \n\n\"Well,\" Thorne whispered to the empty room, his breath hitching in his chest. \"That’s not how physics works.\"",
            "thoughtSignature": "AY89a1/6wTGp3Yq8GtD5KlCLzP3qfjfpyt5QrXvsDKNbS4FR2jBPXckbTU1JKLs3JRY="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 13,
    "candidatesTokenCount": 300,
    "totalTokenCount": 313,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 13
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 300
      }
    ]
  },
  "modelVersion": "gemini-3.1-flash-lite",
  "createTime": "2026-07-21T16:29:13.373559Z",
  "responseId": "WZ5farfmFuDa8sYPwZ-jsAU",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

Generate ContentChat Completions

▶contents\[]

`array`required

▶systemInstruction{}

`object`

▶generationConfig{}

`object`

▶safetySettings\[]

`array`

▶tools\[]

`array`

toolConfig

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶candidates\[]

`array`

▶usageMetadata{}

`object`

modelVersion

`string`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-lite/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-lite/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-lite/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-lite/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-lite/#page","headline":"Gemini 3.1 Flash Lite","description":"Google's lightest and most cost-efficient Gemini model for high-throughput tasks.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-lite/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
title: Gemini 3.1 Flash TTS
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 3.1 Flash TTS

Text-to-Speech • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-tts/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-3.1-flash-tts`

- Third-party
- Zero data retention

| Model Info | |
| --- | --- |
| Zero data retention | Yes |
| Pricing | <ul><li>Input audio (per 1M tokens)$3.00</li><li>Input text (per 1M tokens)$0.75</li><li>Output audio (per 1M tokens)$12.00</li><li>Output text (per 1M tokens)$4.50</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-3.1-flash-tts',
  { text: 'Hello, welcome to Cloudflare AI Gateway!' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-flash-tts",
  "input": {
    "text": "Hello, welcome to Cloudflare AI Gateway!"
  }
}'
```

```json
{
  "audio": "data:audio/l16;base64,...",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Custom Voice** — Generate speech with a specific voice</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.1-flash-tts',
  { text: 'The quick brown fox jumps over the lazy dog.', voice: 'Puck' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-flash-tts",
  "input": {
    "text": "The quick brown fox jumps over the lazy dog.",
    "voice": "Puck"
  }
}'
```

```json
{
  "audio": "data:audio/l16;base64,...",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Longer Text** — Convert longer text to speech</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.1-flash-tts',
  {
    text: 'Artificial intelligence has transformed the way we interact with technology. From voice assistants to autonomous vehicles, AI is reshaping our daily lives and creating new possibilities for innovation.',
    voice: 'Charon',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-flash-tts",
  "input": {
    "text": "Artificial intelligence has transformed the way we interact with technology. From voice assistants to autonomous vehicles, AI is reshaping our daily lives and creating new possibilities for innovation.",
    "voice": "Charon"
  }
}'
```

```json
{
  "audio": "data:audio/l16;base64,...",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Narrative Voice** — Generate speech with a narrative voice style</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.1-flash-tts',
  {
    text: 'Once upon a time, in a kingdom far away, there lived a brave knight who sought to protect the realm from all dangers.',
    voice: 'Kore',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-flash-tts",
  "input": {
    "text": "Once upon a time, in a kingdom far away, there lived a brave knight who sought to protect the realm from all dangers.",
    "voice": "Kore"
  }
}'
```

```json
{
  "audio": "data:audio/l16;base64,...",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

text

`string`requiredmaxLength: 10000The text to convert to speech. Maximum 10,000 characters.

voice

`string`enum: Zephyr, Puck, Charon, Kore, Fenrir, Leda, Orus, Aoede, Callirrhoe, Autonoe, Enceladus, Iapetus, Umbriel, Algieba, Despina, Erinome, Algenib, Rasalgethi, Laomedeia, Achernar, Alnilam, Schedar, Gacrux, Pulcherrima, Achird, Zubenelgenubi, Vindemiatrix, Sadachbia, Sadaltager, SulafatThe voice to use for speech synthesis

temperature

`number`minimum: 0maximum: 2Controls randomness in generation (0-2)

topP

`number`minimum: 0maximum: 1Nucleus sampling threshold (0-1). Tokens with cumulative probability up to topP are considered

topK

`integer`exclusiveMinimum: 0maximum: 9007199254740991Only sample from the top K tokens. Smaller K = more focused, larger K = more diverse

maxOutputTokens

`integer`exclusiveMinimum: 0maximum: 9007199254740991Maximum number of tokens to generate

▶stopSequences\[]

`array`Sequences where the model will stop generating further tokens

audio

`string`Base64-encoded audio data (WAV format)

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-tts/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-tts/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-tts/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-tts/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-tts/#page","headline":"Gemini 3.1 Flash TTS","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.1-flash-tts/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Google's most intelligent Gemini model with improved reasoning, a medium thinking level, and a 1M token context window.
title: Gemini 3.1 Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 3.1 Pro

Text Generation • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-3.1-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-3.1-pro`

- Third-party
- Zero data retention

Google's most intelligent Gemini model with improved reasoning, a medium thinking level, and a 1M token context window.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/gemini/) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input <=200k (per 1M)$2.00</li><li>Cached input <=200k (per 1M)$0.20</li><li>Output <=200k (per 1M)$12.00</li><li>Input >200k (per 1M)$4.00</li><li>Cached input >200k (per 1M)$0.40</li><li>Output >200k (per 1M)$18.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-3.1-pro',
  { contents: [{ parts: [{ text: 'What are the three laws of thermodynamics?' }], role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-pro",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the three laws of thermodynamics?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
The laws of thermodynamics describe how energy moves and changes form within physical systems. While the prompt asks for the "three" laws, there are actually four (scientists realized later that they needed a foundational law, which they named the "Zeroth" law). 

Here are the three main laws of thermodynamics, explained simply:

### **1. The First Law: The Law of Conservation of Energy**
* **The Concept:** Energy cannot be created or destroyed; it can only change forms or be transferred from one object to another.
* **What it means:** The total amount of energy in the universe is constant. For example, a car engine doesn't "create" energy to move the car; it converts the chemical energy stored in gasoline into mechanical energy (motion) and thermal energy (heat). 
* **The famous summary:** *"You can't get something for nothing."* (You cannot create energy out of thin air).

### **2. The Second Law: The Law of Entropy**
* **The Concept:** In any isolated system, the total **entropy** (disorder or randomness) will always increase over time. 
* **What it means:** Energy naturally disperses. This is why a hot cup of coffee will always cool down in a room, but a cold cup of coffee will never spontaneously absorb heat from the room to boil. Furthermore, because energy disperses, no energy transfer is 100% efficient. Whenever you convert energy from one form to another, some of it is always "lost" as unusable waste heat. 
* **The famous summary:** *"You can't even break even."* (Because of entropy, you will always lose some usable energy in any process).

### **3. The Third Law: Absolute Zero**
* **The Concept:** As the temperature of a system approaches **absolute zero** (0 Kelvin, or -273.15°C), the entropy of the system approaches a constant, minimum value. 
* **What it means:** Absolute zero is the theoretical point where all thermal energy is gone and the atoms stop moving entirely. The third law dictates that while we can get extremely close to absolute zero, it is physically impossible to actually reach it. 
* **The famous summary:** *"You can't get out of the game."* (You can never reach absolute zero, so there will always be *some* heat and entropy).

***

### **Bonus: The "Zeroth" Law**
Formulated after the first three laws were already established, scientists realized they needed a law to define temperature itself. Since it was the most fundamental, they called it the "Zeroth" Law.
* **The Concept:** If System A is in thermal equilibrium (the same temperature) with System B, and System B is in thermal equilibrium with System C, then System A and System C must also be the same temperature.
* **What it means:** This seems obvious, but it is the foundational rule that allows thermometers to work!
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "The laws of thermodynamics describe how energy moves and changes form within physical systems. While the prompt asks for the \"three\" laws, there are actually four (scientists realized later that they needed a foundational law, which they named the \"Zeroth\" law). \n\nHere are the three main laws of thermodynamics, explained simply:\n\n### **1. The First Law: The Law of Conservation of Energy**\n* **The Concept:** Energy cannot be created or destroyed; it can only change forms or be transferred from one object to another.\n* **What it means:** The total amount of energy in the universe is constant. For example, a car engine doesn't \"create\" energy to move the car; it converts the chemical energy stored in gasoline into mechanical energy (motion) and thermal energy (heat). \n* **The famous summary:** *\"You can't get something for nothing.\"* (You cannot create energy out of thin air).\n\n### **2. The Second Law: The Law of Entropy**\n* **The Concept:** In any isolated system, the total **entropy** (disorder or randomness) will always increase over time. \n* **What it means:** Energy naturally disperses. This is why a hot cup of coffee will always cool down in a room, but a cold cup of coffee will never spontaneously absorb heat from the room to boil. Furthermore, because energy disperses, no energy transfer is 100% efficient. Whenever you convert energy from one form to another, some of it is always \"lost\" as unusable waste heat. \n* **The famous summary:** *\"You can't even break even.\"* (Because of entropy, you will always lose some usable energy in any process).\n\n### **3. The Third Law: Absolute Zero**\n* **The Concept:** As the temperature of a system approaches **absolute zero** (0 Kelvin, or -273.15°C), the entropy of the system approaches a constant, minimum value. \n* **What it means:** Absolute zero is the theoretical point where all thermal energy is gone and the atoms stop moving entirely. The third law dictates that while we can get extremely close to absolute zero, it is physically impossible to actually reach it. \n* **The famous summary:** *\"You can't get out of the game.\"* (You can never reach absolute zero, so there will always be *some* heat and entropy).\n\n***\n\n### **Bonus: The \"Zeroth\" Law**\nFormulated after the first three laws were already established, scientists realized they needed a law to define temperature itself. Since it was the most fundamental, they called it the \"Zeroth\" Law.\n* **The Concept:** If System A is in thermal equilibrium (the same temperature) with System B, and System B is in thermal equilibrium with System C, then System A and System C must also be the same temperature.\n* **What it means:** This seems obvious, but it is the foundational rule that allows thermometers to work!",
            "thoughtSignature": "AY89a197GECnMwUlM7wtji6/asWPmDOw31IcboL2qXHjETlhZBJfD5iMStj+z9+vySalZtJ1NQYfQF8JpOU7SnXTCMwSHOnVB4Ldz/M2rubkfi11yR+XetAYveyWbs12yboQ4Q2IuojZuBWhHcv5oW3XWzaw/d4xiCdrnmDaqN2BY3xHEaaXQuhVvGqsMJZcQoHGBmoOMupngIq1CGjIrpqVcDXKQ5d2ib99wWnr6zbkcuO9MlSnZQ5N9/9h5lXX62se9hIAiN9dXB5XAjbTfpudRIHsZick+tsJ19B3QF6opQQzTtVxwmuJviFAQMe3QA4CIfqQUhBkCdqs/dYMQ9TeYCUnpFOVDEh6a9qeXhmnPt1YspA3Uur942oQ6EB1uvFAoOMTjKFn/JvsP0+4Ip0/MuULcgfIGPLYo5pgtVa3eS4B9yBaaIq/RAUK2g8lgvjSZI7h7bshhHbIjL5IVExxGegnhy1dqOf/X1tWaRVydvAEQCNrF1wqDfxcUut0xPNVBtFOFMvDUOjiWbrxecTjLDfHe6XiLBQpzaSsAxIqiQFs1qobbqPwaghCHzkdFM5A8CMlG68d1R4P6uxgo7rQzwik1D4Yy4iwCDS9IX5gXQWRCD5qgHGRdftnW9B15l/Cg9Ssgk14+lSUX1VuSNRm34s+wDV5mYwd6NwBe9Q3r13BOXynglWFjKkWKcTaYXeWuyrtdkzZB+Dh4aCTAN3dndni3YKiMCsVVyJr8VN2iaWZ3cC58mqH/PGJ4D2C1ZBuvW3VQvU2QponJUbD2jgG8jVL1zDzt7M80aCjhm6Tnkqge27wCiqFoXxYY8gxPy3YG7P2/EDHq8XuEDYugsH8vGp9htY5LUE6W7ARvFGmXDaSoEuMdirhFPVHF30tlMqVOp12ezV5O30FnPf12ZFQ6jCt24QOCAW+xJGdBcj9tqtLPk9hwopmcOMO+cd+1xSgRAr7g2+HqAv5yocnQe9JSnA9O/QmHEfz2aPRcIqcgI5ETTfll5hWchZ1D9i/+5GBOryHTgcldaYgbK+kZwtWQs8YwPPQhZWEOAgl9gy+w6eZOf77xwzw4a4BDRfVVPbebFAiz90RG6a7SD2pkr9LRgzwJty4o6WOK+s+Jk0QqhHxHCgx9zvaMCy9ZsO3TaApzCZcCvqW7dAx7Lu1I+8dBFjf5l3erM9aFSHLAhOKsq8gjJ/4kHnIPxBs1+SSWY50rZeXUM0WlJEGZ9um03hK2sQSi2GEf1okv0rq4/2xEEadZu693U8syOUYAPU2rhfvSAFVa1XjubQGFuTiIqnLRm5OYCeckyjOE2Ydmq2xOd58sFE77S1LhHLwWsKedwBE7lcMadTBLBT7/BLo/0fBYcbmp0VtwcghSeatRV6oYXA3GYYtaPGn5TH7+ZIf4Nmrht/uJwoKrTjF8ez+mBXec5eiat+UgAtpXp/w1nBd8tfAjsSmgFpaFEeocYJB5X9+FkltYvSUvz582R55JF8yd+f871Yesxi1QdkryKzoae3NmW0jam4osWdvaYolWQHkRKhI0ETh6Nk9839LF+YcSeuFL1GrBeULTkuGQ5AqgqoWhC6qJ0QbtL2qGn0SnyevkK05aXVAx1n5IIPvwYcHQTKkNv5byDyqhNMed7CdR+C1SeLSsGTv6OAO7mfGFLp9uHJhwocLPfmmwgmxzzIjFhsVGwFUrAo8qgU/8efuBzUq3gQSpw6KFRRTACuh2eqTPG+8+umpdPfxrWODcHB/GkJJTapdWzEYKL/2UPWTPx195WLXThCDnW1SLjbz36SreEDpT74s3UoZno977cNMORziHnkJTTGKoYcwMCfhwqgAOFGPcXArdSAbayUGKaASM9hmymn94YJrnH0Zhw3EcAy007QpBDsE/LSUBNl5iEGvmATWTRshPAVlYuU7OVyz7fVgVsbjk4ISb/AzEcNH7RDxjDTivuMl3waURfYgj+G2fdoAALCchRM9j47aGNCMBqPFt0q8B4MU8kk4ck2JuKuarD6AA0LcL/5f+UdUyoSF8RWVE/zxIaNsf6FYc9FSgP+1TZzzGqzhwENnbo6Xh/oxPnAzEw6Qdajm4Qr2Nd10CI05ZDeMTygTsOeDiX1Vx9PmUzOBK5Pg94ZpAplPn5OLe2mcdkrt+JFNdYEfSNtrlmDpRXC6wNrovJ+8HMKy+ogj/CnBLx8pL3zUHwTEPCKyxncS2CcI5VKHSacVLiqOgZtZTOvGpO6CeG8SfR4x2sxlrcB7EQTJV/rbi6oWCfsMEeilpdZwtripKVJZjAswZxwHqXbkg/HMmJQAg9BF0TzZdqRkXxAJWemfQoi6EUCkp5IY/lM8L04qnuap2JAkgnHOviFBk3fk4y1Giziz070+IHqVv17hWNvBB9ll+VUN8ppz+dCgEZTW+37v3MpPznbJq6m8J2CGwNbckZ4q7xaEWmbnycDR8himbL34CRIaRrLuJXOWqd/38mzGi+NA1qfVPkXPu9Ad4DirwcoL7KIWSjIrhinN/zwVi4u3ZhW/bo2OypnmL6Wo//gDoS2WVE7qJgI/dip/c4cAeyoQIWscd+xlWm8GRFkTIjKyEFtiT5bqB5MwPsKOZvZSjHxhGZUBI9gg3WczG8Il/ff6OYFT9GKbP90XT3/3D+ExlTrxkoU1i9qq9ImTIzGVob25kDV9pdlHE04NPV+aWKgR9f9wFCMIFqCv5ZONtrtbc1hgLlXNU+grsGQUHn87sG5b8bMrv9UFEWGjIBm/EjHrUCbE8lm9lvdJWXZc4n+PAoFibUdGy1Xesb02kRcNYKq17g7QETGYStxYimvWvArUjkZDzIB+PkKna4S3gRpjjvlSk7qKMYLxVQchoLBIb9ebqfWMUHqs+GLS7X+6gxlSKNFp+c1K9tieJnRhG9UX52siNth6vWUYx4Z23aYJ+XjUaNhaG5FKFqPgxMGf2Vvgde0X+GageuaDeZTPwYPX2mqRFxIG2bCEljfz662lwgDxSIN0qYm744+LDR1fGR1w71ChPSTADjr9ek5TmeVHpgTKlIONbFrtlRNoBpCtHYIOM7GaK4byFEQDUJAJwFvJQNOqRQkHQ5Ug1wWwfPkGpPf5WiFNd6FxLcKGj8mipQ7gbWWqOfP0UuIak761xMKRvLc97j4+XbfI/3T/n1kOxqhrZswgDh+EmSa96fGaDVzxGJe52C+XKSWwDtb4M16XDBzcxzOZZl3Xo7edtiisivYeNXEhWoVcZrh2q1RNDopHqr+yKbrOVKpD6rotAx6avFynW8eadGnCFo5Q6MgIy8LT/71brdzAuaDYlxKAL4L2ox33bR3L++bOni6Mwi1w5xdHA8nfrseZ07jC9GwMPhQPZ8cJP0JitkdmRVHBZVXRm3uqRif7J9fqXxwvQS66TzC65E9FGEOJdBU+EEl3F1O4KDDuI1ebNYKCxDs7eenWjnp6O7N/p/FcZCldZsiZq/QiWgLijr3JKVD80Jo3ec74r0YVkyAGmRmtwfLXcooR54GUg3gVi8h4antCom5BSUZrBZ42MEbwRPuhbMNxVI7d4DsMlp6uuKdAlN0D3a6ifCKhqNIBSMD4iW5aZZVbk2f9ordELgf1/VKbXV6uX/GqBAdPoEjlS62V1dP4d1hPBJCZYFGMxz+rdPZKKaFfdG40oHXECO2BnyQUr7YXVq+cmPE8anjxAgVYE8zbhBSek4FpAvDZLeA8nG4r/+zxtMydcQwawqYFEOLKD8ihbRRITvMuez7FfFMDr+IQ1oGFaTgEZ+QhK+v1Jl1lSOlCtf4DsAJOld7Pu8PUsSYoKpa8kgHTe4nhFXLaXbuMggi45+5grfY445INA4cc+JestOFwIJSflAFM6T1lJrtjurvBKbG1NhBN/D2r1VCA3GnQBz2NcqTSBMWtOqME2OVh6MgoYqM5WjkQXmuuMnR4PahMLBbmjS/DSy9VYlTZza8Ybz5sQB/6SxhX09CvpsBPyNpjG4/HZiJOFbzxd1uEbKV9BY9+X6uOJ+Fz60Lp0fG37idVqfzzkJ8pRd6eIf8q+Z5KFobTQWe+ZRd7PvmugPt3j7atAPU+MxgkH1su2jwShATGIvmLqwIwTMHa2v3Uuen0qo+9nD/JzKnzUY3SqIofbkqHsRi5SFvHu/swt3OxBkYmM2v2ajT1TI8kcaseI5EWOMpcvsHDSK23sV6dLEJWG54/hi87aEWABhW1DhRXupusCUwA3Tdgq4W12E3r1l4wP/WoKDzBjRu4juaYEtpq4mWdkTQchivrr+6sOqdi4QTiATX4+mdaQGzVcjMs+54zRC62OkYEokJ0SPSOtUPYJZWwUn2JzyeGBspGhKiywJr6aGI35yneGMDS6FvjMCtG+4V2H23oQovfRO1P1DGasDsbBORnw6vSCqibHIkvBdqTBbIK3ANYRvfgP+vuaFqaVwmNsd9LfEEuHNoxFqq9TtLDxbLmvzOVGdRGQ2XbgPbZwUsEsKVd+g3gbj8GcfXunnlvCKhIdGeHTsiYBX+ZX9nHQeGnZcfGTsyIscqZ2bPs7lT+cjm2GttZJZdSzAN+t6qCgyPmSOngDeY30ptMt47KRhg9mZutg8mFRkJH4hJPBXtqxW71+kF5CcPBBEfl9yi1fcnOcwjkAlT7NBg4eM+bbBTFgtJYio7QulEgQTbgHkJ/xVtMPJ5UtbjDnMot8f/VxmaemUJqr1m8o4gxtllh+RMy8cimG0Me53F+htJxqBRZh3RwEZxAfDcfxXLYxt7R42UNC++UammCA+HEjMr56jDXz9EP5kiuPucms3aG7OOD1MSg261udCCfa29pkQvulvwqCCkjBGlx02lwpPkxq49JX3mw7UjpODb3YA=="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 8,
    "candidatesTokenCount": 626,
    "totalTokenCount": 1489,
    "trafficType":
... response truncated ...
```

## Examples

<details>

<summary>**With System Instruction** — Using a system instruction to set context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.1-pro',
  {
    contents: [{ parts: [{ text: 'How do I read a JSON file in Python?' }], role: 'user' }],
    generationConfig: { temperature: 0.3 },
    systemInstruction: {
      parts: [{ text: 'You are a helpful coding assistant specializing in Python.' }],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-pro",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "How do I read a JSON file in Python?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "temperature": 0.3
    },
    "systemInstruction": {
      "parts": [
        {
          "text": "You are a helpful coding assistant specializing in Python."
        }
      ]
    }
  }
}'
```

````
To read a JSON file in Python, you can use the built-in **`json`** module. 

Here is the most standard and recommended way to do it:

```python
import json

# Open the file in read mode
with open('data.json', 'r', encoding='utf-8') as file:
    # Load the JSON data into a Python dictionary
    data = json.load(file)

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

### Breakdown of the code:
1. **`import json`**: Imports Python's built-in JSON library.
2. **`with open(...) as file:`**: This is the best practice for opening files. The `with` statement ensures that the file is automatically closed as soon as the block of code finishes, even if an error occurs.
3. **`encoding='utf-8'`**: It is highly recommended to specify the encoding, especially if your JSON file contains special characters or emojis.
4. **`json.load(file)`**: This function reads the file and converts the JSON data into the corresponding Python object (usually a dictionary or a list).

---

### Best Practice: Adding Error Handling
If there is a chance the file might not exist or the JSON is formatted incorrectly, it's a good idea to use a `try-except` block:

```python
import json

try:
    with open('data.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
        print("File loaded successfully!")
        
except FileNotFoundError:
    print("Error: The file was not found.")
except json.JSONDecodeError:
    print("Error: The file does not contain valid JSON.")
```

### Bonus Tip: `json.load()` vs `json.loads()`
* Use **`json.load()`** (no 's') when reading directly from a **file**.
* Use **`json.loads()`** (with an 's' for string) if you already have JSON data saved as a Python **string** variable.
````

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "To read a JSON file in Python, you can use the built-in **`json`** module. \n\nHere is the most standard and recommended way to do it:\n\n```python\nimport json\n\n# Open the file in read mode\nwith open('data.json', 'r', encoding='utf-8') as file:\n    # Load the JSON data into a Python dictionary\n    data = json.load(file)\n\n# Now you can use 'data' like a normal Python dictionary\nprint(data)\n```\n\n### Breakdown of the code:\n1. **`import json`**: Imports Python's built-in JSON library.\n2. **`with open(...) as file:`**: This is the best practice for opening files. The `with` statement ensures that the file is automatically closed as soon as the block of code finishes, even if an error occurs.\n3. **`encoding='utf-8'`**: It is highly recommended to specify the encoding, especially if your JSON file contains special characters or emojis.\n4. **`json.load(file)`**: This function reads the file and converts the JSON data into the corresponding Python object (usually a dictionary or a list).\n\n---\n\n### Best Practice: Adding Error Handling\nIf there is a chance the file might not exist or the JSON is formatted incorrectly, it's a good idea to use a `try-except` block:\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r', encoding='utf-8') as file:\n        data = json.load(file)\n        print(\"File loaded successfully!\")\n        \nexcept FileNotFoundError:\n    print(\"Error: The file was not found.\")\nexcept json.JSONDecodeError:\n    print(\"Error: The file does not contain valid JSON.\")\n```\n\n### Bonus Tip: `json.load()` vs `json.loads()`\n* Use **`json.load()`** (no 's') when reading directly from a **file**.\n* Use **`json.loads()`** (with an 's' for string) if you already have JSON data saved as a Python **string** variable.",
            "thoughtSignature": "AY89a1/WVQVfP8X81xtbe/Y3eP4vwcFwMmemlaAcD6N/8fTRHsROrZr1DG00bINwygCw86NfVtlJCMVVj2WSJgOjnpj5HOLNxpzdsZXEQnAMyZ5R46j2XVXo5k9Ak/qlbbR4gT5YjEMTge1zojUzgH0vlOr4tqfGP5DgFgalGKt4Oy1Xf+7nnsQUwEFqpPpGNpCXCB1piwk/QpeQkywhmrLvtRvKbmpqyND8NiQOok38MchvygH4Yhq66zy+LUHV1awSmVeydrRBpWckgI9n3BmFZC8woyqHYyXqqj8X8sFzz7QA1Ohp5dbvOUKb9Jv02CgWXxjrkCYXYaDIgGf9b2UwFYzb56L7bwGj9qHnUuIaUIM4SvnW970wNgNHTDjVO9y1or8PCY/3L9MI5RPKZyTx18/UhxQkhDBUfMk72RHhlgQRZcw2zOyaX8AQfthY+qB4PKs61MTvNt2N+PuEArTaHSn8f00hGniQ0S+yRFD0zAb1iOhrsOAG38jCnH2TzeVc8+TN0Gx6paG7FEMC9iUVLucMPS5GHgi68r9n0bCY+dawK8o3x6fkvrl/97mNhOey015/w2RUGz1S45Ga3cTFh8/YoVrDVrn1KIRTWqLRBtv5re8x0Q/rfMEgYLasoyRnR45gINNKz6XpD5iYv9NxksoL7HTXJzSwsiKyEMKx/x4cntCsY2eAuiiXTnFWl28O/0TFOJyNjSdif9XTpaTP9FsQ5EvQ/uEHPQy3h6BiHkE/ektGC0AtuXLEKPLONyBTHln6RILmfsr9fIgJ7BJaarCLE+biY87/ArDpRj7xF/hyIe/wqmAZYQtI2GxssOKdQ9bpje86x3XD0t+KD0RniuLEFknMH6MIF7iaCJT0Xr5oZxoqU/IR+4ldfKJUA7tYXgLuotBarfetiIIFwxWJQpyohO3alfbMv2D2b69bKJ4FX6x+tq8ZjKChIZ3d4gMMiDGv21a9EvUhCjK3oBu6/1eIWYfK3OC5jkv3lCxK7UD1L+22p1m3pQv4c0iv8oj/PI0a22g1dstNpddd8rX15k9842TWWE/kj/le9bIFTKvm4+Az2gUznaHM7i//9zoZJVNo7X7KUThIpRuSFjtWh/aBtS7yiF7PkBz2TaZ4RS+gZAnSTiJt3zy0eCGMsGql0cZPJae895XWD6a0npQ42Q0mMg6LfMNBXLWuN7LvRKDeQV+prJ1l5/LnzYNTCFr+SxFovn1bGLgGpDB/8HR+F+i2a8exCkknt4xJuNVRP/xcbdCGSvKRhr1J3yMgArM2JuM7YchjRJLZJUov4EP72PYKUcleipnJ1vqGDGHMrTnURJcvys9LJ4dqSA+yCYwcLfivR6Z+tT+2jsaIJG27Ne7hHg3k43i17PhNKoEawrWh+b0RQsDCIoJbxLy6No/FY9iswKk3odORflfEZMW4aQrULqTlZXaUy+s0XOv/9z1L/UZPe7N3m10K5Y7v0IrrxdPVh5fGv2mH2Anl4LAdpcZgo9EmZnQEYEAbvT/OKRLtohai9455PTfV4sLvwerc7JtsErvOzDS2WYU/HN6R/n2y/QXSTu/03A4EHPp0qrZO02ftKFMOAkJq6IebHon75WVrI0F8WktOFhcQyqcFjU2QQbvvOx95lNatDyBFLul1LhnzWUILUY4hnWL9QLjWGltLrUW+hie1N+98G9DfDuHTVltm8hvlaNMfle3wVyhfY6Z1ozuXekDwreAObDwExarqkDZHsWcPhaFWXhqfzE92Z6SnXn/eyu0fR5Wq/k2madeiI3ABZpHaP5mR8sQbWie76/Jdu9+jqlXpdqkNFbmrOQdzX4Zpfu0J1k7CAVbmKJVlj5I8C7aVsf//YR+8/4lo1/B8ZtWpSqwS78oitgAl0qoqTm02MguU9E1UelA580kekocvVsiBblTVKL3BlMjmfXdwLS/8kzarNX+955TPQxASsfH7i6nQDfcf/rgkHfeq4zPToNQSUpAa5ICxz/5+Qa115Oz+UWZoGswN2RsWWZVkOpsvuQjAUjlkfi9tQs+9L6htsywaBUbp5Hev/R8iD8V/9/0zycUBv/U/Nal+Q+NX9UIvxjri2inGRA7fCA7Y/HYevIkUNLKRpbS8Uau+mZxCak3QKSPm/ZKrPtqy9O8fvFOgLl3/Bg2XQhkrdm4t7IK0t7nPA8SnvT524GDxAp6zOrBRqACtd9BpvVrsWHiFRms41OUk/wqhnP8SaUhXxEQCa+cyvpnOhvhrmYi9FKAmBTAWojYuJ48kGLZdq/dhGuyzXtMUhf7YuOIPR29EV+0ZZ8VxC65Zn65csmJXoJkIX4dBIkGT7YfT0akJiyVHmfQysN9n9brUh/smhD5sACutFxFb6y7I5QWzU7lIiWrlesf7a9PCD8ZTHxD8gcq+5u3uMGLPIFR1E5YK37QkINzj2Vc637n8Tvs5xa9VDx2xK6tsUKTZMeLGkKbOd1YDwEXkIuFi/npTHUD5cOn7l8CvSK1a4lweFJHPsZsXyue+2ZxUvVZgzRJatE36erCr4XbubFua9FTGDtQVU95n3XW3pJFAkdJ1n6idLa+qD3X7Y/qLlvBO7vD4cPbM27VIExUGcK6HzNTMGoiJAI2ZB5WP0fNfgPMCRhzzsC0Avt1Q9T7i1d4IEcAMcz58G1/9kqlmFoosIbYfGh4BqNLjis49fF68l3AwFye4Yb4mm8KxNLU2+K2wQQPOppfUznKQ/tgwQ4UsjF3wISDVt/Pw3Up2Jc1M14cf1ZphUtI6embyp8y4WxVBJXMBzYx8g5gqijnguUNwZhGH/Ns7CVerczqjw08wyZIKrWSj4H6h4jqxSs05xE3mptoh7Sp3k5cEOMjrUNTJytVbALPyc7jjCX6/mew/Caft0FSiAEXMlir8BhGJQIb9orNpDh0qRIAkJRhnNdSXzfi6ivsfboJltMW5WA71oGuqCASFAZhgO9SOMm8upPOlz0cv8M2n3aVlXi5PLm7QoE7F5zHNUzV9X8/IPu0dIYEQDEapShmrTfIj3XezwHSVZMSmJiCbDmOG04n2cT63xpl42IZdVpWE6Q6aBsxbCsy5nTTNlMEMx8QvZQpXlchdCd3jbcH63e6BfHrKs3tMjhpE7987x2jywpZj1ALWI/l8OZNYxsMdqcpxtaTyfSjsWcplSwI4fUs="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 20,
    "candidatesTokenCount": 461,
    "totalTokenCount": 1079,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 20
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 461
      }
    ],
    "thoughtsTokenCount": 598
  },
  "modelVersion": "gemini-3.1-pro-preview",
  "createTime": "2026-07-24T21:53:04.959579Z",
  "responseId": "wN5jatvIOs27u-gP-sKs4Ao",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.1-pro',
  {
    contents: [
      {
        parts: [{ text: 'I need help planning a road trip from San Francisco to Los Angeles.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "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: 'model',
      },
      { parts: [{ text: 'Yes, what are some good places to stop?' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 2048 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-pro",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I need help planning a road trip from San Francisco to Los Angeles."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "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": "model"
      },
      {
        "parts": [
          {
            "text": "Yes, what are some good places to stop?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 2048
    }
  }
}'
```

```
The stops you make will depend heavily on which route you decide to take. 

If you want to do the drive in **5-6 hours**, you'll take **Interstate 5 (I-5)**, which is the fast, inland route. If you have a full day (or even better, two days), you can take the **Pacific Coast Highway (Highway 1 / US-101)**, which is one of the most famous and scenic drives in the world.

Here are the best stops for both options, listed in order from North to South:

### 🌊 The Scenic Coastal Route (Highway 1 / US-101)
*This route takes 9+ hours of pure driving, so it’s best if you have a whole day or plan to stay somewhere overnight.*

*   **Santa Cruz:** A classic California surf town. You can stretch your legs at the famous Santa Cruz Beach Boardwalk or grab a coffee downtown.
*   **Monterey & Carmel-by-the-Sea:** Monterey is home to the world-renowned Monterey Bay Aquarium and Cannery Row. Right next door is Carmel, a charming, fairytale-like village with boutique shops and a beautiful white-sand beach.
*   **Big Sur:** This is the most dramatic, cliff-hugging part of the drive. Must-sees include the iconic **Bixby Creek Bridge** and **McWay Falls** (an 80-foot waterfall that drops right onto the beach). *Note: Always check Caltrans before your trip, as Highway 1 frequently experiences closures due to landslides.*
*   **San Simeon:** Stop here to see **Hearst Castle** (a magnificent historic mansion on a hill—book tickets in advance!) and the Piedras Blancas Elephant Seal Rookery, where you can see hundreds of massive elephant seals lounging on the beach.
*   **San Luis Obispo (SLO):** A great halfway point. It has a fantastic, walkable downtown area. If you like quirky stops, check out Bubblegum Alley or grab a slice of cake at the wildly eccentric, pink-themed **Madonna Inn**.
*   **Santa Barbara:** Known as the "American Riviera." It features stunning Spanish colonial architecture, great wine tasting, beautiful beaches, and a vibrant downtown street (State Street). 

### 🚗 The Fast Inland Route (I-5)
*This route is mostly flat agricultural land. The stops here are less about sightseeing and more about unique places to grab food and stretch your legs.*

*   **Casa de Fruta (Pacheco Pass):** If you take Highway 152 to connect to I-5, this massive roadside fruit stand/theme park is a legendary California pit stop. Great for snacks, dried fruit, and a quick break.
*   **Harris Ranch (Coalinga):** A massive, famous steakhouse and inn sitting right on I-5. It's a very popular spot to stop for a nice sit-down lunch or dinner.
*   **Kettleman City / Bravo Farms:** Kettleman City is the classic halfway point. It has a massive In-N-Out Burger, but the real star is **Bravo Farms**—a quirky, western-themed roadside attraction with a cheese factory, ice cream, a petting zoo, and lots of souvenirs. 
*   **Tejon Ranch (The Grapevine):** Right before you climb the mountains to drop down into Los Angeles, there are the Outlets at Tejon if you want to do a little shopping or need a final coffee/food break.

**How much time do you have for this trip?** Are you trying to get down to LA in a single day, or are you open to spending a night somewhere along the coast?
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "The stops you make will depend heavily on which route you decide to take. \n\nIf you want to do the drive in **5-6 hours**, you'll take **Interstate 5 (I-5)**, which is the fast, inland route. If you have a full day (or even better, two days), you can take the **Pacific Coast Highway (Highway 1 / US-101)**, which is one of the most famous and scenic drives in the world.\n\nHere are the best stops for both options, listed in order from North to South:\n\n### 🌊 The Scenic Coastal Route (Highway 1 / US-101)\n*This route takes 9+ hours of pure driving, so it’s best if you have a whole day or plan to stay somewhere overnight.*\n\n*   **Santa Cruz:** A classic California surf town. You can stretch your legs at the famous Santa Cruz Beach Boardwalk or grab a coffee downtown.\n*   **Monterey & Carmel-by-the-Sea:** Monterey is home to the world-renowned Monterey Bay Aquarium and Cannery Row. Right next door is Carmel, a charming, fairytale-like village with boutique shops and a beautiful white-sand beach.\n*   **Big Sur:** This is the most dramatic, cliff-hugging part of the drive. Must-sees include the iconic **Bixby Creek Bridge** and **McWay Falls** (an 80-foot waterfall that drops right onto the beach). *Note: Always check Caltrans before your trip, as Highway 1 frequently experiences closures due to landslides.*\n*   **San Simeon:** Stop here to see **Hearst Castle** (a magnificent historic mansion on a hill—book tickets in advance!) and the Piedras Blancas Elephant Seal Rookery, where you can see hundreds of massive elephant seals lounging on the beach.\n*   **San Luis Obispo (SLO):** A great halfway point. It has a fantastic, walkable downtown area. If you like quirky stops, check out Bubblegum Alley or grab a slice of cake at the wildly eccentric, pink-themed **Madonna Inn**.\n*   **Santa Barbara:** Known as the \"American Riviera.\" It features stunning Spanish colonial architecture, great wine tasting, beautiful beaches, and a vibrant downtown street (State Street). \n\n### 🚗 The Fast Inland Route (I-5)\n*This route is mostly flat agricultural land. The stops here are less about sightseeing and more about unique places to grab food and stretch your legs.*\n\n*   **Casa de Fruta (Pacheco Pass):** If you take Highway 152 to connect to I-5, this massive roadside fruit stand/theme park is a legendary California pit stop. Great for snacks, dried fruit, and a quick break.\n*   **Harris Ranch (Coalinga):** A massive, famous steakhouse and inn sitting right on I-5. It's a very popular spot to stop for a nice sit-down lunch or dinner.\n*   **Kettleman City / Bravo Farms:** Kettleman City is the classic halfway point. It has a massive In-N-Out Burger, but the real star is **Bravo Farms**—a quirky, western-themed roadside attraction with a cheese factory, ice cream, a petting zoo, and lots of souvenirs. \n*   **Tejon Ranch (The Grapevine):** Right before you climb the mountains to drop down into Los Angeles, there are the Outlets at Tejon if you want to do a little shopping or need a final coffee/food break.\n\n**How much time do you have for this trip?** Are you trying to get down to LA in a single day, or are you open to spending a night somewhere along the coast?",
            "thoughtSignature": "AY89a1/VDTias+le3Jn45CwRR51o60DI2g5LpXxUzKaW/8Rt94VWKZXixIBISizF6Qy2OBHUcBw02EfJeTs/fLMjh3YQUZyVvNEjo15kJki4BxvcFfmRrLJsLAipjR7QFA/hVSSJBOSLI7jsPQvzFpdF/3SFBk6RKtooUR7QEftb26SctN/3gXtmFzrgEB3HvXC7VTldKzNLaGlUT5fdb0Pj2Mi4uxX2soEg/EnKEVXdMO+LQD5i6XqoBLoaqKjf16M0N8kiJ8uRl2wb2JXxOCCEyagO+ktumAJhC2aWMgel93DWX62e0mj3sYW94ecQ0tzhQO+ghevWLdXi9CPKPOnJ5GefPgiqlZ4elG1IXRrvNMaDkY0xba5QTm/vNLBDJWIhGh5KLdD5OPfZfkVNzI+IIWPXC+QJB2lXy3zEEebOlpMlmPiKk0km4EYN4IbgRU60ZJiYsJzS0mHlb1uqOhspd8AZo63NItrfVnweHp1yEyk0emle8zSvzylFzcTtSAalGNrt314rNgFi86ISjxbBmySKaL2aRckXXElaDdaniPdzb0xvvJ5EbHVk5IgZyllLsm0zLqL8pOMrC6SOEex4zSFvKuxXhVRfcE8lSSzooz+5VTRuk+3l1qU5GB0+LP+htSh2b+q3s5V1aJKpvDpAAF8PMWWwUllvuLjgC/cnB9lS/F/Z3PIV5jRngQyNYPNa5uXItzHppCD2b5jLwtDecdsMVefc2RDGwJEUw5gAzPR+NT4AZ7v4r/AHRJeGGseOigROOnylonAavvzBSBzocLMbmHcwWxizdKWrkO2JcNh4SPFMem75NqVBXqchOT53J2hBZbQKXw2JWsjAvOZKIt2dkWd9p94F9agIRMFiLywOFeAEVLkM88h9s8HQhKBextZWlUNda1yQAJAedFwDB6qK1cd7aWG7FikXULvO+fsHUfaO5o6OJA9mVDgkSijSwHL+29jOV3HYagrxFUIOX5yoQZMaiuHYXtQx6wqC9rZWw1QeP8EYxHwh6ngZbrifJO0NR1QYEGBgFiAldEciTSBW3zEM+cxsJi9KBysyxogaJfY+tCE6A1+EL6TM5s3uIqmU0ggAThqyw+cmP6inKdULpJeuF+6A/dqA0tvK/M8adwlITExXzn5p/DTyt+FCcwpHcHA2qf9Tzq32VIcQFpezzrufXJVYQ0myulydNpqn3lqEllm/utfeGwDrhF3Y+hZM+erRdz0XiXnSqVdpVkHACwRSsg/tbMEMvkbmelACdGZ1udjHSnugrhAxyFOuhZdzWSfT6GNtDAx6KRKOI7rzkFR9d3QWI+8v7y3RUqaE5FpU6bFtcOCMqgebDsb2TnEtSVTRKGkvh2l/+kvr0vEd93WlvMm/byjDI9VoMaBnpyuOuJEkid6HeM1yh4eZFqYhwROuHw7cCtSyCPteH3gxtAQNMFRYxds7oaOgkPNzz72xFmqYA5mOaZwGppImuWf2lwU0w1k2fIRopOIjXkYyQG14ZW2isjo3t9X5ABUEACOsQIko2DewMMOIMcV1GUM7ehnkALqEkx7nj5ENZjRsPs3rO1yuy7WUZ/8xTpIS1Kl3//47uahgZzZzZQlxvIhb2bwArYUvWjcqZQ8cx+ZWnoXrXFtcvt7FqMvCQMdsS2+OUqtF94mkFc9C1iJPsK0htlGxsDsYq/1L6XJ91S8RfNW66J8YFQnnufG7Yvq5rICbuNYjaFX4QVWSTA9Hxy999GSoe/zOwVRj04wV/CXSHAh/C0W12QRvBMca3ZGy3w+VyXeiTQoMDdrPdvOnCoGJUANP0cOVrfMDXOpm7O76d95A2ZZW/BhZ2BGEEaD/JuNJNV5tf+zdp3HtTJvMlPbrvf2gWsXwBoRmCBp8GLMnc9FdSp1DdTDWmDd9C3eJtouMfXd6a1taZ3e/Jj0J+iP4Yj41vvEr11i39X3sG7KprpKFMkwiXBhpoWOxfJj8q8gkEmimH5k6l9FuFbd41oNoLduM8EhmMIGmZRBewVHh3W/jIFF/6ZNFdR7ke/Z4Sj4dEvTtHa1CHhKYNTHXEg6PijRXph02BwNj06x85Cf2ulYs/Gvvs1A0trG4jItGuZVwih5preDtJFPzpAmjMdT/hyCC3aJvKUlXXr2QpQVX+1Fb3bO9jnqB/0yDUOsjZCKLqOjLXn32rhnGzGhnZsUv6P4UiFIGUddvqccyNTF3b6Gryjg05kkvjjUoCwo2NxPIE28OcZzd+a1NdClPdVY5BN81AsC5ueuuxpEW7Y6OJXCQBC7s+8jEO8F4IAgcXmA81agJAuVTwb0Fizqk1cUqJ6q523UZ8k+LOthaP4+4WJpYOTAuWNMsJl9ZqN2HonY16riobtCwfOOr2b5VDRYn1GEKBpcuuk91D5VZtozMeeTYPRNBzlorhbXeP7UOtRxFvWXX03hoA4hyyBVmdo5JB0/8pV9Ua6m4IQ++sRbaF/XiuceRG/aF/xzOewMiy7QWQk4BM98c2qsTxsA/j5KRgLuQiYve1fPtTGgrsQ8J4LLpvJbWxuzuMMzXNVwjK42rclKsJXpOk+EHOzExGpsKhmFi58OHZ0tVbJCusxtZPSfkx7X1BweRw8/CGr94T4/A4F35zpfAl72HW5Nz83uKWMDH0UywGloH/1jpDE7XRmwCk+Cv8DsF9Ow+5lfxD5cIHq5B0ghv4oalgz1LUwudSeZkFhHnKHfZq9q5GaK7KkEX+87fZZRADI49wYmFB7H0lQ2v6AZQ7hV4D4hKXgzdfow1c7p+I6ubt9+goEgcXV5I7tDqP8p1xbyMvrE2pPPYzMwf1rrBgZ6uYHU+v8nkcJ1XqQJG5wzpDcKtk/ooZ2LJEG/mLgpqTehJrd1hxiZaIvbCjM48dPt3+m+u/aqAuMS8l7mYSgL3zxcy7/JHw4VAdk8CnOwEHdCWJ7tO/Trvg+mPZmcrepnKXF7MusNfvhWhNxylCzCGd0hXY3YrDErV6NFNUzPXmJcJDf0JraUcuzz7e9HNl0X/BHGZWmPuq6SZlIVIfHq/5EUYzC1L/VCZbcwabBGLiEwsD0vwLjWWSNdYzAifYzvL4tXw6wvBR0GA/VneRME0v6MPRGBCc78nN3+JyoNI9eRij5vqPHA5cRoeayWpu/76d9cZpDvX3LG4xaHJhUL2hXaAgkCjqSjbNHt38nytRFcI5deWInRL/NMmDB1fmuOmtcf793R3gZOOwBUuOGbE3r+i3NmdDOB42yW9mkuT6kWo+4wD8RRYv1ZOgXcpv22B4mZMbjH+M6L04HObkUHaKnaG+BLGpWrIQ/QZmt9AqLxxzAAkXXmOm4MeJdBSeaKr1iMc5myuKyDIzMHIzehVPKKMoM+SEnlp+vIGuVKyAOyPhWjxgQ4e6x1fGPfZU9pz/lXKK7xMY4AZ9ofyDwQyvJ+NxJG70j7w9nz8ZcTIUKoD2HH1sfO+6MPwaPX2eVuhYkq9oQHgQdAsK8hbgmlBEfcvIS2pvgB9k6EIx2nEUs69j9vGO5473tjpAMhQ6zPWq8w+4QwaoBshyGPyBKhpVWX7mNyDb83Oh2nsqzLM+QyUIItdqH7JzPMwsnsZYidyCZJ1fYHXJ6Hm78VmWq1hXihmO0oHrfB5f0PpDgx12T8ZTefnuXOAHcdUWFVzp0KHp9wBXu+8x6JdyFmH/5lk5ZYgrixq08eqkpcM18AzYr+hEmtl8/a7sQFO76GAOxaz0+PngYESiTQVHSJFP9yDAqsxmwGYrNGxhffgKrzknPQURl1l6Sssr4RGXdv66EVH2yqTfQqcQFpniCTiFrJfRA56nvLYrRtLLaKiwEfnqN0iNPve2O31BbSg+Dhj0SI8T6/YyzboYroHH9vV2H37KTJzuLXSMSPWvMUYe42x/ckAeeCqbSRTplgHjkikPnpyyTmh/hHFfUomxnZmQJGRk2Qw57Co32ZTTFKy6aGE9iBdcrxsCwxsywP5ljQ4hm9dM4SIwGjGWFo/+ggBoy9t2U9Iri681RpHh6d8ZfvlH5DNpQu0bF5YMXM0/Y+ubghZfXX0yZc9UXAdPR2RG2VO42Lq1cp7O1PmmNEjwjAi3CXo4jm0Ftfnj1mm/k2oEogDnU4054iA0tSDAjeduQtctdGBWf6d3zcOzlP6BqrKnMaiDxyHxlX5gIHjtP/nU3iKUuh0Oi8deRiqxFGkf88Jjm9mrHI0vAGOC0nfDTHQvpyaTldhQhDHkiWHtwZO5N/toPtWzXN0SIvIjnKMxtq+0GhU1xgZp9x/SqO3MDbvhW+TF2gAYTtlfwobxURrFAcDMQOdRlZOdNEc2zxBy57rXgKwoaUkpwXevKzou4j5Q3+ZbPXhXpKCx/mtCyqHUm5wv0hff/kOKz3KU+MIi+ozWoMHGmiJ0t2w+lkxAqYqO0ftQlrX6B6o8J+HdhLn3N9okrmYBDedlLWeGwaaILGCoYazFjrFAnbxdy0AOMqNShUhA1B056ZM3Cms+Id9uJJXEi5sf4mMPSdW+2CfhgqMd7UOZXmrbrrjCLIaUwcw1HFupMk8oM77FqiDMdCeNazHsTGV0rtj1r18e4aLRk2/txYWLBj+hiSJnmiY3wNNHlLOjwFRgd76/DWOdz1QObv68a6SI41dz5kreJ+i8F
... response truncated ...
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.1-pro',
  {
    contents: [
      {
        parts: [{ text: 'Write a short story opening about a detective finding an unusual clue.' }],
        role: 'user',
      },
    ],
    generationConfig: { maxOutputTokens: 4096, temperature: 0.8 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-pro",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a short story opening about a detective finding an unusual clue."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 4096,
      "temperature": 0.8
    }
  }
}'
```

```
Detective Elias Vance didn’t mind blood; it was the absolute absence of it that set his teeth on edge. 

The penthouse apartment of billionaire tech mogul Marcus Sterling was a monument to sterile minimalism—white marble, white leather, glass. Even Sterling himself, currently lying supine in the center of the sunken living room, looked less like a corpse and more like a carefully placed art installation. No visible wounds. No signs of struggle. Just a dead man in a two-thousand-dollar silk robe, staring blankly at the vaulted ceiling. 

The forensics team was buzzing around the perimeter, dusting glass and bagging the obvious: the half-empty crystal tumbler, the silk slippers, the victim's unlocked phone. Vance ignored them. He operated on the principle that killers who left clean scenes always overcompensated. They focused so hard on the macro that they forgot the micro. 

He dropped to his knees, ignoring the sharp protest in his lower back, and brought his face inches from the pristine, white rug. He began his crawl, moving in tight, methodical spirals outward from the body. 

Ten minutes in, he found it. 

It was tucked just beneath the shadow of a floating glass coffee table, nearly invisible against the thick pile of the rug. Vance pulled a pair of bamboo tweezers and a small evidence bag from his trench coat pocket. With practiced care, he pinched the object and lifted it into the harsh glare of the tactical lights.

It was a walnut shell. 

Vance frowned. A discarded nutshell in an apartment that smelled entirely of ozone and expensive bleach was odd, but not Earth-shattering. Then, he noticed the seam. The shell had been sliced perfectly in half and hinged with a piece of brass wire so thin it looked like a golden hair. 

Using the tip of his pen, Vance nudged the top half of the shell open. 

He stopped breathing. He fumbled in his pocket for his jeweler's loupe, jammed it into his right eye, and leaned in close. 

Inside the hollowed-out walnut was a diorama. It was carved from what looked like ivory and painted with a single-hair brush. It was a perfect, impossibly detailed replica of the penthouse living room. There was the glass table. There was the white leather sofa. 

And there, in the center of the tiny, carved floor, was a minuscule figure wearing a silk robe, lying dead on its back. 

But that wasn't what made the hair on Vance’s arms stand up. Standing over the tiny, dead figure in the walnut shell was another carving. It was a man in a trench coat, on his hands and knees, holding a magnifying glass to his eye. 

Vance slowly lowered the shell, the silence of the sterile room suddenly feeling very heavy, and looked up at the empty ceiling. They weren't just hunting a killer. They were dealing with an audience.
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Detective Elias Vance didn’t mind blood; it was the absolute absence of it that set his teeth on edge. \n\nThe penthouse apartment of billionaire tech mogul Marcus Sterling was a monument to sterile minimalism—white marble, white leather, glass. Even Sterling himself, currently lying supine in the center of the sunken living room, looked less like a corpse and more like a carefully placed art installation. No visible wounds. No signs of struggle. Just a dead man in a two-thousand-dollar silk robe, staring blankly at the vaulted ceiling. \n\nThe forensics team was buzzing around the perimeter, dusting glass and bagging the obvious: the half-empty crystal tumbler, the silk slippers, the victim's unlocked phone. Vance ignored them. He operated on the principle that killers who left clean scenes always overcompensated. They focused so hard on the macro that they forgot the micro. \n\nHe dropped to his knees, ignoring the sharp protest in his lower back, and brought his face inches from the pristine, white rug. He began his crawl, moving in tight, methodical spirals outward from the body. \n\nTen minutes in, he found it. \n\nIt was tucked just beneath the shadow of a floating glass coffee table, nearly invisible against the thick pile of the rug. Vance pulled a pair of bamboo tweezers and a small evidence bag from his trench coat pocket. With practiced care, he pinched the object and lifted it into the harsh glare of the tactical lights.\n\nIt was a walnut shell. \n\nVance frowned. A discarded nutshell in an apartment that smelled entirely of ozone and expensive bleach was odd, but not Earth-shattering. Then, he noticed the seam. The shell had been sliced perfectly in half and hinged with a piece of brass wire so thin it looked like a golden hair. \n\nUsing the tip of his pen, Vance nudged the top half of the shell open. \n\nHe stopped breathing. He fumbled in his pocket for his jeweler's loupe, jammed it into his right eye, and leaned in close. \n\nInside the hollowed-out walnut was a diorama. It was carved from what looked like ivory and painted with a single-hair brush. It was a perfect, impossibly detailed replica of the penthouse living room. There was the glass table. There was the white leather sofa. \n\nAnd there, in the center of the tiny, carved floor, was a minuscule figure wearing a silk robe, lying dead on its back. \n\nBut that wasn't what made the hair on Vance’s arms stand up. Standing over the tiny, dead figure in the walnut shell was another carving. It was a man in a trench coat, on his hands and knees, holding a magnifying glass to his eye. \n\nVance slowly lowered the shell, the silence of the sterile room suddenly feeling very heavy, and looked up at the empty ceiling. They weren't just hunting a killer. They were dealing with an audience.",
            "thoughtSignature": "AY89a1/nJwqLvTZRX5LPVcjnU/V3AI3ulS85hu8rnCwOMBRa08DV5rtf9Xh2XRVLyqXcvDcBhl00FbpS6tOl92tDxHZ/T+EtwFWnPlPpaC4xdzGdGOjlallnYKcY/rSxCwhsjuGtowqkX8Y5yZMgTpVi7wgwZ5BWiFtcn+mopaKRYqXDbi/CwXq7w06h/R+2ate5pRK43UhoT8FBINF3sGeAwpSrObNR+6xO/7J9E2F7RkXQ+mcVR0zfnMZVBeM/ICH4Mtuj+tEo+iDLc4g/6J2T+Z8baZuF9+hOXOTc+Zvgf/a3pWqNL77BdWpF09VnfiQEs/7gTTXfWa3dtxjldjV4bH142KZ0ihKOH33Q2M3QRkhFdDcQfRIZrklEO+vFr7lzEmN6QxfbezNX8m1BKkLJXZO0TXDUo6UA1z7z6vtFSfLxNIplo55or8Umyj1fK82dUACzltCga5FFDshJqTAofKqAg1eno9EBHihC0ZWCbdvfFXTzOyGMqep0wH5z5TlvRK5ezZWONT9Is/gNbVOdwNr4EJAM7brrCrVbn0akEah1wwRog0zPouUtxTkEbyyoGOthOtHZE2As5WRIuNpoY9qiFaYKVJXRiDImgpFn32L81R40jOKxD0W90rHIG8pKBAyAXKPUsusPKXrcq8PKFeAyUxDdrPw6BoMFODpUfSyhfN5Gtz2thhzUC1TiQa9Ic6oEW2VuhY7dPidYzF3jjvtkeUeSUH3tTQi8Sv16lw+tmmXk8CLGmYOGW41HlHg13pegG+bf3i9uK1/sy15hThinj7FU0RfE4ucubrOcRkZOA/MzCxVqIE0jXOgowCPn6NKHuL4Ij98r8xpPlQB/X8IvvXTDh7QegE0uTUoWMGmUzNgBlwifw0LBndYvj+suksjXSE2E+JDxgrccsZltnP1uohZ2b8YbGslASYHU0hAiAcdvcojmqx1Tu3jegtZGdF2Zi+vT/g6fNR4kXbwQWA/Sn9hs72zS21voaXKeZqtr02OTgGek+zOlTykAdklhVBt9c9qghLTnuYOEpneaTn8rBxB9zE4rS2k8BT+d96aKfNHtnKHRWgdcBnMX8yuEwmGCF/U4YY5kXEUctBYiBue7OGr3UNxsE59ub4FlQRa4Y/rdZYLc+l/v0aRKYuRD+kKHla5b9HB53KOIxrD1zvhFxErAqqVL7oFgOsFmWzsetv8wID/6h7SDi0Hrc0a4NkkkqfvVGc7wK4JbuMQKOnh938uZaTbpn4s1LpHlnIiwpT5OGk46X2pL8ePXeIjxHUL/VJTMpYWtlgz0krQlkqswt6V7RF2VP/SS41PP0suWUPTpgNEEl5QpfsTl5gXvrYhag2t0ENY6/XiYGeZ1UsQttoX0uW7Dyo3/BEFzZXgULi66TGy1jEuep6RDg38fXs3OHBrqiPyVJudj5yKFe8jz5N6FDzg4wCPSl2dRjxG5eJzlzBC2/5n9z/bn58JKOodnbGl/yrF40daJR1WLwJ7W/vLrQkZBUsh5HSn66LpSB1iRAfKv2ZPlvcMV4raJgfkPpVaQHVzMhZVN9+if8sEDnKIYu/Apm2VYMCzkr6hjD9RwXLHUODTghh1ZpbIZibcEQMMYcU0evKJfAyV7xIPIj/Kev5Daxx5GR5NH+5vpiyx4imKgBZRao5S3YeKluT+d60O5m90S7nyrZEUYeLr7qiKYjTmYtt8U3xZ0ReL7Fk312o0fDgFcwcEZ42gA3Bkh5yrL7XQdGqWkaOWwFZk7hKrk8rz4iD4CXNh1XDtR8DVTia0pWv6ofrAEqTtbwnhVQL7TvEngUkDFHofVSuh/6du+zSpmGloJjk7k84EA0ej6z22hIhV/pRyllDsieJkwtJRaOoyuGuiN12OVUw7qb77z+9UtzlFCIPIPO/ctOt4PpSCgJW+/v6OH5CBOAxx36CDN8e8guMnbhaknFH9WU79rQQuCbpJPKNPN1XvV6lvZZ4b39EEG4EPs1TtA2KsWarSRBXFlHpjBKweYsMv4K4pbByIg23qHi+K4Cjgpc/T3bSAXNJO7hi63Ezu9tNmfM0xwTlJ51N5lhjGtVEUkPp7P+y61dg+ezNk06v5NLpP+sN7zs3WIac5nvZ2Xk1nuRGTJlr2SZUP0veGeZYyOA/FoIi2mHW7mGBybMRb7WBufbWwSiia2ls/Ufl+APC/GtN1oOdiNpS/Ktmi+wNMpqvPL97dFd4aJ48uMG0Qp4wIvqjL9kALTpkYJuZM7rloOU3vKMQ9lXTukc6VwxRLZoHC1tMZ612wvR7pGhSxFULTwxtn+Mqd3T77iOnb76vKKC0nKoBNtYFcASP5+VQf9PEnAiNje9Vztzhj2t9FIntk0mMXL9TXAoJ+FtHavesDI5fiqrtWwgmOQuqQUpr02ZPByEhurvUHN+CDPkHKibPjckTaH/WCWmuDAjA+zU3FOiDR532hbN7dqfLR47caW/znEEwe8+e5urjWg9yWN0KCeAQai7x4rCeftU572oTQ2RsB6VAulfi27l+Jk3+dA6ZdMRZYT7U5ga7+pB8gHkyP8gRBy+Q2eekeGU0AZrPy4LBgf6W/UC7RgqRaXzmKooGLwYmXLqQd+OcYJ3mHY3PF5s8pmYMz1+TfFXTiTXtcBJdHc5nSp4tI3yfbQPiprTpt/YkMaRpRDgsr1mtUQr+FR6lMhxrGCu3boDdNTnQIt2ILJPn95RSQrwWW6+2DOy3ZZDWrMOsvdK34aK/+4KSNxE5csE2VQ0bF18sSmVEezPUQT5NbDAAIdQPSfSHi601rqYlgn3hDf/FGcQdegd2NRbvlTzQUAi2T4Ypo0abC2uZGqhUjNKGmnjxAbuJOxWUJuONIR7oYMiqZn64VY4FAvDvkisTx44p1S8rP2ZpgzramX3Ts67fxRWTXCr+cT5nSJdZMdqrx0Lozr+uAouG96cfCs5nt3bPejNygeyNWHKxqvfMid3q0G4mJYguxpYlXQLvSXfYmAkJ3/j2pXiliZKRpaG/J8r8WMO+rRi5LUizmqXluNLEZcYXctNqQyq8GuJ3gtIeVgviO2fil9R/C15zKTYU+ZgWmykKUVnU1tLMKSUkqaVH87jlWXVn6pr9tixx9HT7vY64UL2hw+5WSfZoNLG0Pz18H99ox7YdY8GzmdB8UQeq+Emb887jMTCAFw/Nx7jLscptgeljgEKyf6dqVbQkgZ0KwNMDq0DPF2cHKaAQg8ctwSXnYO6xtYgS24rWNV0upskSBiLWsIXSEsRuNf/7eTSpcxIP7F5G7Kzq9Xz92eaAgwQW+LybXaUAeAVAe1CUGJMhGQU5VVn0n4/mq+HYzTWHux+MhlrtH6MXX6NlX6PDsBWrUFRKHFt/7LeiZzEiAFegNxix0atnWbzqWqEjFZgE+tp1S1ahoRg1kNd5kAD/NM1mJi3/zfCTf+GJAgFt8YNpCG+NtFPkFItgJEMk5ZA5eauRSWVyLYIzLZxTtAfS+YcofJQK3HmNuiny2iGNFhIxxFtHDXW/2sBXXuVFTH82jS+4bhN4PzLS4aGYCtqF3MabevwMthAMD5c7MP2AoszYcVJeOYh5vNjfIqdXZCviy095UWYHGxuvYKWbATO1LXhJ4HwI7cCysZZFbnrZSoPcbGGoS4uasD0GMnP6Emv9iD9Yom9FAQGYAO85bfMiFkpMIe1bgW52DFqmqvH+lkMkldNZVubKIFrHjrPdwNIM1BTJgDLjptmBFBNJ8Zpp001Mq44JY+wU8Bpfi6i8sBPDb2cSBl4nrs/yrHp7Oe9dbCAGqrTMNP8dzinkwtEHToeSQDAJjyUaVOENDAh4irrtk6c3FaxWYfgxC3b1Zxngafp2mGj/NOZfCWEADeIOgjC4mW7f0MyYYFB/tmu4N3MMHaDXlXaFm1DOTxfHtIqvWVROH7D00pS2Gb/GJGs/UzaQVqLZ2l2XKJCRvNeVPm81oGuIJog5mw+C92AyzZkbE9p3VtHb7lKAbnokGv2lz+4V0nW8Ex4ZVj6L365I27MObCg5p8LG2fnZEIKe9QOrC2EnRpE1wUSarxg4gc/hKoYax/mMctpMnynZ7pWBst0+cdFhfwcf+xeBlb8R1gBXo8lpI5U0V3Bv0K1rTthhYHRRRPHwj3cYZDY7qOy15mVl+9HYDQLVstR0Gwyh6UblFORQputgCNIzgHZoXAyeh+xRW1qTFvyYtEjTvHSr8N2Yo/J0nBdbvEwl613UZS9FgLzuhg07JnWGCuOz67Zni6d6qCYM1qORQUB+bX/6clV/OtIIVkLcoUAuykEIMi5snxszzcCUOKGApfvec2bW9I9LCtRfWHLT+AvmiKqK4P2wwtQEg2MK5lWyn4y+5WpB4fd7cIm9Sfr66lDtfS9IsBeySzjd0rAxriVk4Bs7DTn1w6XziUNDs27bbseJgDKhv6j4Ph9sJeimHwWDt2fVQdSVUU1wtes7+LrTJO4GdqsqIF1F9kTHZrKZgqiaAqzzCzZcsOoVQZhjG7fOdWNIsa82Jg78+3ZtdIuUy2qlcytwuDG6fQsw56JzecAnXabg1EClmBJyfpVWbfEuPgr74HF2aNGHE9bf1FvgLXvP7sqNP/ldNilqd3EZQhGOaX3uTbsw/4rY7RklIEjsLiY7GxZoI0OfwNaJqxeZN1qXfzosn7WRJlpRLkJ72ThXhTPvxZC68p+knf2nxNqVcdrdmHR5/k59o2ByMaHi6tGDjJV3VQ/TTsqkQk/1xjZVQTltYI8/ChM1xLMJNNrAnTUTChqCw9ZqsJpKOuKKTEbXayOunQVV9zaiI2dwjoGZCdid0r7nsPNPalGRxOzGkdvjtuSA1dQm2MrcSI5/cbKRRi1PGT+4yehB4zk0mD4WEy2LhuLbS08sX7vlHnlsINgg+8JDQYAcT56HzJpiaKcAnb/Igriw00VZPYkXAQwcmku5HsPiW3trUaqd41CIHezNrVhAehjFR/eMRpZ/NX0qH/3s8hnQ/a28zIFmzePqrk+FBdqf/Vv+HCQCkfnj9sx9BLPu/eryjXABheYcz6TUegt8wk
... response truncated ...
```

</details>

## Parameters

Schema variant

Generate ContentChat Completions

▶contents\[]

`array`required

▶systemInstruction{}

`object`

▶generationConfig{}

`object`

▶safetySettings\[]

`array`

▶tools\[]

`array`

toolConfig

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶candidates\[]

`array`

▶usageMetadata{}

`object`

modelVersion

`string`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.1-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.1-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.1-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.1-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.1-pro/#page","headline":"Gemini 3.1 Pro","description":"Google's most intelligent Gemini model with improved reasoning, a medium thinking level, and a 1M token context window.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.1-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Gemini 3.5 Flash is Google's fast multimodal model with frontier intelligence, superior search, and grounding capabilities.
title: Gemini 3.5 Flash
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 3.5 Flash

Text Generation • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-3.5-flash`

- Third-party

Gemini 3.5 Flash is Google's fast multimodal model with frontier intelligence, superior search, and grounding capabilities.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,048,576 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/gemini/) |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input <=200k (per 1M)$1.50</li><li>Cached input <=200k (per 1M)$0.15</li><li>Output <=200k (per 1M)$9.00</li><li>Input >200k (per 1M)$1.50</li><li>Cached input >200k (per 1M)$0.15</li><li>Output >200k (per 1M)$9.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-3.5-flash',
  { contents: [{ parts: [{ text: 'What are the three laws of thermodynamics?' }], role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.5-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the three laws of thermodynamics?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
While there are actually **four** fundamental laws of thermodynamics, they are numbered from Zero to Three. 

Here are the **Three Laws of Thermodynamics** (traditionally numbered 1, 2, and 3), followed by the "Zeroth" law which was added later.

---

### 1. The First Law: The Law of Conservation of Energy
This law states that **energy cannot be created or destroyed; it can only change forms.** The total amount of energy in an isolated system remains constant.

*   **In simple terms:** You cannot get energy from nothing. If a system does work or releases heat, it must lose an equivalent amount of internal energy.
*   **Example:** A car engine converts the chemical energy of gasoline into mechanical energy (movement) and thermal energy (heat). No energy is lost; it just changes form.

### 2. The Second Law: The Law of Entropy
This law states that **the total entropy (a measure of disorder or randomness) of an isolated system will always increase over time.** It also establishes that heat flows naturally from hotter objects to colder objects, never the reverse.

*   **In simple terms:** Things naturally progress from order to disorder. Natural processes are irreversible.
*   **Example:** If you drop a hot cup of coffee, the heat disperses into the cooler room. The room gets slightly warmer, but that heat will never spontaneously concentrate back into the coffee cup to make it hot again.

### 3. The Third Law: The Law of Absolute Zero
This law states that **as the temperature of a system approaches absolute zero (0 Kelvin, or -273.15°C / -459.67°F), the entropy of the system approaches a constant minimum.** For a perfect crystal, entropy becomes exactly zero at absolute zero.

*   **In simple terms:** It is impossible to cool any system down to absolute zero in a finite number of steps, because as you get closer, it becomes infinitely harder to remove the remaining heat. At absolute zero, all molecular motion stops.
*   **Example:** Scientists can get objects incredibly close to absolute zero (within billionths of a degree), but they can never reach absolute zero because some heat will always leak back in.

---

### *The "Bonus" Law: The Zeroth Law (Thermal Equilibrium)*
Scientists realized *after* the First and Second laws were established that a more fundamental law was needed to define temperature. Rather than renumbering the existing laws, they called it the **Zeroth Law**.

*   **What it states:** If System A is in thermal equilibrium with System B, and System B is in thermal equilibrium with System C, then System A is in thermal equilibrium with System C.
*   **In simple terms:** This is the law that makes thermometers work. If two objects are the same temperature as a third object, they are the same temperature as each other.

---

### The Famous "Humorous" Summary
Physicists often summarize the laws of thermodynamics as a game you cannot win:
*   **First Law:** You can't win. (You can't get more energy out than you put in).
*   **Second Law:** You can't break even. (You can't even get back all the energy you put in; some is always wasted as heat/entropy).
*   **Third Law:** You can't get out of the game. (You can't reach absolute zero to stop the process entirely).
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "While there are actually **four** fundamental laws of thermodynamics, they are numbered from Zero to Three. \n\nHere are the **Three Laws of Thermodynamics** (traditionally numbered 1, 2, and 3), followed by the \"Zeroth\" law which was added later.\n\n---\n\n### 1. The First Law: The Law of Conservation of Energy\nThis law states that **energy cannot be created or destroyed; it can only change forms.** The total amount of energy in an isolated system remains constant.\n\n*   **In simple terms:** You cannot get energy from nothing. If a system does work or releases heat, it must lose an equivalent amount of internal energy.\n*   **Example:** A car engine converts the chemical energy of gasoline into mechanical energy (movement) and thermal energy (heat). No energy is lost; it just changes form.\n\n### 2. The Second Law: The Law of Entropy\nThis law states that **the total entropy (a measure of disorder or randomness) of an isolated system will always increase over time.** It also establishes that heat flows naturally from hotter objects to colder objects, never the reverse.\n\n*   **In simple terms:** Things naturally progress from order to disorder. Natural processes are irreversible.\n*   **Example:** If you drop a hot cup of coffee, the heat disperses into the cooler room. The room gets slightly warmer, but that heat will never spontaneously concentrate back into the coffee cup to make it hot again.\n\n### 3. The Third Law: The Law of Absolute Zero\nThis law states that **as the temperature of a system approaches absolute zero (0 Kelvin, or -273.15°C / -459.67°F), the entropy of the system approaches a constant minimum.** For a perfect crystal, entropy becomes exactly zero at absolute zero.\n\n*   **In simple terms:** It is impossible to cool any system down to absolute zero in a finite number of steps, because as you get closer, it becomes infinitely harder to remove the remaining heat. At absolute zero, all molecular motion stops.\n*   **Example:** Scientists can get objects incredibly close to absolute zero (within billionths of a degree), but they can never reach absolute zero because some heat will always leak back in.\n\n---\n\n### *The \"Bonus\" Law: The Zeroth Law (Thermal Equilibrium)*\nScientists realized *after* the First and Second laws were established that a more fundamental law was needed to define temperature. Rather than renumbering the existing laws, they called it the **Zeroth Law**.\n\n*   **What it states:** If System A is in thermal equilibrium with System B, and System B is in thermal equilibrium with System C, then System A is in thermal equilibrium with System C.\n*   **In simple terms:** This is the law that makes thermometers work. If two objects are the same temperature as a third object, they are the same temperature as each other.\n\n---\n\n### The Famous \"Humorous\" Summary\nPhysicists often summarize the laws of thermodynamics as a game you cannot win:\n*   **First Law:** You can't win. (You can't get more energy out than you put in).\n*   **Second Law:** You can't break even. (You can't even get back all the energy you put in; some is always wasted as heat/entropy).\n*   **Third Law:** You can't get out of the game. (You can't reach absolute zero to stop the process entirely).",
            "thoughtSignature": "AY89a1+rHsoYmr4zo13WFFuONc7LS9+Qb629kRUXpef5oP+4bGGaSf2xmaJWXalx2O5uR+EQFZlHljF5gb6Mn31zgECDUxQgGiKp5rAhsIc+IBnPfJ6QbH6qUqV5n7Iaukzos7PeLX5J7xiaY9dMO8MaNKvesuZhRiJcwDGMI92bT/b0V6p9yl7BCknjSN3jZli4jyb5ddybaUkxzXwEFfrq+dJY0hgEDxcqfVRzm+0hoS6P0TmZoQZnOOpEAnCFHjx7RoT2fNts9g+K2fRsI6s610dgVG45iLA98Q+X6Dm9KFdz1BEssA8eSxvI8/DQ80rIukWVtXObmSF8t7ih/4g3wqxUxWPCIsX+YbJzFQSOGxTu0jsb0ylYlsMo6FAAPHT6bQuvZomAzYCNM/aV5d+QuEjMwOxK+bzis9P1KOruCtQXDYLLn0njcnLYr9oue3VpePlVsdWE/xWctPvHMfFkEOLVZtBusfmpCog23D/FT31TRaXJJ5uPX1ehodosef9/IbLNSsNblj7rh9GY9RutafTW6tyzejedlmf4JGUUO6yLtQJ9gvhTGGPgkIsOrZyk9L0WFKLspIvckHH1ncvLPmD6acPPlNKbGpP7t27zpqpI3rA5emVHCB028swoklpCpkCbmq22nvfa+6Wxt2SpiIloQ6+gYtEQO/duPatUaIl171g6UVWkoi1ScADrFuNcnXjsug0Oka7sC4TT2dxVpZFyuokOAZmqXygHTJuAEcy5b6UgTOynUgB/CUNpixwewyDYFvmalRqyCeyHHHjStvtlrC5qW/nNWfP2ndZfU/FLK2RF/H1kytg0M8gqAiFLbFU9Of1/dKtGeUixnRmMdLJ1+SuBSiIPkRmI+1H1ihl1BETEhzU+G8j/wa1rCEjxxOLqjNXQWNkrT46ccczJZW4APNvpM5KYo9PgFFod2qSW5zCqsby+bCNunvCIvVH5nSk+JuAH7PD99hz/NIIyR/PNER7qW+sbHU5qEorIw5V4jfPzwu9/z48aZmiHvxVVmHM5LypBa9ZnRckcoNNf04ygmHPpy8ZpMNY/HphixsOymDebjPrGKcjfcuBECJ+yaFVBwK6Q8aQ4adm3CTmwfeBr6x7sj8MfthWsk2LDC3/JQ3vqLTcrzNJf4KsHGlDwTvpDJUKJOdtjGqQJGaPS+Etcrq8ORD/7F9FP4U51sYnCuXvX3Pne3ka7ZwXQlSa+6uH7tdAZIkZC42u+RB1VisNzYp6HL8UQDSzb/LZBYqXljS9jDE6lV1+hmiPIpkhY/URsih6Hb3VnfXpneri3zcOyhlb0YFh9zP8goGwxYQ9jDWra1HGh8n6yarYyn3A/EfuSOgLQlpZ6+G6jW71CZl8j0/ryIkAqSQIS+RkCCSD7hZbEdv4IyS8SF9dgDDTLx85U6XDhze3cPOPVfSpCHmCCYc8sZqbXBBuTh2eZU9gpbY1qFBD/QgSEYYV+XRsHvQECQ2FSZG+s1QPpdrLvrC5VpPR7Q4mgsgR4TQCYRFZ4JcYpqq+E/to7jQYMqzWYU267/crkffqXi0hGz89fasvqcNT0cZUS2BGMzFVNZaXUvMK4LQPkOtkZBtIXjIKMf/oT/EmhId2J2FYLq1y3qjJkvdQs/TZwQDP140YNgqv/k+oCP0Yv+kRARI4qVJeexLhqcdJYRN+eBt6s0TQbstGC3YgY7Cij8HtrFJ1ISXfUMPNfgfrYWp+F1Lx1BTCOhfXBzYGOaGCAtXV2kE0M7BRS/pjxO5t6SSC21WCP3EITpn554eUiwrVH9qGYu152c+jnxJw04ZNQT56Hl3VQeHHWojOi3eRLZoP9AYD7nFw3pTdnSQswnHeC0e8o4egHcODWRKg45BMM8PZNKsZmqPDtdJd1UK5ck91T0gRZcTWYE0GEPO3QGfa+DXFQSUqrLt3dpwNomEQztj/gobeyNx46LF6ywbNTM1dLdSHceQmYM7iu0DcrPxLtsumr/Z5LgxNkxqL4gt9jIJjQYKE6RKgGjiP9f/mLDx64Lr0NXLqS1YloGH9oW0R18L32c8bJwmocO6/m3nHl/KQ7lvtNE1kpLwxbvOzNvnBzU3UpGMgzfCavF+pyIFSMyDUGRwoQkXiUR8sKCxbKgAoQp1I/ttqbeOGulK01I0UNDoZ1vEFZ+QRDaFaCQdWemFF0Ffv8Q8oL6B2f10iFmBHtadnVD/wuRjL1vd0RpiNVtrwseh9vflPA09u66bB2npOg94srxNQcDuKIN5N94eXoObc++R17m6L4L78MF5wE7DwV20mQGTlveN6K6zPEr2rArXTziwFPaXGTCy7Kc0WNOCMylLVkVZdi7WyDmlQteR3qOwZwbOK8qpHa/75bHTyKuul+Qzq/Jc/SZSkCCOZxHjm3X2UKndo95cfMcp+q5AwA0FmISeIb79AXHmfQrr44G9D61Xu8sNOD6zki5oFEGYRrcpC6+gAv1d9KRain/gqZjJ84DjEMbIwIVWE/M7gaMkIEbGBzCNm5EMdc3BATHbEgzBjAgtCvYhP+a1cqgKvWMvu/3L5mg1MAEzlLKV9FGt4l45zDASXiJHb12xDkz6gDvzd4yES0NytklOlI8MGVkPEK1bJZRrhszoNO9UOqf0XVZYe0KijdlCTDG6REeNlQYx3SU8fFe/EsaxL1Xwu2GoBhgNuniByQZYL9hTJNmoSQdWVkp9Kdu+ff9HgRztXo5kXCUVMRErjmY54NRP/v1wVq6IPW43AY73s7hyvqZc9u11vqWjCN4BYjQJbC7l5tKFiYw2KuTDD7Bl5Gw5fSJJXb/GYixRqXXQDqqjyIRjy0YE0njjryuQOWwUXXioDLw1ejANKgsSY9sP/iWPp21Cbl0je5HdBpjT5wIv/Q+AibU+I1Q/bomZE0LJXXCJZ+68J78FG/lLHMZ9dlcEj5+PgfzZALWD6AXxPMBxe1j75RWj7+PaYZqABM5IpTuTr0pFHeAM3rEIhQo6VR3XtA3o+iQgUIoBdEOSJXbAVbIFDVQy9w5RAC/2NYzqcwlnP5P4quo6X4t/ZtATn3e/hY+H2J85nwE/cQap9drfZWo/WIUUXj0TVxOQ9DQeA11xmkQTmvve2vkWZbPFDd2fVGalnxLJx33AefwueoNvYh6++lyIMhWeTkCgt+eKTefZPk8cW/zNnGNJuTm8q9LUyT7oU0HuRSCdUbxJD+Lbb4oiREd6Hhm2vWM88z2bNJ0bl+/sHc+jksFuAOsXT4eK2kjzm9FmR90uAjP05d2/0Ii2A+Vli0DGezMVluvZ1ku6+Qnul/vdlPR7HsEypr3wUg/aAYrf37dT+f/bmSD3n6IkwnzeJu5K21Jy1cYC5Bczbl+xtxg00eSqryy76eUzb4gFYEBu/JuTHleicF/9IRSJgBXvmIeKB2YnUtTDtRg5LklPwaiT2GP83uTmCaU8rINZCJwzblTbKgxZw4i/ufMGfBzDaPJ8regwhUv20tPkthtDK2zz+kig8lVew22JHEEyAF0eYECoZ4ob6K+h2XnV3/+RIoplfW1+Oe9RiE1YqyoJs3y7r+nBV4uyC7E+rBBl4+sbSrbCnmn0eqI3DCC5plz3vS6Z0URWF0PS9ZszqZ0enhbnB75Kt6QzxWoo8k/6rq7dioUhjkzQpOycatWQS/riPefMIcrQp4wPT3jNtakph1B7czDHzTFMC/fPZLEUpMchVV+eyVdkAN6uNXjirK8k1rHvV5bPJFuDLJHWb380sVU+EtT6PxxRszrdgGvwDnWgpTT9HeQ4uYLLoPnQ8BckO5NmVZYA+ACPhEQgfGxLFFi9d6V0PsxlIB/Z7SHCSpTC1zgXL6aVfuy/jbmcFQvv7kDZviNCIZVu/dZ5eTS65SS215XZguMb2fQMofvOcfnMzWD2YDe+GQILg+k6O4qtsS9SKBfVh4CN6xW49TNFErUBCOlqcRDNwgIkeKubQlCilbgXxSJWSBITcB9HvupvCVgH+n0oWVvVIBuK21KMLadtyNKjLbfbGcdKyGE0FlVzdKFBZ7/QrGLo+ZZDwlrVu6bNR5MeCANiUInJ2EAQVyvVZTTEAX9QPauAJYxUpdzRyhie3uhfIGbDujMOsHcyoYBMAq6K6ZhlqHEzssBOKoGK+hI3fuHlCrzuLWtJnIk+6IZTrdRE7xojcXmttSfb2+j93QbD00sJbCBdyO9GtjO4gXY8osSfJRgzIvBd71EuLw8CAIfBPMGriT0o/xe7qgbkNUJJwMwFCP/6JBMlz+GXDzQPaakFBKFoUcbagujuB3hjMgj7H9aG5/bCZ1RZDqSEyAst7dVzLOv4R7P1x+7VYVH/E2bY00XYuwOxqFxCoiQdtodURHOSIPUsG2K/DYIFHQthdQCPRy/64G5A48KFyCDlZjdxJtkr6AgLOt+NA6QYYcrpjhQ1wKpbeM2p18i3gj8WAM3246QA3BDJXs4izLeNc5KG34LagEzEkL+FKaevRThg4Gkwx14WaJRGquDb8BZz80G7HfTvo19ZjlJLBBhr31lneKFIQmkZtR/qrSk5g7zW7riDmbEO9pWCRslXSjB/gER0JiCif76X
... response truncated ...
```

## Examples

<details>

<summary>**With System Instruction** — Using a system instruction to set context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.5-flash',
  {
    contents: [{ parts: [{ text: 'How do I read a JSON file in Python?' }], role: 'user' }],
    generationConfig: { temperature: 0.3 },
    systemInstruction: {
      parts: [{ text: 'You are a helpful coding assistant specializing in Python.' }],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.5-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "How do I read a JSON file in Python?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "temperature": 0.3
    },
    "systemInstruction": {
      "parts": [
        {
          "text": "You are a helpful coding assistant specializing in Python."
        }
      ]
    }
  }
}'
```

````
To read a JSON file in Python, you should use the built-in `json` module. 

Here is the standard and most secure way to do it using a `with` statement (which ensures the file is properly closed after reading):

### The Standard Method

```python
import json

# Open the JSON file and load its contents
with open("data.json", "r", encoding="utf-8") as file:
    data = json.load(file)

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

### How it works:
1. **`import json`**: Imports Python's built-in JSON library.
2. **`with open(...)`**: Opens the file. 
   * `"r"` means open in **read** mode.
   * `encoding='utf-8'` is highly recommended to prevent errors with special characters (like emojis or accented letters).
3. **`json.load(file)`**: Reads the file and converts the JSON data into a Python dictionary or list.

---

### Other Common Scenarios

#### 1. Reading a JSON String (not a file)
If you already have the JSON data as a string in your code, use `json.loads()` (the "s" stands for **string**):

```python
import json

json_string = '{"name": "Alice", "age": 30}'

# Parse the string
data = json.loads(json_string)
print(data["name"])  # Output: Alice
```

#### 2. Reading JSON with Pandas (for Data Science)
If you are doing data analysis and want to load the JSON directly into a DataFrame, you can use the `pandas` library:

```python
import pandas as pd

# Load JSON into a DataFrame
df = pd.read_json("data.json")
print(df.head())
```
````

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "To read a JSON file in Python, you should use the built-in `json` module. \n\nHere is the standard and most secure way to do it using a `with` statement (which ensures the file is properly closed after reading):\n\n### The Standard Method\n\n```python\nimport json\n\n# Open the JSON file and load its contents\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as file:\n    data = json.load(file)\n\n# Now 'data' is a Python dictionary (or list, depending on your JSON structure)\nprint(data)\n```\n\n### How it works:\n1. **`import json`**: Imports Python's built-in JSON library.\n2. **`with open(...)`**: Opens the file. \n   * `\"r\"` means open in **read** mode.\n   * `encoding='utf-8'` is highly recommended to prevent errors with special characters (like emojis or accented letters).\n3. **`json.load(file)`**: Reads the file and converts the JSON data into a Python dictionary or list.\n\n---\n\n### Other Common Scenarios\n\n#### 1. Reading a JSON String (not a file)\nIf you already have the JSON data as a string in your code, use `json.loads()` (the \"s\" stands for **string**):\n\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\n\n# Parse the string\ndata = json.loads(json_string)\nprint(data[\"name\"])  # Output: Alice\n```\n\n#### 2. Reading JSON with Pandas (for Data Science)\nIf you are doing data analysis and want to load the JSON directly into a DataFrame, you can use the `pandas` library:\n\n```python\nimport pandas as pd\n\n# Load JSON into a DataFrame\ndf = pd.read_json(\"data.json\")\nprint(df.head())\n```",
            "thoughtSignature": "AY89a18qMqRbC6jUdfpqPMJZFOdHxrMWgA80pVwEdCki3rzJAus2ozHxO+yjLaoSA0yMkUGjZIeuJjMR2AvbplB6Q8GEFG3rYwhWKw0YF1tItgJuVrURI9LM62wgyKWDVXFYi1raQZnE4HLr9x1IKBMonDuxQS3rymVnhdyqXUIScsKL1CEe6WC6w2hCByU3G/eTgP1WK9zac25HC1zZztXn2b2sCdJ7sRVuC4Pi/SdNW2THy1gwTFg7GxGU3VkjZ5075bAEgM+2dp9F5DIrqWSBlKXEhZuxbIvO0Gokh1t7eWRqOFC3kvpoXT6Kh994DH9OPL2JBcZpB6QxCLQ4AF3KPTFJVwOqWoko0qQQGzlS6Y7I2ceb2pyOheIEhtlhGI79v/ArYLYf+lLkQSBD0tL+CmpUqImmLLrW0x9QvVDvIADFEW3uPkIz/uSxfKqnRqNpIgYVYlFzntzUqPN5dl4LiWKNka13WgWPxXJ8zroo4M06xnQTbj1Qgw/qyYfqeKdHXsM9FQx5xzs4q/UGPEl2zpu60JrlnewJpXe2JqZGyU5eg7ePT4dlFux1RVxl/1DNckGUkZRNf1BB3BUPQ5JpVlBCp1sx4qBXJ/LXVWImNtJsU7mduM1ZJ6LfRim3G4qjgcJcjPsHe2oP9UpkRCdWKfY/wI1H2NiVzoq+lzYozijy7PIMR8JcujYa3MM+rXOlhhW9dvBxNPcdUqjm/jYQmrkl9KH3oXDC3TvR45LV00ly2qqsr3uWmHf10NNI8xBEAt583IlY/bo7jD/475wF5M0ynEIF5aVeMFYFMCgImOJqBJ5MTkSp57vzDuOLoGQAmskDdrSiNJf3wOf1afrLELGLidkTVFIoTduDhQklhMsEiqcgmqCVGA7MqNeU1SCsPOSCy7HWgfnAyu5KjABzjJ7khN8kL45D9JESXV+bQoDq9G0pBaAuaexGHL3b5Hc2hynnsMBjCsNi+yH1pKA/t0mFR/Q4e4ivMwAbzsoo6WrhdHlo9JTsvmGfmNA+cC578k9fuZJNKMJ1AJKe69cYaprUkPoGHjZ8DaitQ75MVa6NMymIpJY0kbDVvGIntO/MM/nrJnPpHzpjWVFpPExXhppGhnU+CusO3L1ErNpGv8+G5vmgFAh6zUtQLFDuFaENr+tPBC9H6yxDQ6+1MTdwwRInn5Bgy6vm8GQ2F3mtgot53bK8hrJATZiAoz5zeNzPsMmKUB3rMMKExYeiWNKBsrkrs8RZA1ZamPWci0YSBciEGh1nZvGdVG+GZuDHwF2Z7NIq29sb0zGXDaf6n8Jjq0hpKvoKJYmv81Ku0OP3h3lrjij3c4z6ho1qylZmjroEXVlqxfa8IVM541nUUQ++wcfziEXXc5GJItzi4C6EbEBBwcNzXYgTRJstbmBiv1tedgLHNu10hNaRzWgS56CldbdIz87Lic8FbMPIM/e6esKkWgovWrgf6lWPmCUF1oThzZxSksiT9cskvNslBOQF/KVg4w6fFgN9hVxWqBlHuj+6yKYORiKKeKFIr+ERGarFkVkl3w/ouahaKQJbiHaDtJH9NwiZqW3bzKebW/j1kEJOUDgyOR9p0FZowuSHTcF4MUtOksL2tMcduvz7spo5SYLhSS3I1LcwY+g+ds7TjRUUrkQ1I2EP4spnwcX/cjrgCF3LXDZWMP6HppE70TLCXt9OL8dx7eQ47or4iu6VaVraQvqCLLG5CbXTB4QIwGcaHx1X3ph0psaxYDOrG0N/hrzwUEPUWjwv17XcwRDss/O/sh5JDcMajuKLs7qxD/5Kn6Nh8khxB84SHKmabVxlHJS4eaevlooinjzE16pWXtV4D7uizDptncEGk0BPdSPzbkFo8CWqf1qIo8vKEhx/288Wn8x6WQ/oCe65M0+hgFzCbD8FCNwIOLop7yKXDZqT/NArE3/RQhbgZiiX+SCMB6L/gG6ldB0VwZiFUh4w9Zdkfrl1Y8UbynQTd4bJUgZ2AiR0exxipkKgdWll52S9p22DakiJdK44fpHRl5Ah0RvxNtlGCnVeR9TOmVwfx+sa3zFoM29czGTOt4vZP8If+fmQiI8ZtWrqMtTwK9xIoZipHzibnrQTHcuQoD5ZabiSDU6jyowOAyS64amQZsucaJu5qaSUDoPjATAh3YywUthPzm1SFFPIl+pQyJGoZbxG1GhRjT/3rpPSnHD2rPUHCOM99uVeWjD2ITyDwHXwkuV2eF9IFOz3iIQozYYj9pfwsGMJ2zE5I0JzZzEfDxGE25gQMDHgeM8E7b+vJ2W9FyaAlCTNjMSbJ4zruh9OlDBMRiN1ZxFIRcMy5lWl3x+NRY6rMgj9KVo9TQjBEWb1FXuvTEvCBBsg5XwgHw3g/Hj83F5Wp/b5AVwR9HmXmh8RpEZImH3R7htHlfua1UHd85XZYynwbnSDYe5nYh/TszdRIGGop9n38BIUAf97TrLzKnR8ZphFaifaCKhKZhB7L/q1AH+haHQSY5BalMgUVhZiYJMABzx73pVtz6gQcGwqtYBaQW1293AJkgYuP4WOEnn76ZlEU9Wv48UkSY1dx3wSSsgjZk4Igo0REAn08lNRLLtExgphQs/1NtBzyIm6V/R4+vdskqwRTSVfWF2Iw0rxMB9qLfZ9ZFOQnQ4uhVmiwgxTowoqvesec+Vc7rfJn9sSYe6SqpNcTugqtHUVQd8umzLAv+6PtJTaDKksU10LNXvKM7PpoaqGiW10Zb/vP9RRg2SZQuoQcmzg+tSKLnfVjGfUGaI5q/4seqkAtDqt/9xtwvL7M989TYTnHTIguKY+ZyBnYMH0syoZ6rfwkI66LSCk8SQUESYsFygghqIMgX2KYpy0t6DH716gU5oE9c3/U5ukAEQlwmFDecZOgqc/f/ayjG7f73h5n1eUr5WHvTHJdbmeD3ke5zCRy8n9BQdz22L6nCCuDL41EmLeSTiMGymQ5DH3o2lgGxFbZIeJpy7ZrGK01qeWVdpTA9YPnZmVn945zutuGWTDcMVRWb4bwUPAKMtg7/cmlxaBAX6JA3EkZd5zgF3TbpQYN88bPe3QN/vDU6BDUXR3/8nmgys4EFYFaG1Zk2BRRlgyLgXzLV0Q35kh51s76luutrwIk0EFH6zmlgjZvhVvnlduYi7zvuWyy6U9qO++vhIFSBmnZViFVKoTmo+RNWCI+UItk8/u4cXBnWqVgQl80u7umOIs9rqvYxrYYe5ISNYzyaK7z2B/fb+cpjgXcepch9Ev7NqD/fmHjZ7WVhyDzjfXF3mI44myUHOEQL2JKRvN5D8XbvDVwtuYL3fkUnIRR8qsbWH/HnXinW+RJZPOcDyILGjXF6CvwP6q+T150t6ZhphiInXnak2hDD822JyVF5HCVavOrngSTU6aovYXHVmZrWnEE0GbV3GB6iVEz6uw2bZl2f+QTJyrwBSD7XcxDvvQyJRhhPP4xeFp/RE8gc34OpTBwWScWa3C2F6APY6RjNrYFOdI3i/IZlGXWczEaXTQo4NHM0ALHmj/+YuHniuT0qMTMrmlqPo+M0lbPPhlR1TNfI5Sr/7he/QevThbwh8HY1aB0Ezbo513CnVY+JWhbiQd3y9s4gHFtiPUCFixmYpbFaMTv2rmeuDrkjPuHGwQpYE5iP9ewTL75Wzh8dGf1A5g0B4KnmTTbN94nZjf/lFt6efPt6qKyl8785ctLKVkQwNyHiy1q5Qv7BrGHuU0"
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 20,
    "candidatesTokenCount": 422,
    "totalTokenCount": 1165,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 20
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 422
      }
    ],
    "thoughtsTokenCount": 723
  },
  "modelVersion": "gemini-3.5-flash",
  "createTime": "2026-06-08T20:34:23.284583Z",
  "responseId": "TycnaqevEamO4_UPsMub-Qc",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.5-flash',
  {
    contents: [
      {
        parts: [{ text: 'I need help planning a road trip from San Francisco to Los Angeles.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "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: 'model',
      },
      { parts: [{ text: 'Yes, what are some good places to stop?' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 2048 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.5-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I need help planning a road trip from San Francisco to Los Angeles."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "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": "model"
      },
      {
        "parts": [
          {
            "text": "Yes, what are some good places to stop?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 2048
    }
  }
}'
```

```
To give you the best recommendations, it helps to know which route you’re planning to take. 

There are two main scenic ways to make this drive: **The Iconic Coastal Route (Highway 1)** and **The Central Valley/Wine Route (US-101)**. (The third option, Interstate 5, is the fastest at 5.5 hours, but it is mostly flat farmland with very few scenic stops).

Here are the best places to stop along the two scenic routes:

---

### Option 1: The Iconic Coastal Route (Highway 1 / PCH)
*Best for: Breathtaking ocean cliffs, beaches, and nature. (3-4 days recommended)*
* **Crucial Note:** Check current road conditions before you go. Highway 1 in the Big Sur region is prone to landslides, and parts of it are occasionally closed, requiring a detour to Highway 101.

*   **Santa Cruz:** Known for its vintage beach boardwalk, surfing culture, and redwoods just inland. Great for a quick walk on the pier.
*   **Monterey & Carmel-by-the-Sea:** Visit the world-famous Monterey Bay Aquarium, drive the gorgeous **17-Mile Drive**, and walk through Carmel, a fairytale-like village with no street addresses or streetlights.
*   **Big Sur:** Drive across the famous **Bixby Creek Bridge**, hike in Julia Pfeiffer Burns State Park to see **McWay Falls** (a waterfall that drops directly onto the beach), and grab lunch at Nepenthe for cliffside views.
*   **San Simeon:** Home to **Hearst Castle** (the lavish estate of publishing tycoon William Randolph Hearst) and the **Elephant Seal Vista Point**, where you can see hundreds of wild elephant seals lounging on the beach.
*   **Morro Bay:** Famous for "Morro Rock," a massive volcanic plug standing right in the harbor. It’s a great, quiet spot for kayaking or getting fresh seafood.
*   **Solvang:** A quirky, authentic Danish village tucked into the Santa Ynez Valley. Stop here for Danish bakeries, windmills, and wine tasting.
*   **Santa Barbara:** Known as the "American Riviera." Stop here to see the historic Old Mission, walk down State Street for shopping and dining, or visit the Funk Zone for trendy wine-tasting rooms.
*   **Malibu:** Grab a bite at the Malibu Farm Cafe at the end of the Malibu Pier as you make your final approach into LA.

---

### Option 2: The Central Valley/Wine Route (US-101)
*Best for: Wine tasting, historic missions, and a faster but still beautiful drive. (1-2 days)*
*If Highway 1 is closed in Big Sur, this is your best alternative.*

*   **Pinnacles National Park:** Just east of the 101, this is California's newest National Park. It features dramatic volcanic rock formations, caves you can hike through, and is one of the few places to spot the endangered California Condor.
*   **Paso Robles:** A world-class wine region known for its bold Zinfandels and Rhone-style blends. If you stay overnight, don't miss **Sensorio**, a stunning, massive outdoor light installation in the hills.
*   **San Luis Obispo (SLO):** A charming college town with a historic mission, a great Thursday night farmers market, and "Bubblegum Alley" (a quirky alleyway lined with chewed gum).
*   **Pismo Beach:** Just south of SLO, famous for its wide-open beaches and the Oceano Dunes, where you can drive vehicles right onto the sand.
*   **Santa Barbara & Solvang:** (Both Highway 1 and US-101 merge here, so these are great stops on either route!)

---

### To help me narrow this down for you:
1. **How many days** do you have for the trip? (Are you doing this in one day, or making a weekend out of it?)
2. **What are you most interested in?** (e.g., wine tasting, hiking, beaches, cute towns, or food?)
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "To give you the best recommendations, it helps to know which route you’re planning to take. \n\nThere are two main scenic ways to make this drive: **The Iconic Coastal Route (Highway 1)** and **The Central Valley/Wine Route (US-101)**. (The third option, Interstate 5, is the fastest at 5.5 hours, but it is mostly flat farmland with very few scenic stops).\n\nHere are the best places to stop along the two scenic routes:\n\n---\n\n### Option 1: The Iconic Coastal Route (Highway 1 / PCH)\n*Best for: Breathtaking ocean cliffs, beaches, and nature. (3-4 days recommended)*\n* **Crucial Note:** Check current road conditions before you go. Highway 1 in the Big Sur region is prone to landslides, and parts of it are occasionally closed, requiring a detour to Highway 101.\n\n*   **Santa Cruz:** Known for its vintage beach boardwalk, surfing culture, and redwoods just inland. Great for a quick walk on the pier.\n*   **Monterey & Carmel-by-the-Sea:** Visit the world-famous Monterey Bay Aquarium, drive the gorgeous **17-Mile Drive**, and walk through Carmel, a fairytale-like village with no street addresses or streetlights.\n*   **Big Sur:** Drive across the famous **Bixby Creek Bridge**, hike in Julia Pfeiffer Burns State Park to see **McWay Falls** (a waterfall that drops directly onto the beach), and grab lunch at Nepenthe for cliffside views.\n*   **San Simeon:** Home to **Hearst Castle** (the lavish estate of publishing tycoon William Randolph Hearst) and the **Elephant Seal Vista Point**, where you can see hundreds of wild elephant seals lounging on the beach.\n*   **Morro Bay:** Famous for \"Morro Rock,\" a massive volcanic plug standing right in the harbor. It’s a great, quiet spot for kayaking or getting fresh seafood.\n*   **Solvang:** A quirky, authentic Danish village tucked into the Santa Ynez Valley. Stop here for Danish bakeries, windmills, and wine tasting.\n*   **Santa Barbara:** Known as the \"American Riviera.\" Stop here to see the historic Old Mission, walk down State Street for shopping and dining, or visit the Funk Zone for trendy wine-tasting rooms.\n*   **Malibu:** Grab a bite at the Malibu Farm Cafe at the end of the Malibu Pier as you make your final approach into LA.\n\n---\n\n### Option 2: The Central Valley/Wine Route (US-101)\n*Best for: Wine tasting, historic missions, and a faster but still beautiful drive. (1-2 days)*\n*If Highway 1 is closed in Big Sur, this is your best alternative.*\n\n*   **Pinnacles National Park:** Just east of the 101, this is California's newest National Park. It features dramatic volcanic rock formations, caves you can hike through, and is one of the few places to spot the endangered California Condor.\n*   **Paso Robles:** A world-class wine region known for its bold Zinfandels and Rhone-style blends. If you stay overnight, don't miss **Sensorio**, a stunning, massive outdoor light installation in the hills.\n*   **San Luis Obispo (SLO):** A charming college town with a historic mission, a great Thursday night farmers market, and \"Bubblegum Alley\" (a quirky alleyway lined with chewed gum).\n*   **Pismo Beach:** Just south of SLO, famous for its wide-open beaches and the Oceano Dunes, where you can drive vehicles right onto the sand.\n*   **Santa Barbara & Solvang:** (Both Highway 1 and US-101 merge here, so these are great stops on either route!)\n\n---\n\n### To help me narrow this down for you:\n1. **How many days** do you have for the trip? (Are you doing this in one day, or making a weekend out of it?)\n2. **What are you most interested in?** (e.g., wine tasting, hiking, beaches, cute towns, or food?)",
            "thoughtSignature": "AY89a1+RSw3izWhv91qBq++oOCAKdBdIfuEXRL6KkcT8QxwfL8n7FVLLD/7atWacNOqF/WDHom42ee2Elzv+XydRRH0dPfh/ekI8E6dgOaz0nClFG0xbawqUSH/0x5N6apdmSzGU1jNFiKW9Pyf4yq9ab3Dv8SzoUy+n4245X2juYWAt5VO6dRaA3Y8bObPduovnt7eJE1CLtXA2wB7fdYF4DdqBuSfAc+/19ozJ5MoNuYzCRERDVMW+nEq2cZwQ8Nfoglj6WMcpBm3C8BP3tNGKjkSj9xHwWAcOkdf99C2uCPOL3dp33JY4FLa3W/AI0nLCIg0L3tduo6HF+/xoyWBEcI5OhxiNqjayiVpeeSGB8U4Z/+c3ymi4GJRRYNq8hVtouW8zCtCGaVWrzARsT6dgBiqAJzsgYrf4d2n2Vp9ef4BvzMtyEqCcdkS37hCeo60gE9rIzKCRL6hwdOoc6rieGryhg07NN2lN5V/boeVfDdhP63VDeFaaVHXnwdY4stYtkjIQ7IIpVHYdyR9/hxuM1iFc+vfwRM53+CFQOw7Ned7fSFRrR1ec5XqfAeNSnA/TQOGTmp2vZhJ8MwY1atVQoKxa1rf1zFRU7a0FbZACjSwL5goR41KKN4IbJMywoCzfCmKBPqbsqpGqKdCLk+pEA8J2/eVL9+SFKy9EpmcZZ1R7HUgdfIAm5ZAzRX91mv8c/coTgnDdGR3XHJ69JpohwBT5rdYlv/uT9iiGHx0sxu/rlp1g4TBP8L7Zfk7J1+K2G/njtJadeRjSIZ4Nyv2evZ/7nj+UVAPeqOiaJAVI8i9JzaWt+obEDuzl8iStLTFnlmMI3OnS4u2W834gOZlf8w1ziFLps951sLSstX7eP4sXe3pOQZ+HUqOgoqfsoYOnx9U7xwenTJY8yVkvCPftSwSf8I/X89kKAYO4ggJ2jL8rFy1qZwfqNmGpvgiMZI9K7SetYR7vAlDSsyjHeEH3uOOQ8TcMrXCtazDttLx7mio0BbKGgqhPGcDnrX9puQTtuBnFweKZsJXaB20dFKAs8JFmuzzAdPfMoXIa8l2ri9nfJE+tzQsPFLCptp+fSsj+iw3m+oqY22sP96PEOPO0Pqij/I1e7fhltfKvY1yNfjPvzm9krVT2G3E2XqdcA8cXRi4pIDm69/YHleAD5Q8LmDBZ14xUj3ROjPJnIFcIFvtI8jgEjYM722g7tLee9exECuDwK4kri69/wN/2ckpyTKPacLInfxDDF6TKE9vxTcyGVdrlZ8jAX5PUJgaQbWlomXMFy4Miu/qUZDTwwjOQUNq/odhA923jPBOqai7izIudL9WJiVEXY9lU3E/2hvd3luZAd9Mayy0k7u5KFivVXsSdhOB4nMt0loZ+lbzmWDpSYaWQH/k1mXV8dm3/KFs/l6a9pYLk3fGzr66IW+Sa7vRoSbaeEppbaFvA9ERLKCcBZxtkXLICUngC1z4HqCKYuPKo5EBRtq04DR3Z5Dfzww/LilA2vg8f9riezdWBxsYKXtSkIfYaPVR6QuwOXr2D6s3RzZm/UKYrX8tyoBuQqndzffbp2A2cZ7iQXBmO8M5AducLKYnm9ljE54w8Ym42O4UZUfs//LPhaivC6LVGUoJ515f+iVwFBPheXVQQQ3GriHKHWLy+k2Vupv0PFfteBvLXOeG8WfoQJcrjn4deKg48esMBptpbIJVqEvDlUMHzBVfNisyxMsmeXn8FXFQwpHmAwJXUgrUFNOYjGhUcfZOPzwXxOBicNKRi3f7sCW3c0L4EFzluHGFUdvv7JKBlXYVTCK+8MZNRLex70sxtSYemY7myxboV/Y0MCZyP8qM45hKrxTKZC2g3FRDeEWv6emY9eEs/4ze/P63kDoI9DoRv63T7EQeRXsCyYKZbDIJgNc7VG+DFX/ucW8tx0ZZOSUPRiHBUirKf7858ecNS5/BajDjyAIo53DWKBzvzmGEUkozS/0rhl3cu8HbOul9TcUiwWPwuTHerDdIMJmMBZZqYKp+mIS8tgSHF81FRIiUUt60Ig/LPI3RXbPhMnZnZk9YiK42U538klS7/3CBf/QjQmMqZS84HxIY13v8oZbfM12WWeRwQHgDLgKH+ovc6IaJcDj3JUNmXU9A0BI33FTtd/DqiZ9Eb8D8xG6eak1089KYVrJfFjOy7SeeLHcll86YzLv+LxJEaR2IWFYqENlC2rd+lxX18Itle/OZpr2+FkDs7uRgl1GoVqrjfOoqwCaJSaodZOQPTbpj9mSLHv1qcEagcG42h8pwb3bCBmutU/bxNLgyvUUR89ScKzPrkTg5OiClY2/DIYTZgoxyseAVRl/Efm/KSjQVoQ26QmiASYWUwnCRxei7N8j/lwYgXzCY51JwExjCjE98jgKOca9yh01fTIAY0EH6ZM+08oNGvl+t3h1knv3Jva7BbdoEtPz9XJJsV37EmsXUXe253ifYzc9qxR9kSVOwGSkzkloyZMzMLDi9MPvQUXJ1LptkY3Zqkvg0thBic/XXU5rrhziTewcQJuzK6UbyAkUf1ArqEJjEWmD0eHF6B535/oWQgBQZh9QOsLhm1BBD2ixstl8zYtcZLcMRrwvVIJhwRUBgTDxdyGOB+IpfHnMI/i6qldkbC9ubeDLg3qe1rM8WXeTXYVcJdEEYDzYvuqmIm3ldjlQb2K3mwXEB3FvG51Oy8glYY68b6l+TM2e+UwG7etuSJZ0Hq5iUmw8DoSKA2hjmsVnGqe6j/t8c/Zr1bAP/3VS3g3N9xIWUtqe5Pe3MAfB5WrJQEVd84hxFvXxbHgBJC9e+2uHLbcSEvnaIL7RZfdSyMzfM7P/lKr1npSeGj8Ybc2UMYombCLcC03F7LMvgh/GjlNFhwPACNlGZTB7CwrcA8kacuPYCCI0nA97Br0hmW1FXB9RzqHRkSeWiqkir5G3VIkoAi90R0a1E/kn80Jk4ryrXBp03yjzzAr4FcdqCkbLweXrjuCEazD+AAfkn0xnQgLBIYxZh3KjUOuL7JNmmkSwsbAr8+70S7wZhUSbLZlZ6l7ZbcxpYmFxwa2wFwfN+PAJJBQR+/DKJttJppoePfDiha+B45mHXlb1OAcW4lGiH1BkEsdsI/yOSpg685J//VtBhclV7LUI9hQqTSXAUjDXhiFH3fTay9hrF+qRzhhdmO0FpnEhzev8dUJGFt8f7R+4ktof4SdY70/HxY7eYvSjW+CUtVTFIEXAiQQOsOxcCDsFKNQj5LXu6Kbput6dDu3oYnkl+//uVYxxBv/ViU7akr8VSMU53br6Bv+85bPX03s1J9Ri6tDUz9NSq5yH07fNpK4ZnocaaIyt1CYJtLC6SP7hvbbmtQWbDOGQRmlk5N8LwR4QKxEaNKeloIynGWl6DRr7tLcMzGsppkA5ls4ThoKoM3UnQ8jlFN8qBJh7C/ooQ3g8HtcT7zaihentYPvaKZfalPPkU/z9iWbtrV3ydXvk8uSFiFW0GYC8SlazFWKy/1a+4uiPDRirWlRRSLbcQP9G2QJ7Z8J4uXkL34QIYYoBD6uIHAurY+cCqOiHF4CXatSrjim4h8d20ZKRkcroT5hlNLCV+WSJg8lJl7eHXj+7YVAp3o7OYgPTlMYa6Rl3/kgEJFvrByRCgQ5oVLeYu+RdDgpFhBkZRVq45lHtDQyJqs4F061Q5sIubsb5k6VPRq/s+vZPMB7eTaRqx7wrpF3QtU6xSG71f5hNRrLUYxgsSdyVAuI6R7AhquTnNH9jheA/Ehlg2FNEFc1gkkZch2NiScBANwRIBCZK9CGeYAEFPpkiLTvdhFBMIkCsBv1QYql0URP27JoHC3zrrsfql2wMwXtMbTMWZOE1KH8D92UzFxSY2e7QPEGqrUy7S8SBoR56rEXzLV3A1ePy0Rkql3dkahsLjhXc0LGZyAUdMEh6IfdIT0zqZkz5KQcmzIejliSonJG+hRV/HsUgbryDETNJUGGjn+zLtKsi/xMnW9D9YmxMIEgSO/x0nNw4yBcIwVXlZRs+jNNrUV5MmbezfRTi4Ul+aq1L1Xi2q0E+6Gd1clxULNDkszX9kmgdCLBzdTY+43ZVMZZpETS17GHhCUQQuiVmJUl7A1vAdgC7u/+Gwy+gWk4hSxpubLMxn1nBfHXfQBQxCWebsi/VHcX3L/iII2Q3wh+hu0be3Hy98oAaITSXLbJJch"
          }
        ]
      },
      
... response truncated ...
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.5-flash',
  {
    contents: [
      {
        parts: [{ text: 'Write a short story opening about a detective finding an unusual clue.' }],
        role: 'user',
      },
    ],
    generationConfig: { maxOutputTokens: 4096, temperature: 0.8 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.5-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a short story opening about a detective finding an unusual clue."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 4096,
      "temperature": 0.8
    }
  }
}'
```

```
The rain against the penthouse glass sounded like a handful of gravel thrown repeatedly against the window. Detective Silas Thorne ignored it, kneeling beside the body of Julian Vance. Vance, a billionaire philanthropist with a reputation for pristine health, sat upright in his velvet wingback chair, looking less like a corpse and more like a man waiting for a late-night guest. There were no signs of struggle, no traces of poison in the half-empty scotch glass, and no marks on his throat. 

Thorne snapped on a pair of latex gloves and leaned closer, tilting Vance’s chin upward. Under the harsh, sterile beam of his penlight, the dead man’s mouth was slightly agape. 

Thorne tapped the victim’s teeth with the metal tip of his pen. *Clack. Clack. Click.*

The sound of the left rear molar was too hollow, too metallic. Thorne reached for his forceps, gently gripping the tooth, expecting a loose crown. Instead, with a soft, wet pop, the entire tooth slipped effortlessly out of the gumline. 

It wasn’t bone.

Thorne held the object up to the light. It was a masterpiece of micro-engineering: a molar carved from translucent white jade, capped in tarnished silver. But it was what lay *inside* the jade that made Thorne’s breath hitch. Encased in the stone was a microscopic brass gear, no larger than a grain of sand, turning in perfect, silent rhythm. 

Frowning, Thorne pressed the tiny tooth to his ear. 

From the depths of the dead man's molar, a microscopic music box was playing a tinny, three-note lullaby. It was the exact melody Thorne's mother used to hum to him when he was a boy—a song he had never told a living soul about.
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "The rain against the penthouse glass sounded like a handful of gravel thrown repeatedly against the window. Detective Silas Thorne ignored it, kneeling beside the body of Julian Vance. Vance, a billionaire philanthropist with a reputation for pristine health, sat upright in his velvet wingback chair, looking less like a corpse and more like a man waiting for a late-night guest. There were no signs of struggle, no traces of poison in the half-empty scotch glass, and no marks on his throat. \n\nThorne snapped on a pair of latex gloves and leaned closer, tilting Vance’s chin upward. Under the harsh, sterile beam of his penlight, the dead man’s mouth was slightly agape. \n\nThorne tapped the victim’s teeth with the metal tip of his pen. *Clack. Clack. Click.*\n\nThe sound of the left rear molar was too hollow, too metallic. Thorne reached for his forceps, gently gripping the tooth, expecting a loose crown. Instead, with a soft, wet pop, the entire tooth slipped effortlessly out of the gumline. \n\nIt wasn’t bone.\n\nThorne held the object up to the light. It was a masterpiece of micro-engineering: a molar carved from translucent white jade, capped in tarnished silver. But it was what lay *inside* the jade that made Thorne’s breath hitch. Encased in the stone was a microscopic brass gear, no larger than a grain of sand, turning in perfect, silent rhythm. \n\nFrowning, Thorne pressed the tiny tooth to his ear. \n\nFrom the depths of the dead man's molar, a microscopic music box was playing a tinny, three-note lullaby. It was the exact melody Thorne's mother used to hum to him when he was a boy—a song he had never told a living soul about.",
            "thoughtSignature": "AY89a19lgSQcev60/qplEo1TLqK0IE3xXnRTo+cVH2SFO4EYasSdVPkP4TlNyNu81RlWp1Uhc8aEhWO6stpq3Oic0j5/Jdzyf1Q01DjWVBJQeggrNov/nP8ecj2BTOKUae/RFVeMTvpNwKPDxp4gKzcxeNN0PSOe7RgXp5V6hnGSYJB1oXBhG9QV1FE4sm1U9Z+azRcSKGvNIqZzfWZGvhohKArD9D7jpr45NkzLqcHKGgnEMIKjsouMj5ZhItiUQFMdaQxLqUHH/u6B3MivL5SCXTcy3+7zN4V/ZbwnRe5jiaqP2uTC67dpcWx4N/gQtfv0m76ZTsGTkXC1MEzMnwmbiKPPKlS3UD/oD2FVdNyviTbxsv5Y3lFhjJbb7Xez+tVt71hFSZ021jg7b5zT/QJDNU2H3baanZ8kqktsBWr2137fMzoStuVRfMq55WdlpzegnV+j90LWZHGr5c0N0jEaJUu1NcpvbrJcRztndJbh1QiyFo2flrQzg9zhAuBHMHIl5cuC5oanxCK0KBkYkJoamaAUPKFNgNZV6O0Q9K74ZYOfxCOpIVkwhq1MBdmqf1XzhIJNTMfGfL6odfPE5b87P5PBjUL/3t25Bh+HfSgCIDiCR/dE/9Z7AgR+o/A4EsGlsVTIcLtXccfv/ys/yNmx+bM2dMqxCGcDpbtllEutE+rd1rJaudYU04IziKxklSroxEi0w4rT2Oq2Clm/DRdzb07xahyEuQH65TWfus8Tzdc8iv0oq/7Tmd3onHC3x71bIq0TDwj6IV72pnrMvwJt8Tgp0YZPdvLUSvH1eZulyD3EyZ8sfvEFaba6OQN47X3PHlYk0IYlz1QD4Fs7CwtnBY3nTCwRimdUZh5V3HBK8KzASpsiekd36qQsHdFHOciYbYK4RaNd4BWh04MM1a+7hv6+1qihnLrTis2Ofef3FCc+S5ck4guxWmkPLSY8RnO+PaIJIbJWCy+D9sc69UzzUT7AsyDY3VCVvCp723AeEQ28/Z9NLgtswBCHsxT8FHMYY3jKR3bXlX8nIl1fZ5jvYyscOk8txnoXQGrzm1+Piwxp9uLhX8jufgkxJhphr4/m5OBEyXILTwTR9HXlRxSkv4XikadqZoRbrFT+8jO9bTbJgmLbvDral6KOADEX+5JDXzmwNdJ6+xWvGYDzy5jw1OfTXm32Qh8303P3YtGjhLHahnCZsE+40bxCcg2tBDZGvAdvTg+GPmTJN1MF0ExVeMRtqb+vr3ebXkOWPrGxDjgRUKFUjwyG300E+BogBZONJc+gvt483c7TTYJVAiA4i0fpT8qYScEA0gMCFGdyOgbooq4OliSUFLQB0kmtnbZ95v9bCxaz4MpnmO21CqqTYO/EQUYIyLExvU8zc6PbfTU0CHTwYXv3Y/qLIcH0vDbj+7w4bVxTOzFTXu4fpsSV5QoAUgVRwXAwWwp0IGvrv2KUrOsr4G9GegZ5EiAVHv2oru2i0Lx6OWEkSNY8JIhU4Um0tVs/SSdPbVdmYQNhnBJzSFdK+6jJXgOYEkf1vuzXTc7AHM7Yul3G+RkkL0YPTqZ8ywQBenrrkgtpZ6Aoj8sioZhdsQAsq7yrG3a49gCdVqcSrfTtjLl49MYAXuFuwM/Y4fGQW5w11BAEDQjVo237Id+9mkPb+bSlYNN2I9M9QajDd4XAgj27sEJuXQj6aVcznT1HAOpm2BSOX7n5FIek+ics9CiyIo+cmENwpSz8b2UnhmGk6oHaMpcTGJfWsbwes3KvaCIuR0hx3kQjBCTnODOClqcDDtDyZcCL1uUHKsHY+rRnIM9jybilvcRpjeVpv24Kx41TN6sSqZ7Dv0CXgf6nwYboi7uZhJHlFcny7W3+skw3i7q+BZTKbzQkR0wSlqvdBv5HKrNAdfFalOxllhKVIybPpZ9KbJRH3hSJmS1TYpG99JHpZWLh8BBGzQHO6+1wKZ7RtfSPN5/3TXalZNQeJYlvL5jm1O5/W1XJB/pMaofo6ZdSC8Lqo6zGHX+AloXtp+RGy178XvLLSS1yNfQNNythjUb3b18+KsPeKRWXSdRR7gOd1Hrg1qdAGNX3BfQlR+rYOImurtfMZ4T4vLYl6JtBTbttDE3muDGmsfhZvsh1+/nakZA4uHfUYqI8JEgAbfWg3pejxcT8PHH7UbiOXNQtp/vmh2tN5F82y1XlMpuZya3mFoew7G8EMaD9k09MA5Vw+fxcOVTHfvJKpbVeH6yvOxmO6g0rzmPFr0BdYam6ZrumGifiv3Jc+29SUM3kr/TdpYEBvAu6d8yHB2J+o3dT78FcES+gLYxijqYfCOsvcn94uZWSVthDRJY4u3aUmtQNNTIG8Yl4qSirb/KeRFaOXAP9t6aybSDAXcIaXmCwUw9ln8Ksb3o2dddWLMwb/V+lp2ImwO3H2gvjg3Vqv01LO50qvNnpF4BrOQx4nEywQirPY4+Y1Q4Hl5STT7V8c6isjo2EgFxc3xAV0oAn4pivWU8mV7dyTT7L0UDnMzJcT/Je6W4NBp9T3iUk+SLveI9rY0W52BN/TGvZoSSBsDzL7vNPKYKrKDyJnXA1H0f58AsHVzqQArMD9bmhLsBcmXLmK9vnbTliWC59uy8/6eeK4AL+2eYr2rtJwwHRbkSooEt31cHu9THrUispZvy4coXi35KDjdC65VJc7JwkfIJ+vVac8zuypnTKljLIm2bQn3f3QLY1EJ563e3jInwSM4cXDIxP+vYS8hUYOz+8UAlE6dkhIDHaRozR6uBg3Oyw2B3pn0s8p19Fu4qHX7CdeQJha710uYQw8uLDfxKsDF/X7Hfo16WHVdTrAdz2RST2L3PrNXC0MsBaSO/inG97Eoq17b/6KznWZouIPIdUn9X2cwgWJshG9nxqp4ohpJlNFsBfKVlymAPFszBZlockexDdcKIpcY5kD69lZXDgMaWpFh4s+5XMvpCCHbNR1StpxdK4+2y/1E4yLxeVZCxeFxn/KQe5pABoJDCNSIpAkRUfYGuxmrGBgfQFQgL7WZhLMM8Bb04ZYVc5IAQvxhvo45i6faFVlunsSN/7CNcrxiU4iqld7CQZscasBWQhtUh+xvc+hjSSh4mqRPBqp5ZrRT7R11djCoC8S51Vf1KBep3b7iCix7wdu38Wbh8STLqqp/8Yf9e2brtPGqZXwrp1wxRtbBjDo5FoVBBL7hMJGA7UeBnAuiyH2skeCI8EQtZTScYHcIagSqyuEclJ8/VHP6FOaRYGR3O2TAUPBdFGrex3zvtij1XsdudKDs9YhtQvZpRdfosD8s8NW8jRaD1P2n6FB6Rz2jk0IOTTpzvstRAI64wuaKDhu0qa143tHV6oxICcOLrxKCmV/NI1Ol9/09Xm64A6AOZxEWJ9KHRbxN48AbzpXfRqEfr51S41sngGOHsl7ZZafSTSh+kzhoVavhrjYCs95s+2VkSd1kbF/MsC9gvxk1HAkIGeW/QdSYgMjZZeNTVtD/7YIVXchGhxWiUKYR2wj5GNz+og5cWkoU6IK+mNEf1WztSu9rBjN3ablV0vc4vW6Hxq45urFdR5ukrvC/u8ejd8my3RZrnAPFMiZxSD88wD7XtA74DSgfLEwVPrdSBF+qsx+4dwr3ETro1+LPstdBT5bjJ9K5eV2CkYq6G3WsI37qwYWbW2aux08uZsh8vuRh0hd0a7+xROfS62HjlrjUufHAUVpAQB0+J2kaIZih1asBoq0ospdwmy1R0Q8oyPSo30GrGoTHN6B+zSWL0mL9y56sq6ZZvcVgmnIMK75J8RicwpWeueZcSRq9ipowKQbzhWRYjKNs+QrD/qyZdMkm9wn+iMQgoxXHdpUY/axfhsQJw+NRvnv8GQBnBTHiEmK2e/Igv4xPK3/BxwtjGN2rCYajeppvrNyU7N4lo+ZjqCPMMxsrhcpSQxC5xE66prOB/p+WUFRguTcZTqSOwTpxz58jh8J7/oVRGvAhrgkD7d6U8j+oy5acjsSoW8nsUTV+mc3XW5d2Z8CSWJXO8TghJziL1AgFUKie75srtPh9VW2EawGU/1GoxuS9J8U6bgM7xDPWzdgt7MU/S+DY3YGdyD0c22WpNauwlNgADfJNzE8LmQWK7Tl1GF0THzCexC6346ZweADyw5yjjxjrYkGPUTvB7x5f6mpAfZ51vJUqWn1QQczWi5hI1ibeD2NVuFf8i1fg/JvRj6gQgFwXQ0gsReLXphY1Wrh8DrgzU4uTF56WodJpqssHXuKdiZ0CY63ATVPnlHZ5hTbc8FIl+GOkaMizLL24zO2P6HeAAnQP2yCMvmhIgyJ5h59S8VIVY6ked/LsIKmoy4OGroPIVgsgK8FBN+DOa1qLWdg5hcVavHQoW7SVPLsy54HajePekSLhXvFvcLmZ3ZJUwb0b8keDJ3Fex0Qz6D8Mw/C929XiOrtOn6P77a8HZw1ZpdMyhnNExRJsNwYW79c+CKBJFrAPs3N+jYmRWWa6OxicVtMdbQ7SBuYDruHngUN5zx4AzXxeZX3TpgZEaBpJQUDCfsgdDHBuyFfq9SJAdbiwOlBDtgh8cSpsy/3bSzHnQHUU/JRLLdKXosQyQhiyB19yU359XCkpQB7qvUVlfNR4s0yGOXtgwJB9G4iJgm/5h/c2PwzhrbQChisk5RlkctKyFvrw5+t0xILEik8HZm5p2fuFOqF0yInYkoLNqL8+Pdt0OtO6BUdw1AVpkORe42m9D6VA2Ou9EtMEsiDlYVRch0aGoJ87nd9SV+kZJ5+xkPl0ldJcwE0DoFYewIDkMrzngT+fMSpIDmv4djhPvQzZ5LtDMzE+BDM64nVyf1RxPljGzDiRhjTDzYWzSeT+ihslO1HKuxyBi9d5i0rxRACNmlJCfCT7iisOmv83wdAbZn0YnV9pSZW6R4DD6hceb5pM8007qCZAvFPA7e90BmXq0kUTZ7+oL9vNKzU3kDcf2yLxcklIqW7px0ZDGlbNwHlp82W326ATBjvUr0RlnGy2S/FOgemIY8D5Ienz4AM6LqgZL2d4rYMJOFkSaFkZQm47i6N0OhJHZQZmC5E6gCw7XejCJMpFMB+BT/Zs+vTWH8M6or9MMY4gkx3rzP5SIn6ZeVsBNQPdupOw6cJUe0ZEX3Fs+lWg4bGjtJk2IHUAcb4GLXcw31OKcjd6C98ZNe13Hor9Z9noP3DA6nURdPAuzfRHd6CH/mdITa8ECJAZKv2zrZS6WK/bivxc1aUFzISY1CjLJ3Ti5VvDvotY+hQ8f9aF1u0LaBOcAp3RWfcIjODtpoyMZQ70Cg+mxw1zTOgKUpmufW1bCZCMlHwBYH7xCaERrfRfG3zIwPLR6Hgpqgt254Ojn6ZbpOPBvlMQ9grvvWhXYxVefN8zmlDXRbxN66va2Nk+byyOQBb8d3eQ8/hQ+MOLHexFk5+TkCTAIA0TFPISUe0K3w3PHXa1jsXFLKGoFVd9ytE7MJ0Y3wBVXDWOjYAij9W6lZh9EvM2BsGrsHRvE4Y0sxKOoGtyXLAP6cMz4I9jEE5lTls9HwhPgtUFvHftCFSWouMwxUjqso1Cg0xiupB0UF2h0FIc2rukuBxQCWCrC7LPYDBvyjh87s6fJflb1uYXEIteBBlt96bERLxbTnv3lk5PK8Hp75xbIOJiqWuQsXdhv+fJc2Cb7uxBm0TRykdgEmhp6uYwH1OFpwjqSbe8NkJFGJIGNy6CINZO8MU7Je0SldqbuB60Ywu6tk0655mC79GcwBK/V8Acj3fIK+eF0afvxi5/STd0cAfzt8NJrxoHbC77adocN3TDCSxqDFGkLX9z+R6lXn9X3trk/hsSO4bgf498QY4dETyXNjrnny3jTob370ZmCl6H3wLyyhIauIrheLYbvW21YjPdONi5IHR2ZMPb7mpXbIDP+Ae3Q6j9veV2T6PKkOY0feHWfw/D2Zh3Yvz+DRGj8xRCeib409JozM4zfJ+M6AJ9xcON7frhtBr3h1gVcgcigNcWl0oCgf/PwpOJ+Xo02atLBd7eVYnpjmETG4OscZKeKBjAKqbhjWRwVkoMa+VYAmUfDhM2nUPXmxEMxLjxxASXTnSw+VQJP4X4kgWPpdiE7K+dH8JcQkhqQ0KV7nOqFXVsE084//PTC+CL4+vaCfJM7yA1PU6hJ4tBTzZEP77MZTAeuZ0xZx8Gp3eQWoL+pN6G2B6MyEo2bFTZD+R+
... response truncated ...
```

</details>

<details>

<summary>**Image Understanding** — Sending an image with a text prompt for visual understanding</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.5-flash',
  {
    contents: [
      {
        parts: [
          { text: 'What logo is shown in this image? Describe its colors and design.' },
          {
            inlineData: {
              mimeType: 'image/png',
              data: 'iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAC/VBMVEUAAAAzhPwzhPwyhPwzhPoyg/sonYslp1swiuD/vgDwQivwQivvQivvQivxQyzwQivwQC3uQizwQizvQivyRSvwQyvvQivvQivwQyvvQyvwQyr/vgD/vwD/tAD/vwD/vwD/vwD/vwD/vwD/vgD/vwD/vgDwQivwQizvQivvQivwQizwQyvwQyvuRC3vQizwQi3wQivwQivsQyjvQyvwQizwQivrQy/wQivwQivyRCr/SkryRS3wQirwQivxQSrvQisyhPwyg/sjqkjvQywyg/z/vwDwQyv/vgDxUCfSug4kqkjMuRHwQizwQyvxQSrwQivvQys1gvnxQSvwQizwQyzxTyj9rAf/vwDUuw0kqkgkqkkkqVEvit4zhPswid8wieAyhPv/vgD/vwAkqkjNuRDvQizwQiwyg/wyg/wyg/szg/wyhPo4f/8yhPsyhPsxhf8vh/8yhPsyg/wugv8yhPzvQiwkqkgjqkgkqkgbrVIjqkkjqUkjqUkjqkgkqkcjqkgiqkcjqkgjqkgkqUkkqkgkqUgjqkgjqkgnqkcjqkgjpUcjqkklqUcjqkkjqUgkqkgkqUgAxWwjqkgkqkgjqkknqkcjqkkiqkgjqkgjqkgjqkgjqUkutlkjqkkjqkgjqkgjqkkkqkgjqkgfqkojqkjvQiwjqkn/vwD/vgD/vQD/vgD/vwD/vwD/vwD/vwD/vwD/vwD/vwD/vgD/vwD/vgD/vwD/vwD/vwD/vwD/vgD/vwD/vgAzhPwzhPwyhPwxgvsyhPsyg/szhP8zg/oyg/sqi/8zgP8yhPsyg/wzhPszhPwyhPwyhPwzhPszg/vvQisjqkkjqkgjqkkjqkjvQizwQiz/hwD/wAD/vQD/vgD/wQD/vwD/vwD/vwD/vwD/vgD9qwfxTSj8qQjxTSjyZh/9sgT/vQH/wAD/twD/vwD/vwD+swX/vgD/vgD/vgD/vgD/vQD/vwD/vwD/vgD/vwD/vwD/vwD/vgD/vwD/mRDtQivvQivvQisvjsgzhPtZTWZOAAAA/3RSTlMAzP9mNvBxeuPi3qIvdDlZED5D1yjv28pm/EdLOgqLtcneHT5eV1V4lrRefqos/iCF5Q1RxLsJmmwYAxQ18DfHyN7d1dLRzs/KzumxrLA79kArOvL/////zef//+Xl5Ofp6ry4uLi+wm6WszsS9qAdCoG3EKunmuJvCV4qj59ZvC7l9qrvN1QyEyUHyyHss8VMAUX+kgzYQX9lhjwDaaTRlncaEPv5+PVREPunn5hD/XTzY2hsZZGT+SOvg31iV1FDTCUx/QYY2XP6aL67kIqRma7A8u0zAVQaNwju1nnA/v////ZS+iYUA9qHM37G9yoXWTXDMMy4m3wFHOpMS4fyEyqSAAABpklEQVR42u2Wv0vDQBiGj7h0EBFBcFToooWig4uI4uqgIIcHR/BP0NF/oJsigtFFRXDqJrgorv5YXApSXRxEnIu/NhdN0yR3yfflvuTQofiO393z9C25HGGsizPElTTz0os8lVE63cuR0PB+nhECz7MzaMCb3JhM/osTMlC4fphJjF8mCrBTIQTRMA3zJ4JomIH5U+HnWdtaHftZmKqQeCaCPEUbx9XVCSofGRaSG2aDeR/CfwrdgD3kJWYq0DZU4E3VdK8wZVUgXrBtKK8VEPUCt4/Ktyx5wSwFr7aCIvyZwr/9UgEHTI+twEkLRmwF77YC9i8QZVuB+FvBnK1grbP6oAiGTS8O8A/yvc5GwQWdv4qmj+QKl2CBHJeiQxGcE/lVZeFeM9Qw3sUK6BWklDAvZUnhb7F7UUrY4PnzFaQAYy2NTyt2O2M3eQqTFWSc/XhxK566cIHQIJOp3SUnJYRndYiH4sI8Yx803jdcw49pgyiQN9hBadD4jKN+bMm3T5sh86YLw7P5+SA7OH5I/GBYh/HtHN8cByl6L/+Hy+ZRCHusq/MN4hbRTvNyopwAAAAASUVORK5CYII=',
            },
          },
        ],
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.5-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What logo is shown in this image? Describe its colors and design."
          },
          {
            "inlineData": {
              "mimeType": "image/png",
              "data": "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAC/VBMVEUAAAAzhPwzhPwyhPwzhPoyg/sonYslp1swiuD/vgDwQivwQivvQivvQivxQyzwQivwQC3uQizwQizvQivyRSvwQyvvQivvQivwQyvvQyvwQyr/vgD/vwD/tAD/vwD/vwD/vwD/vwD/vwD/vgD/vwD/vgDwQivwQizvQivvQivwQizwQyvwQyvuRC3vQizwQi3wQivwQivsQyjvQyvwQizwQivrQy/wQivwQivyRCr/SkryRS3wQirwQivxQSrvQisyhPwyg/sjqkjvQywyg/z/vwDwQyv/vgDxUCfSug4kqkjMuRHwQizwQyvxQSrwQivvQys1gvnxQSvwQizwQyzxTyj9rAf/vwDUuw0kqkgkqkkkqVEvit4zhPswid8wieAyhPv/vgD/vwAkqkjNuRDvQizwQiwyg/wyg/wyg/szg/wyhPo4f/8yhPsyhPsxhf8vh/8yhPsyg/wugv8yhPzvQiwkqkgjqkgkqkgbrVIjqkkjqUkjqUkjqkgkqkcjqkgiqkcjqkgjqkgkqUkkqkgkqUgjqkgjqkgnqkcjqkgjpUcjqkklqUcjqkkjqUgkqkgkqUgAxWwjqkgkqkgjqkknqkcjqkkiqkgjqkgjqkgjqkgjqUkutlkjqkkjqkgjqkgjqkkkqkgjqkgfqkojqkjvQiwjqkn/vwD/vgD/vQD/vgD/vwD/vwD/vwD/vwD/vwD/vwD/vwD/vgD/vwD/vgD/vwD/vwD/vwD/vwD/vgD/vwD/vgAzhPwzhPwyhPwxgvsyhPsyg/szhP8zg/oyg/sqi/8zgP8yhPsyg/wzhPszhPwyhPwyhPwzhPszg/vvQisjqkkjqkgjqkkjqkjvQizwQiz/hwD/wAD/vQD/vgD/wQD/vwD/vwD/vwD/vwD/vgD9qwfxTSj8qQjxTSjyZh/9sgT/vQH/wAD/twD/vwD/vwD+swX/vgD/vgD/vgD/vgD/vQD/vwD/vwD/vgD/vwD/vwD/vwD/vgD/vwD/mRDtQivvQivvQisvjsgzhPtZTWZOAAAA/3RSTlMAzP9mNvBxeuPi3qIvdDlZED5D1yjv28pm/EdLOgqLtcneHT5eV1V4lrRefqos/iCF5Q1RxLsJmmwYAxQ18DfHyN7d1dLRzs/KzumxrLA79kArOvL/////zef//+Xl5Ofp6ry4uLi+wm6WszsS9qAdCoG3EKunmuJvCV4qj59ZvC7l9qrvN1QyEyUHyyHss8VMAUX+kgzYQX9lhjwDaaTRlncaEPv5+PVREPunn5hD/XTzY2hsZZGT+SOvg31iV1FDTCUx/QYY2XP6aL67kIqRma7A8u0zAVQaNwju1nnA/v////ZS+iYUA9qHM37G9yoXWTXDMMy4m3wFHOpMS4fyEyqSAAABpklEQVR42u2Wv0vDQBiGj7h0EBFBcFToooWig4uI4uqgIIcHR/BP0NF/oJsigtFFRXDqJrgorv5YXApSXRxEnIu/NhdN0yR3yfflvuTQofiO393z9C25HGGsizPElTTz0os8lVE63cuR0PB+nhECz7MzaMCb3JhM/osTMlC4fphJjF8mCrBTIQTRMA3zJ4JomIH5U+HnWdtaHftZmKqQeCaCPEUbx9XVCSofGRaSG2aDeR/CfwrdgD3kJWYq0DZU4E3VdK8wZVUgXrBtKK8VEPUCt4/Ktyx5wSwFr7aCIvyZwr/9UgEHTI+twEkLRmwF77YC9i8QZVuB+FvBnK1grbP6oAiGTS8O8A/yvc5GwQWdv4qmj+QKl2CBHJeiQxGcE/lVZeFeM9Qw3sUK6BWklDAvZUnhb7F7UUrY4PnzFaQAYy2NTyt2O2M3eQqTFWSc/XhxK566cIHQIJOp3SUnJYRndYiH4sI8Yx803jdcw49pgyiQN9hBadD4jKN+bMm3T5sh86YLw7P5+SA7OH5I/GBYh/HtHN8cByl6L/+Hy+ZRCHusq/MN4hbRTvNyopwAAAAASUVORK5CYII="
            }
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
The logo shown in the image is the **Google "G" logo** (specifically, the "Super G" icon used for Google Search, the Google app, and various other Google services).

### **Design and Colors:**
*   **Shape:** It is a stylized, geometric representation of the capital letter **"G"** designed within a circular framework.
*   **Color Segments:** The logo is divided into four distinct, vibrant color segments:
    *   **Blue:** Covers the right side, including the horizontal crossbar that extends into the center of the circle.
    *   **Red:** Arches across the top section.
    *   **Yellow:** Covers the left side.
    *   **Green:** Arches across the bottom section.
*   **Background:** In this specific image, the logo is set against a solid **black** background.
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "The logo shown in the image is the **Google \"G\" logo** (specifically, the \"Super G\" icon used for Google Search, the Google app, and various other Google services).\n\n### **Design and Colors:**\n*   **Shape:** It is a stylized, geometric representation of the capital letter **\"G\"** designed within a circular framework.\n*   **Color Segments:** The logo is divided into four distinct, vibrant color segments:\n    *   **Blue:** Covers the right side, including the horizontal crossbar that extends into the center of the circle.\n    *   **Red:** Arches across the top section.\n    *   **Yellow:** Covers the left side.\n    *   **Green:** Arches across the bottom section.\n*   **Background:** In this specific image, the logo is set against a solid **black** background.",
            "thoughtSignature": "AY89a1/5q1bTPB9D6PLxX7+jrWKT1+chZMM/cs1X1RkxRz6/DYbn0g1kS8NGv05YGsXHQylBdy/tqz0QE3CQ20Zn92ChpFLj6kMZ3vhG7q4/lG2Ln+/O/srxp9rl6R0TAqgGmkMsZu+V1KhccrmkFpVhKQGHoroKXovf2yuvRJq0+zpRwV0A2V2N7ZEsBRPP4XqTp66wkIIzpL61NatnxY76UrAV/OPzw+CRqMU52WG2lKbng26iPudIn27LpRvXgnmiZT4Rr1hgOzge5ISQ6kGOCSUvolI8W0NhsWmT4yXNP+xKE4WwN4W7QHI1Ws/Yh2vbD8zIoxyO/GfMbuzRqrvZs1qZXnNeZ0JAagXQWQ86souYS/qE0pMwXuIY5dUE7kzEFeuE9yC1VG5crJEI8TwSk3l5H7VZ5ai/oU1TSD/hLIQnpSdh/WHM6nvfhXBbg/OQmo9WW217jqzTuj5vKwyort8agJeoj3AiLyVfnqIrOmSxJbFMaFzgbvH1n143Crj7yr3caxnj8mPboLC3djh4KdpI7Hu7sQOLS/tjwhO16n1AVxTxyJMUs1TEHY1FavohCwY4S6yKTq0eOWrWSNlSIzH1XwzuzxIQqjqIYS58fVI8QQRHDYuuvbQo9lLj4SyKOeN/mZ7JtJplFT62IwEmTlMEkMnWz0a4gKazZuoYp/VvttvUTVut89nx9q4yfXFUDwnvxoMZgAWL7ixFF04hgja9KTZviplX5ZnQ2APuDxDc+Ykhq1AFxFVtCTU/59tgnSzl8k1p2pQPkZrkyTMXNKvuE8izwNEJUHd6agVhYIne/RJ3IUi4vy1Nq1TkaCxsl0Br6jPQj1WO9L65I/nfG2keCkNmcp/ZzDeROzzj/kxv7jKmdo7lg2RIY/23mMW8dQnTqnLJNYwQb+xdhnJ+Kxk9FrAs6xWo8U3fVq5gXmDnyzOX+6xLJNV4KtZQzPmdkiKWmEYY8Zo4g84m0ObeiAqg2YRj7AJ/nwJXn7o7wf6cvw8fFDqMChe8aXJ1qJyry3g+7eXB/RHL4q3plfnGlmVyduQFQdX65Hcv9rhvJ1iaPTMu+Lxn8HM+ZCyGAe+VUuWfOLVZFmoSyjaghc/zAatBu+AwHD7bQFKRwJ3xLzAfGIK3lfW9uAFZ4n3eu3r8WNQEYE90edUI3HPBRxVZH3kRh4ou3dqg6vM3Oz+XDjvGZ7LCPG5pBosi1mSg7trr02v/gR+hvmxwGj02RE95cmqAyRmar1W13EHCuiBMehmLEEL3TDUHO9vi1rpRuTs69LaenyXU/IIZ5cg/kWTv8TggEMNnGUcgRIEZ+dbL4gOv6UQk8Ts3JcG4Re+fInParEKx17xyMqsfxyOCSXDL5mtwHA163DK3L7zLBnZ9Cci2eXBUEj3tX6d41tBpiRxnIXbtCtX0q7tYqVTTL3+31zk3Cguu1TT01sTG7K7U8QyWf8X9BTroqvY0y3idI/rOVlOGxcAtUnlMfvIMhSiY+HppJumGk+msYExa8RGnoLI4tUBDcNVBDVWY68Kljb4r4LOZhCKcdWN/B4czKYgbaJZLfTK+10SjsznIppmLXXEr3dzK3Zl5a4W6mAZxOPMroLHuCwhOtIksJQnGJYQq4v4LzlonASrmKaExiw57YUqpuQyRFTJRpZkDKUKGeevbSuaubb61O4sJm32Zavtdh4m5jNSRxpZ+DikztNzGXGGbk4lF8V+Jl7V3Wzk04H4L5MfEg5fXDHsH7/0XA3q4L37n0X7RdRFWkP//PC+B2QrPLGq2gXx+Tm8CdBdxwfPWEzXXwxzET7OX7SxlFalegn+mm1KMUVpWuYhlz1pblDLox2ZEbGwyejf+6AUHWbhH8Fc5ZvJJOQFhpZguFHh+8o91itHvjvx44rZzx+0p0USleXESLcRpZfe95JzLW8rcDE2Gr77wn2J+AMQR2XDjob5MrLtTm5d8DC79xrGyrIJcMzaI5MHsn1nclh2lKEpL43MX4y+UzjPU6XMxPhwL/gmjbAC+NWyaAHaW4ZQiLqiOgnxgVAJyP+9UTj7/N3cerxGRrSsAoT4UpHaOeDatEoNpx4ZQrf0tzdHvnPrRJzFrObbHa+s1cEY7sul7XoyfNz2n6o7UJMMYOuCaASXzuwk1A+rsPrvlfTQSIPZyWE/pCRAHQFkiQlO00KqRC+RAFPOmSIFj/UhzQfCPbJvlh3HIpo0RE6qUx/QbRVOVbuo3JHsBo0OrZwvTnyIfa5wRmHv1aG6BegdwIfgLUqBeJzmylV/UrRYKjUxnTrIeApoZvJSTtSj6/eQuArlFzRLNOb4MRKWI9ryZ4loTDbrOpDkH8GIsTpx2ZXyqFtfLPp5wHegFcmS6PLYeCeJ54axXm8zNGB4kRyb4DOlbuFqBJg/DeQi3hrgS+QD7oR56nXd1YnlaC95+aynJ1pybFOjVLQUiWbo08eTxx64TZJcRxjv0DizrGjM9ZpvVLQIdNmeSm3EvMl7xsdm9MGQJe2Fbtshr9swUPVy/Fvdg0COuteQmCJnHIn5ZWqh3NV19sIC6Hm4fMMRmFr9wSA53ySKYmzYgk/vDr0SwTia8jdX+IAD7oZC4pP9L8or8iwK+nKr2OyIaJcQe1qrr+VE5n2Xqq04Q45Z8j/KAvk+w6NRH1yJ+zsIwcs8Bfh9OO0kqhn5RyRTzd1LxO/yWFbgM9hilcZDLDXDfoCWqLB9aUCgr8wjZ5cfdxVY8N/Ne/V+YBAZPLFDvkj4zWLrTuQs+JQurXh9klN/T4Efxh6uqNbnoI260NGk8G8rsFdKWZtSVIU8uMEzIXFjRjWZ0ioiKFmHQ+m+q"
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 1103,
    "candidatesTokenCount": 183,
    "totalTokenCount": 1807,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "IMAGE",
        "tokenCount": 1089
      },
      {
        "modality": "TEXT",
        "tokenCount": 14
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 183
      }
    ],
    "thoughtsTokenCount": 521
  },
  "modelVersion": "gemini-3.5-flash",
  "createTime": "2026-06-08T20:34:56.911323Z",
  "responseId": "cCcnatvPN8e64_UPks6J8A8",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

Generate ContentChat Completions

▶contents\[]

`array`required

▶systemInstruction{}

`object`

▶generationConfig{}

`object`

▶safetySettings\[]

`array`

▶tools\[]

`array`

toolConfig

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶candidates\[]

`array`

▶usageMetadata{}

`object`

modelVersion

`string`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash/#page","headline":"Gemini 3.5 Flash","description":"Gemini 3.5 Flash is Google's fast multimodal model with frontier intelligence, superior search, and grounding capabilities.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Gemini 3.5 Flash-Lite is a low-latency, cost-effective multimodal model optimized for high-throughput, low-cost execution for subagent tasks and document parsing.
title: Gemini 3.5 Flash-Lite
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 3.5 Flash-Lite

Text Generation • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash-lite/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-3.5-flash-lite`

- Third-party

Gemini 3.5 Flash-Lite is a low-latency, cost-effective multimodal model optimized for high-throughput, low-cost execution for subagent tasks and document parsing.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,048,576 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/gemini/) |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.30</li><li>Output (per 1M tokens)$2.50</li><li>Cached input (per 1M tokens)$0.03</li><li>Cache creation (per 1M tokens)$0.03</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-3.5-flash-lite',
  { contents: [{ parts: [{ text: 'What are the three laws of thermodynamics?' }], role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.5-flash-lite",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the three laws of thermodynamics?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
The three laws of thermodynamics are fundamental physical principles that describe how energy behaves in the universe—specifically regarding heat, work, entropy, and the limits of energy transfer. 

Here is a summary of the three laws, along with a "zeroth law" that was established later but is equally fundamental.

---

### The Zeroth Law of Thermodynamics
*(Establishes temperature as a measurable property and defines thermal equilibrium.)*
* **The Law:** If two systems are each in thermal equilibrium with a third system, they are also in thermal equilibrium with each other.
* **Plain English:** If System A is the same temperature as System C, and System B is also the same temperature as System C, then System A and System B are the same temperature. 
* **Why it matters:** This law forms the scientific basis for thermometers.

---

### The First Law of Thermodynamics
*(The Law of Conservation of Energy)*
* **The Law:** Energy cannot be created or destroyed in an isolated system; it can only be changed from one form to another.
* **Plain English:** You can’t get something for nothing. The total amount of energy in the universe remains constant. If a system gains energy, it must come from somewhere else; if it loses energy, it must go somewhere else.
* **Example:** When you drive a car, chemical energy stored in the gasoline is converted into thermal energy (heat) and kinetic energy (motion). No energy is lost, just transformed.

---

### The Second Law of Thermodynamics
*(The Law of Entropy)*
* **The Law:** The total entropy (disorder or randomness) of an isolated system always increases over time. Heat naturally flows from a hotter object to a cooler object, never the reverse spontaneously.
* **Plain English:** Things naturally fall apart, cool down, or become disorganized unless you put work into maintaining them. You cannot convert heat energy into work with 100% efficiency; some energy is always "lost" as unusable waste heat.
* **Example:** A cup of hot coffee left on a table will eventually cool down to room temperature. The reverse—a room-temperature cup of coffee spontaneously absorbing heat from the room to become boiling hot—never happens naturally. 
* **Why it matters:** This law explains why perpetual motion machines are impossible and gives our universe a "direction of time" (often called the "arrow of time").

---

### The Third Law of Thermodynamics
*(The Behavior at Absolute Zero)*
* **The Law:** As the temperature of a system approaches absolute zero ($0\text{ Kelvin}$ or $-273.15^\circ\text{C}$), the entropy of a pure, perfect crystalline substance approaches a minimum value (typically zero).
* **Plain English:** You cannot reach absolute zero. As atoms get colder and colder, they slow down and lose thermal motion, but you can never completely stop molecular motion entirely.
* **Why it matters:** It sets a fundamental lower limit on temperature and helps scientists calculate the absolute entropy of substances.
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "The three laws of thermodynamics are fundamental physical principles that describe how energy behaves in the universe—specifically regarding heat, work, entropy, and the limits of energy transfer. \n\nHere is a summary of the three laws, along with a \"zeroth law\" that was established later but is equally fundamental.\n\n---\n\n### The Zeroth Law of Thermodynamics\n*(Establishes temperature as a measurable property and defines thermal equilibrium.)*\n* **The Law:** If two systems are each in thermal equilibrium with a third system, they are also in thermal equilibrium with each other.\n* **Plain English:** If System A is the same temperature as System C, and System B is also the same temperature as System C, then System A and System B are the same temperature. \n* **Why it matters:** This law forms the scientific basis for thermometers.\n\n---\n\n### The First Law of Thermodynamics\n*(The Law of Conservation of Energy)*\n* **The Law:** Energy cannot be created or destroyed in an isolated system; it can only be changed from one form to another.\n* **Plain English:** You can’t get something for nothing. The total amount of energy in the universe remains constant. If a system gains energy, it must come from somewhere else; if it loses energy, it must go somewhere else.\n* **Example:** When you drive a car, chemical energy stored in the gasoline is converted into thermal energy (heat) and kinetic energy (motion). No energy is lost, just transformed.\n\n---\n\n### The Second Law of Thermodynamics\n*(The Law of Entropy)*\n* **The Law:** The total entropy (disorder or randomness) of an isolated system always increases over time. Heat naturally flows from a hotter object to a cooler object, never the reverse spontaneously.\n* **Plain English:** Things naturally fall apart, cool down, or become disorganized unless you put work into maintaining them. You cannot convert heat energy into work with 100% efficiency; some energy is always \"lost\" as unusable waste heat.\n* **Example:** A cup of hot coffee left on a table will eventually cool down to room temperature. The reverse—a room-temperature cup of coffee spontaneously absorbing heat from the room to become boiling hot—never happens naturally. \n* **Why it matters:** This law explains why perpetual motion machines are impossible and gives our universe a \"direction of time\" (often called the \"arrow of time\").\n\n---\n\n### The Third Law of Thermodynamics\n*(The Behavior at Absolute Zero)*\n* **The Law:** As the temperature of a system approaches absolute zero ($0\\text{ Kelvin}$ or $-273.15^\\circ\\text{C}$), the entropy of a pure, perfect crystalline substance approaches a minimum value (typically zero).\n* **Plain English:** You cannot reach absolute zero. As atoms get colder and colder, they slow down and lose thermal motion, but you can never completely stop molecular motion entirely.\n* **Why it matters:** It sets a fundamental lower limit on temperature and helps scientists calculate the absolute entropy of substances.",
            "thoughtSignature": "AY89a1/ol32QPrMVbKQjdSf9juhARUkac2Z+KPcq5oo84TKrgbEj7WuE+4yuNhidBd0="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 8,
    "candidatesTokenCount": 634,
    "totalTokenCount": 642,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 8
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 634
      }
    ]
  },
  "modelVersion": "gemini-3.5-flash-lite",
  "createTime": "2026-07-21T16:21:55.338444Z",
  "responseId": "o5xfaozUFK2o8sYPiYHy-Ag"
}
```

## Examples

<details>

<summary>**Data Extraction** — Structured data extraction from unstructured text, a common subagent task</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.5-flash-lite',
  {
    contents: [
      {
        parts: [
          {
            text: "Extract the name, email, and phone number from this text as JSON: 'Hi, I'm Jordan Blake, reach me at jordan.blake@example.com or 555-2938.'",
          },
        ],
        role: 'user',
      },
    ],
    generationConfig: { temperature: 0 },
    systemInstruction: {
      parts: [
        {
          text: 'You are a data extraction assistant. Respond with only valid JSON, no extra commentary.',
        },
      ],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.5-flash-lite",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Extract the name, email, and phone number from this text as JSON: '\''Hi, I'\''m Jordan Blake, reach me at jordan.blake@example.com or 555-2938.'\''"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "temperature": 0
    },
    "systemInstruction": {
      "parts": [
        {
          "text": "You are a data extraction assistant. Respond with only valid JSON, no extra commentary."
        }
      ]
    }
  }
}'
```

```
{
  "name": "Jordan Blake",
  "email": "jordan.blake@example.com",
  "phone": "555-2938"
}
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "{\n  \"name\": \"Jordan Blake\",\n  \"email\": \"jordan.blake@example.com\",\n  \"phone\": \"555-2938\"\n}",
            "thoughtSignature": "AY89a1+AejOv/9okEuBeoArPDSAKd5ZcT4tlNk6itaskjb7ezx7K9fEu5NLFUx4iUig="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 63,
    "candidatesTokenCount": 43,
    "totalTokenCount": 106,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 63
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 43
      }
    ]
  },
  "modelVersion": "gemini-3.5-flash-lite",
  "createTime": "2026-07-21T16:21:57.867550Z",
  "responseId": "pZxfat75NIvG8sYP3dfakAo"
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a short conversation with low-latency, high-throughput responses</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.5-flash-lite',
  {
    contents: [
      {
        parts: [
          {
            text: 'Summarize this in one sentence: The meeting covered Q3 budget overruns, a proposed hiring freeze, and a plan to renegotiate vendor contracts.',
          },
        ],
        role: 'user',
      },
      {
        parts: [
          {
            text: 'The meeting addressed Q3 budget overruns by proposing a hiring freeze and vendor contract renegotiations.',
          },
        ],
        role: 'model',
      },
      { parts: [{ text: 'Now make it even shorter, under 10 words.' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 512 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.5-flash-lite",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Summarize this in one sentence: The meeting covered Q3 budget overruns, a proposed hiring freeze, and a plan to renegotiate vendor contracts."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "The meeting addressed Q3 budget overruns by proposing a hiring freeze and vendor contract renegotiations."
          }
        ],
        "role": "model"
      },
      {
        "parts": [
          {
            "text": "Now make it even shorter, under 10 words."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 512
    }
  }
}'
```

```
Addressing Q3 budget overruns, hiring freezes, and vendor contracts.
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Addressing Q3 budget overruns, hiring freezes, and vendor contracts.",
            "thoughtSignature": "AY89a1/dUv1ajorDdpZkOzaeL0fb5CjoZL4SoKtpQeX8AK5jF5vNa/v4F6r7OqdabWs="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 61,
    "candidatesTokenCount": 14,
    "totalTokenCount": 75,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 61
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 14
      }
    ]
  },
  "modelVersion": "gemini-3.5-flash-lite",
  "createTime": "2026-07-21T16:21:58.695703Z",
  "responseId": "ppxfape7KqSn8sYPpMq_gQ8"
}
```

</details>

## Parameters

Schema variant

Generate ContentChat Completions

▶contents\[]

`array`required

▶systemInstruction{}

`object`

▶generationConfig{}

`object`

▶safetySettings\[]

`array`

▶tools\[]

`array`

toolConfig

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶candidates\[]

`array`

▶usageMetadata{}

`object`

modelVersion

`string`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash-lite/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash-lite/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash-lite/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash-lite/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash-lite/#page","headline":"Gemini 3.5 Flash-Lite","description":"Gemini 3.5 Flash-Lite is a low-latency, cost-effective multimodal model optimized for high-throughput, low-cost execution for subagent tasks and document parsing.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.5-flash-lite/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Gemini 3.6 Flash provides sustained frontier-level intelligence optimized for real-world tasks at a higher speed and lower cost, excelling at code generation, agentic execution, and spatial reasoning.
title: Gemini 3.6 Flash
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 3.6 Flash

Text Generation • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-3.6-flash/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-3.6-flash`

- Third-party

Gemini 3.6 Flash provides sustained frontier-level intelligence optimized for real-world tasks at a higher speed and lower cost, excelling at code generation, agentic execution, and spatial reasoning.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,048,576 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/gemini/) |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$1.50</li><li>Output (per 1M tokens)$7.50</li><li>Cached input (per 1M tokens)$0.15</li><li>Cache creation (per 1M tokens)$1.50</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-3.6-flash',
  { contents: [{ parts: [{ text: 'What are the three laws of thermodynamics?' }], role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.6-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the three laws of thermodynamics?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
Although historically there are **three main laws of thermodynamics**, a foundational law was added later and named the "Zeroth Law." Therefore, physics actually recognizes **four laws** that govern how energy, heat, and work behave. 

Here is a breakdown of all of them, starting with the classic three, followed by the foundational Zeroth Law:

---

### 1. The First Law: Conservation of Energy
> **"Energy cannot be created or destroyed; it can only change forms."**

* **What it means:** The total amount of energy in an isolated system remains constant. You can convert thermal energy (heat) into mechanical energy (work), or chemical energy into electrical energy, but you can never end up with more energy than you started with.
* **Example:** In a car engine, the chemical energy in gasoline is converted into thermal energy (heat) through burning, which is then converted into mechanical energy (moving the car) and sound energy.

---

### 2. The Second Law: The Law of Entropy
> **"The total entropy (disorder) of an isolated system always increases over time."**

* **What it means:** Natural processes move toward disorder and randomness. This law explains the "arrow of time"—why processes are irreversible. It also dictates that heat will **always flow spontaneously from hotter objects to colder ones**, never the reverse, unless external work is applied.
* **Example:** If you drop an ice cube into a hot cup of coffee, the ice melts and the coffee cools down until they reach the same temperature. You will never see a lukewarm cup of coffee spontaneously separate into boiling liquid and an ice cube.

---

### 3. The Third Law: Absolute Zero
> **"As a system approaches absolute zero, its entropy approaches a constant minimum."**

* **What it means:** Absolute zero ($0\text{ Kelvin}$, or $-273.15^\circ\text{C}$ / $-459.67^\circ\text{F}$) is the theoretical temperature where all atomic motion completely stops. The third law states that a perfect, pure crystal at absolute zero has zero entropy (perfect order). Furthermore, it is physically impossible to actually reach absolute zero in a finite number of steps.
* **Example:** As you cool matter down closer and closer to absolute zero, its atoms slow down and become extremely organized, but you can never completely strip away all kinetic energy.

---

### Bonus: The Zeroth Law (Thermal Equilibrium)
*(Formulated after the First and Second laws, but deemed so fundamental it was placed "before" them)*

> **"If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other."**

* **What it means:** If Object A is the same temperature as Object B, and Object B is the same temperature as Object C, then Object A and Object C must also be the same temperature ($A = B$ and $B = C \implies A = C$). 
* **Why it matters:** This law gives us a practical definition of **temperature** and allows us to use thermometers.

---

### Summary Analogy (The "Game of Thermodynamics")
A famous, humorous way to remember these laws is:

* **Zeroth Law:** You have to play the game.
* **First Law:** You can't win; you can only break even (you can't get more energy out than you put in).
* **Second Law:** You can't even break even (because of entropy, you always lose some usable energy as waste heat).
* **Third Law:** You can't quit the game (you can never reach absolute zero).
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Although historically there are **three main laws of thermodynamics**, a foundational law was added later and named the \"Zeroth Law.\" Therefore, physics actually recognizes **four laws** that govern how energy, heat, and work behave. \n\nHere is a breakdown of all of them, starting with the classic three, followed by the foundational Zeroth Law:\n\n---\n\n### 1. The First Law: Conservation of Energy\n> **\"Energy cannot be created or destroyed; it can only change forms.\"**\n\n* **What it means:** The total amount of energy in an isolated system remains constant. You can convert thermal energy (heat) into mechanical energy (work), or chemical energy into electrical energy, but you can never end up with more energy than you started with.\n* **Example:** In a car engine, the chemical energy in gasoline is converted into thermal energy (heat) through burning, which is then converted into mechanical energy (moving the car) and sound energy.\n\n---\n\n### 2. The Second Law: The Law of Entropy\n> **\"The total entropy (disorder) of an isolated system always increases over time.\"**\n\n* **What it means:** Natural processes move toward disorder and randomness. This law explains the \"arrow of time\"—why processes are irreversible. It also dictates that heat will **always flow spontaneously from hotter objects to colder ones**, never the reverse, unless external work is applied.\n* **Example:** If you drop an ice cube into a hot cup of coffee, the ice melts and the coffee cools down until they reach the same temperature. You will never see a lukewarm cup of coffee spontaneously separate into boiling liquid and an ice cube.\n\n---\n\n### 3. The Third Law: Absolute Zero\n> **\"As a system approaches absolute zero, its entropy approaches a constant minimum.\"**\n\n* **What it means:** Absolute zero ($0\\text{ Kelvin}$, or $-273.15^\\circ\\text{C}$ / $-459.67^\\circ\\text{F}$) is the theoretical temperature where all atomic motion completely stops. The third law states that a perfect, pure crystal at absolute zero has zero entropy (perfect order). Furthermore, it is physically impossible to actually reach absolute zero in a finite number of steps.\n* **Example:** As you cool matter down closer and closer to absolute zero, its atoms slow down and become extremely organized, but you can never completely strip away all kinetic energy.\n\n---\n\n### Bonus: The Zeroth Law (Thermal Equilibrium)\n*(Formulated after the First and Second laws, but deemed so fundamental it was placed \"before\" them)*\n\n> **\"If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.\"**\n\n* **What it means:** If Object A is the same temperature as Object B, and Object B is the same temperature as Object C, then Object A and Object C must also be the same temperature ($A = B$ and $B = C \\implies A = C$). \n* **Why it matters:** This law gives us a practical definition of **temperature** and allows us to use thermometers.\n\n---\n\n### Summary Analogy (The \"Game of Thermodynamics\")\nA famous, humorous way to remember these laws is:\n\n* **Zeroth Law:** You have to play the game.\n* **First Law:** You can't win; you can only break even (you can't get more energy out than you put in).\n* **Second Law:** You can't even break even (because of entropy, you always lose some usable energy as waste heat).\n* **Third Law:** You can't quit the game (you can never reach absolute zero).",
            "thoughtSignature": "AY89a1/ETDBr0NG2TxxpkIfwxONbRoRzInG6WZbfIclPMB0UlgRCQ0iwDy1zt7bN/l9UhNohgkU39x70015xk3dRIC0CDbuO/HNEwpBqG8HCOYpgWj+28bGQga7K4CGLPQDI5adByEMUCBwP/SDtQX7gmZln/ZaHpgAqBREo9QNhs8mEi4EMMnXE3fQeEF/uNQKLsA9PAaQcyhGh+lEjpne5Xs472y70q0xR4LWWm2YEQiO2gCO3iROcaX7h56xmH2CYzZKInpOE9ET00rvMS/IbT3ypGSww46kgS8JN22pNTo9z3Jg9/0HmBEzVFD1C7oaU44kH3PTmHYT8gQCnKGfgLpMNlCRc0JqtmCVsU90FPp5skxYn1AuAGOjqA8Fe6uwJPG0djtQHIhtsVzK3KJ93W088D1bui4h14sc96epwc5adns4HKjYrq/xvzkKH23aOHMscDToWZi4VU4j+xq6ywG6koLCaDZSorJVYw3xFZwG5O6GRf9gsmICK/Ye6kKPtuj84j2jyJvrdPTaOMHDyo7jrKESdxDvCQL05+4VaAEnW3qqmnQ8smYXYV9tpX5avZxx0ut6x8kLiuh8Ely4XWT6YOCJoEVIpllJtDLbCFmoQ4YVu1NMs/QwTm1TMA1EmFji65T3rZB0zM/8bseaZGjSlV8HZTwaJPRWS6ExZ//4wtsCaFLuWudZeYNLzXheDJEllstJgZxqMfY+9iVU6sStwRIKj2Pi6F1V4+BdgA6GaTo1xgXntuZFZ/abbvfrSH/emAPScYPXBnu6sz3Nh8diwNrq+ZiCo77d8551pKnFqFulDNWVfF3L2N0I8IuAZvYpRd8hOoTQ7FrU5sTlEqDGo7XWe11MYLsE9bBMKYa/2sKg5fGDW4sBK5ND8g2tUonh2drGYvXriSmBlB4zhQ9+bruhIZV2ti8kO1JiiNZJf+zYHwMcwC86XuYajREjy54uQQ0QZuLJUDurWZanU+MF6hKWxJHaw+LvvtTufoZPqOUoWUHIyepzG3sJ34/+v2ZHMrwJhRwDXtY1l+ztzIOWdeGsV9DIdAqWP9aoSHK2lYkbeDFc8eQWNEgb6UHtGJBszUr1ZWC0TRbNqhg/+lgBmPoK3IE3/OGUxYzCxPus7TCyE1oEIOStk7bClU8sX0TnIDu6DyiXu1pyGiFJLKYO4A4N8sq+J6/i5wikfX3ythECewwQbQ3qtMsaPixnbWotiDLo3uns3dSXS4FW1isyqiMYV83DolBQwCT2LPomv+8hQDYiTmhhm3G7jr9qMyFTxmHDA8KZNQqki+rOCyX92PwNIRjbCRgQyCzP5JWmx8hiSq38FmwLOcMZr7JGd9NPo3PnU5QzqN3ruM1RpvHhXMhe7/44iUrFDvqQO6eot9JmZNAMIsvbFHGyaLd/TQUzPKqAv92P7fZSVbFZoj9irsA0uvbOF3cWwGRH4JtQ9nIJzQj+XfBFknk7DjNUUd65wT0ObsUWgZs21gWSy/vqSpW/z9e9bHBJvEhYtbyJmd9WKthAcuxhUAZnzLtS3etB0aDopLnScLPddFWogTdJORZM62H4h+0Kj38bHCcOYPHkDb+iQTCDiqHlPz4xS27+TwG0K57IFx9ytXYbgio8tgLURmw+Nc/v7rKJZan5B/RsptgEV1lTpQO0DTeN/V2CvCBuqlbMUagQT1FrIBORrQcQaqQCTeFDmfk4SdzAMNexn49pz5Oj/8BdOSwxbpxMeMf6O1PvGbR67QLBCFDmPXzdNZBgpHce9TikI6CfhAZCYY8g56AT/dk77kc5I03CYVGDHOHnR/eICHN3Kh56xO/d0dEEy/w/yzcky4rZ5xT33W3rHpLb+U5U0cUpRckDr3I5Gj5b9q+AXbm1U6DIjB6dl4+jXG8naJagGdec0VLURI3zVuwv9I71u9qAZ/d+/8RXlJQk7pLnxngd93vyBDLeeWZfunI/AqH+sUfUDaGvdHaNaAvMc7LQisep29QbEhp90T6VaGgS1j1ZWkZLv+eP2tl/FbsK9PX1vsjuPBJGJa3vrC6mB/3qDDhs+Ffv+ymnnD/Y2JJiEY9sGKENEpX/0s5kuyWkE5Ez/PNSrcB1SuyE/0MwlELdoKkOdOL2wkyrqDKCK5inUbH3QDzD+jKxQzgRQbthnKblQufbAiBNUasW0n6aIHgtXR7sDGqGirAao+d/WDP4ZtccZKhvpzy0s87yrHc304m6wrSE9YucCNvkwFUL8iXeb/L6Mk5a78Lpx1cVNuqZ0Gek6mh6/Bc24+q5drDRycuWzc770pNRx7czUPw3sElTXb0/KPoz3kzrHPJv5IdVwrEgfKkPwZ9iz75q3FiU6EhPf/7GhfgQaw4vhChxuiwm4pJViI2qSMFJuMAWRznDVJ63A20mB9k39ZuV74Qxg+m8MUhxgPvPlCAmWsMLeCKDiyh0WVr2PAayMw+Q6WDhUp5qetpTjD5U9I0BEtff450VvIKUkZ/LF55qS3leQ4cTrpSnXitETP3vyLokMpN2qvBK9Xlfa+uCuUf3H+A9Kl8gc1lRV9EujJuecbz61YtBut6lMMP/9OVSCiegHELWG2ysWMkdw1JxIcqSbRmufRJh3IC1Q4uZLzDkq/hDgqNibmcyR8hLfQhqk/lGYuSCbnwOWkiVggbminIO4g8c6g9yAptjl08Ha6AOZXeLGnXGzOVafJy7nt46SJwaaTmjyZBL7Sq7NsPtoxlc75yqd6jgGGn/8xXZti65plS/OG3IcefHBe7Yeiu5kvk4zCRcHb+jFr1TkzpyRRDnhijHL0Z/L4axP8LM3a2IrdauI5cfXgUFNVje/rLK7WVyGXf0jYZ/FRm4OUj/eGj8DT+dXO481mR9qIIoDSq53TO1HWf7OrEmt6LC4SBnWkMntRDE4WornvtPBxLLjjiDlhAPDWmBsbLERG6Y7YQXaiEpfQO85KE+RumbaG6ESV7FYrrSac+nJJA0SOcxing8OfReWWNGMW579O7R5/2JFNtnZPWcPRiPSp0NTGmULmDZHhWNhlrArNTyeR9XMlkWH5xSiCkwUrFLYmSEkaLdM1qG0pPuSYRAmaGuHqMdHHeb0BcEQdU8g/lSBu+Ysb5ubul6ZAYQCXWgLiaYOpTZcY+Pjs8WnIxlo8hoC+pDt0kx30Voge/nwWrbNED5jCkdF7MhioYo+Soz1o6mbQJJR0BMNgTbF1jWjx4xhnZnqs7x6eZWR51UXUX5TebkiLDdrEGt/Bn5ICwmuhgVlaIcP/Yc7dlsz3CBDhMbWXbYzQP33XFSJXjunB5G/fRrALGgswVEfXVvwZM3wCMUVaLeVwTKtxoQ2tRtSe+UwrKnaEohj8PKSvxa+RQKLsLZN/Mzumm8KhqQcnpcjJtQjn1Q7ezuTNa5rbvXliuqglOuFvA6tpEE7KJupFRVQK9D8h/wAHdmrRmk6IX8sihNbtKnuxomss52qJbx64eqMKWxm0vQztJJBWyR8ejeMCw9h7X+cfqKihr4R//GtMqG0z4EpaAPeEdeZHZNHAL4dzzZrFb3q7kSQuGwjabA5DX7yr0TI9BStAGhzEGNvOwDITTrS6En7Qn06UWblRC3WQbhC+zESmOfhrPxf408xfrybhqHjVxP0P1kydhdFGAkh2UVD7nwvHtKK9u25IpXhjwTQ9bS0OAQP2m6jCIc4o8ro/3bxr94I/TeSP1xS2ERvHMKzH2jnroX72SvjfsfCaFg9hLsW5oFuFEnkvTDUY+6F8S/88xNRnU4cDHfaJT7xqST5H/q0ByMZWPbXphbD7cVIyG9pYvdTnXzVFs0b3eruAr8Ofj2ZLKElw76tMCOOOtvX+UfM8yZfUesvAy/t35mvp7NdIMtwPXthyNO9mqwatkRghA2gR/Y+FQOJ1OuNIwG4T1BmDfZBtVsj+SRAuto1Gq2dtmc1nI1yeQs+ApbuSSaPNNnWMdWgJiPjgT56dYQj4uoirdhYAegHO85tR3Mrz55QH6Lsz8SS8faoEEEftUBEiAwGwY4V22oZHo7CG2hsRAJawN/D5z/iNmRehvJx268tfTAQDjipEmt7SZTsO1mLRSOmmJKzIxduQVugodGFRwjZ0TFwgyoBZucqERARjeI2kI2j2ZEmcJjEgI4sIxiRrkaqYPemY/wPBZ+b7HY8VY0OzApHTHko+fuEljM857rDL2dIc6LImZTPGXMJWhlBxc3GY/HiVLqr6Mch6VAj6mvVj4La+Lt57vgTUk7hnoozEJauOmk7lm8NNR3RfDq6bwGoo7Z8pGIQobfbnS8aQLv/dRjWPLMIvm2uhsP2dvqZjtPtaawN4G3STkYR50a9cw3f+DBJDFoQZ5BQJ3M/J9z0nGDU14AFaqIiY70FexApNUQHx5F9l+VX
... response truncated ...
```

## Examples

<details>

<summary>**With System Instruction** — Using a system instruction to set an agentic coding persona</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.6-flash',
  {
    contents: [
      {
        parts: [
          { text: 'Write a Python function that merges two sorted lists into one sorted list.' },
        ],
        role: 'user',
      },
    ],
    generationConfig: { temperature: 0.2 },
    systemInstruction: {
      parts: [
        {
          text: 'You are an expert software engineering agent. Write concise, correct, well-documented code.',
        },
      ],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.6-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a Python function that merges two sorted lists into one sorted list."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "temperature": 0.2
    },
    "systemInstruction": {
      "parts": [
        {
          "text": "You are an expert software engineering agent. Write concise, correct, well-documented code."
        }
      ]
    }
  }
}'
```

````
Here is the standard two-pointer implementation, which achieves optimal **$O(n + m)$** time complexity and **$O(n + m)$** space complexity.

```python
def merge_sorted_lists(list1: list, list2: list) -> list:
    """Merges two pre-sorted lists into a single sorted list.

    Args:
        list1: A sorted list of elements.
        list2: A sorted list of elements.

    Returns:
        A new sorted list containing all elements from list1 and list2.
    """
    merged = []
    i, j = 0, 0
    len1, len2 = len(list1), len(list2)

    # Compare elements from both lists and append the smaller one
    while i < len1 and j < len2:
        if list1[i] <= list2[j]:
            merged.append(list1[i])
            i += 1
        else:
            merged.append(list2[j])
            j += 1

    # Append any remaining elements from either list
    merged.extend(list1[i:])
    merged.extend(list2[j:])

    return merged


# Example Usage:
if __name__ == "__main__":
    a = [1, 3, 5, 7]
    b = [2, 4, 6, 8, 9, 10]
    result = merge_sorted_lists(a, b)
    print(result)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```

### Python Standard Library Alternative
If you prefer using Python's built-in libraries, you can use `heapq.merge`, which returns an iterator and avoids loading everything into memory at once:

```python
import heapq


def merge_sorted_lists_heapq(list1: list, list2: list) -> list:
    return list(heapq.merge(list1, list2))
```
````

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Here is the standard two-pointer implementation, which achieves optimal **$O(n + m)$** time complexity and **$O(n + m)$** space complexity.\n\n```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n    \"\"\"Merges two pre-sorted lists into a single sorted list.\n\n    Args:\n        list1: A sorted list of elements.\n        list2: A sorted list of elements.\n\n    Returns:\n        A new sorted list containing all elements from list1 and list2.\n    \"\"\"\n    merged = []\n    i, j = 0, 0\n    len1, len2 = len(list1), len(list2)\n\n    # Compare elements from both lists and append the smaller one\n    while i < len1 and j < len2:\n        if list1[i] <= list2[j]:\n            merged.append(list1[i])\n            i += 1\n        else:\n            merged.append(list2[j])\n            j += 1\n\n    # Append any remaining elements from either list\n    merged.extend(list1[i:])\n    merged.extend(list2[j:])\n\n    return merged\n\n\n# Example Usage:\nif __name__ == \"__main__\":\n    a = [1, 3, 5, 7]\n    b = [2, 4, 6, 8, 9, 10]\n    result = merge_sorted_lists(a, b)\n    print(result)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n```\n\n### Python Standard Library Alternative\nIf you prefer using Python's built-in libraries, you can use `heapq.merge`, which returns an iterator and avoids loading everything into memory at once:\n\n```python\nimport heapq\n\n\ndef merge_sorted_lists_heapq(list1: list, list2: list) -> list:\n    return list(heapq.merge(list1, list2))\n```",
            "thoughtSignature": "AY89a1+jl1yZgJ6QPBiWalH+ch0D5pt803+N0bNcmdWGazGtevbVVwWDy1AHvZ4ImV+aquNL8lkZ+mtNdiDucobOv4RjR4ClQIHyLzCKBR3TZf9EZ7BGUKWqP78+tj6FniQQIYHtLxZklxRb/RN8frqJFyXnzssMqVWTP6Uu46vkA3+UfciHSB5SeeisppUX4l8REm0X5I0U5rnlzIJmyIMZwoL7W5VbYVj41iPLrLQgyWZf3ZozW8xbJw+XC2B6aIjV0Qke+OUtCx/evygP9s1NtVgtUOS+LY2urxgDrnOWaT26eTxDpFkCTUEr+uKmRlGtE19HJaUfOguIjUMj+290pzvWzicmMUD2nmSItC28o1W3oozLw+hfItH65zcN+CYzMvLLl2B4LWafa1L8frmlGbezubG2B8/CEB92CfrAzJIKREf5BYe3epbOGH3wfcwpcAX2zM+1zbi1xgP1n9h5yF0bURyRHm0UkWkaqbPFpfWZcqn2BRo5pMQ1Pkc0suBGn+LlmsO+4fKSfQGbirEqDef2mdwso99VXerl0UJJyKnmRtX4cnA/4J2xwSTce44zNueff3LXExzMzWTHyUGyaZPAX99AOPVJ0nFYdjQUeCGfIpoyFmFcacuOakTwruIGwTjXS4U1J83+1YmCi+UQ9P2JFxBeBUB42hPJZ8R2aK7SJt2xuTnoXizyD7aUWUj05FdFIGE9VaopiFV+HwtDefFIqYZ6xS7pXixkXIaUpYWmBF4t9XkeC/t82NVslU6KgMB73ehCOj6FoUgwT47JOfhQQuNTlN2nRkwWyRZ2rYlS4OLczNwAKZYgkD7ddFE3hD5zBJpc9nYkbky/QQTRVJ15SrWp8NhUc+6a4DhoHZZRaL/g6oE/gJjEMJl4v8xNMAcWXkGKHarDKrQzxvlzzS+nuQMNYU843XlDOWk00NFmLEp75l9mv03NHW1cxJuxDjLxu7jo3m72CSh+gezunoNAgTdUmg3OMfbBIAVvO6Hq+nvw5elfEtraF/KJ0vGQ+a2SI5LMvVG7YKaS0fSvrcKu1K4xHmdo6JSoYcYdOnyX04wJxcov/wAdhUCjnlsljwnikKBLSd74arcHmFwD7du0uhZXAEwmUE6Wi0ERFB/1WjUWxT9H6y2LaNpomS2qPQdjFlXsdt3uzuyrr2k18hrwte5CRtG9c90/9JLDhVDsWgiIXi31i275Y3xy6tZSK2oe2OSGykLhllGjQbT2jguC093IWQfS0TFsVposO6qgYXk+35ZQ0MDq4nD1iXyRB4yscIFvtcs8yX0UGM89aYr/hheIziGnA0ehx9ZG4pLNdC88AOhUypLn38f8xau9A5K57Z50Tn6/57MsV7nACruho3sgU8VHXcv+GI+XOwFqOxAHMuCWAZknUtEAdFTFvmVnb+Q6X0FXrMOyvOHy2mZ3nCpDY9BFnJVviNnns8owQp2klh1vgIW5iREK+rNMHDhaYsH/6oVz+HFzlT/MiBi7e95TUUapc2/Vldc9ITuf+1RfHpgMlQZrBlwrBXPYRou5Ut3vwmX4KlKRgyARjfSoFdxLclRzEk+S0Xc3gtxF61y/1hfapteTeNHPGo0r7tYz4hv5bdfw3/IqfDGGrUzoWYWJ00zExpd/LjVk5dmK7WFD5lmMmpkiPLSIxs2NGVwMZKlvZ/tbhq0er57aMUJeRRBA0XVCGXstNMxs/baPqSYwqZQsgSmPIph1pNsF+WPDTEE9UEzVq+e/1SfJrKaM7JLPYm+d0jgzJktY9jYlGgPLAPTIZqcEwo8IoJdX1hf27iqLJ6gAQDhqaH9MuxS7FSOnRe77ltdXdCSjxXPNcg8o+F1DkBvXD9LnAB8ny6sR+QjWKr2Wwwg8ElMLc9lGZhl7IIL6X4fT68zJ5hbmtn7ljXPv3Icb2H5sYoytSiJ8LyjzrfjSbjqIV/nKUIGAYY6Kg4+dQW3PsEhWRWe5Sr4H+gRq2pCf3xuz5JaqeVo2XRu0j8SCddPF36a9aHVDe57kT5CIOs7EnCMNOspHYhdgLOzstLOIn6VTK6/PeYaUS8yPACRiszWtlk3Q2jQySkr29Zf+If1kVcOaV8MdF6hIdhNmDav+9cby3rZTKUqiS+QN2jT047fQn5K9TNv/Axs9znr1DgaHm2f6cjg6oOp30D1ku25QTq9FcBuIZ/npyzk2C8WsTPBwWQ3FWRQPHQ8nHN4/DySC4ffAgXJczhs70NZVChc92xNSuWU4BR/iSYSke0oPnX4dprIMxz87jJ1ALYvpuN0KEIkZplX+fHjrm8aSHKgfOf7aCjp3ZmhDBCJVLnXjy28xDhtvhnEylrrjJlX6KHR5B88KNr4PTep8MjRZtlGnGjhrvCPuxu4ImkMlprfyf6W+dpw5S32Rxfr/QvS2psLLKeSBZfYxqjr3eXTT7f59Djg="
          }
        ]
      },
      "finishReason": "STOP",
      "citationMetadata": {
        "citations": [
          {
            "startIndex": 640,
            "endIndex": 961,
            "uri": "https://github.com/s-m-quadri/geca-labs"
          }
        ]
      }
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 32,
    "candidatesTokenCount": 472,
    "totalTokenCount": 988,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 32
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 472
      }
    ],
    "thoughtsTokenCount": 484
  },
  "modelVersion": "gemini-3.6-flash",
  "createTime": "2026-07-21T16:21:23.639338Z",
  "responseId": "g5xfauqCJ-2r8sYPq8XmoQg"
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a multi-step coding conversation, typical of an agentic loop</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.6-flash',
  {
    contents: [
      {
        parts: [{ text: 'I have a bug where my recursive fibonacci function is too slow for n=40.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "That's expected with naive recursion since it recomputes overlapping subproblems exponentially. You can fix it with memoization or an iterative approach. Which would you like to see?",
          },
        ],
        role: 'model',
      },
      { parts: [{ text: 'Show me the memoized version.' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 2048 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.6-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I have a bug where my recursive fibonacci function is too slow for n=40."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "That'\''s expected with naive recursion since it recomputes overlapping subproblems exponentially. You can fix it with memoization or an iterative approach. Which would you like to see?"
          }
        ],
        "role": "model"
      },
      {
        "parts": [
          {
            "text": "Show me the memoized version."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 2048
    }
  }
}'
```

````
Here is how to optimize your recursive Fibonacci function using **memoization**. 

Memoization stores the results of expensive function calls in a cache (like a dictionary or map) so you don't recompute the same values over and over. This reduces the time complexity from **$O(2^n)$** (exponential) to **$O(n)$** (linear).

---

### Python Example

#### Option 1: Manual Cache (Shows how it works under the hood)
```python
def fib(n, memo={}):
    # 1. Check if the result is already in the cache
    if n in memo:
        return memo[n]

    # 2. Base cases
    if n <= 0:
        return 0
    if n == 1:
        return 1

    # 3. Compute and store in cache before returning
    memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
    return memo[n]


# Test
print(fib(40))  # Returns 102334155 instantly
```

#### Option 2: Python's Built-in `@lru_cache` (Cleanest)
If you are using Python, you don't even need to modify your function logic—just add a decorator:

```python
from functools import lru_cache


# maxsize=None allows the cache to grow indefinitely
@lru_cache(maxsize=None)
def fib(n):
    if n <= 0:
        return 0
    if n == 1:
        return 1

    return fib(n - 1) + fib(n - 2)


print(fib(40))  # Instantly computes
```

---

### JavaScript Example

```javascript
function fib(n, memo = {}) {
    // 1. Check cache
    if (n in memo) return memo[n];
    
    // 2. Base cases
    if (n <= 0) return 0;
    if (n === 1) return 1;

    // 3. Compute and store
    memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
    return memo[n];
}

console.log(fib(40)); // 102334155
```

---

### What changed?
* **Without Memoization ($n=40$):** Takes roughly **1.1 trillion function calls**, taking minutes or hours to finish.
* **With Memoization ($n=40$):** Takes only **40 function calls**, finishing in less than a millisecond.

*(Let me know if you need this written in a different programming language like C++, Java, or Rust!)*
````

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Here is how to optimize your recursive Fibonacci function using **memoization**. \n\nMemoization stores the results of expensive function calls in a cache (like a dictionary or map) so you don't recompute the same values over and over. This reduces the time complexity from **$O(2^n)$** (exponential) to **$O(n)$** (linear).\n\n---\n\n### Python Example\n\n#### Option 1: Manual Cache (Shows how it works under the hood)\n```python\ndef fib(n, memo={}):\n    # 1. Check if the result is already in the cache\n    if n in memo:\n        return memo[n]\n\n    # 2. Base cases\n    if n <= 0:\n        return 0\n    if n == 1:\n        return 1\n\n    # 3. Compute and store in cache before returning\n    memo[n] = fib(n - 1, memo) + fib(n - 2, memo)\n    return memo[n]\n\n\n# Test\nprint(fib(40))  # Returns 102334155 instantly\n```\n\n#### Option 2: Python's Built-in `@lru_cache` (Cleanest)\nIf you are using Python, you don't even need to modify your function logic—just add a decorator:\n\n```python\nfrom functools import lru_cache\n\n\n# maxsize=None allows the cache to grow indefinitely\n@lru_cache(maxsize=None)\ndef fib(n):\n    if n <= 0:\n        return 0\n    if n == 1:\n        return 1\n\n    return fib(n - 1) + fib(n - 2)\n\n\nprint(fib(40))  # Instantly computes\n```\n\n---\n\n### JavaScript Example\n\n```javascript\nfunction fib(n, memo = {}) {\n    // 1. Check cache\n    if (n in memo) return memo[n];\n    \n    // 2. Base cases\n    if (n <= 0) return 0;\n    if (n === 1) return 1;\n\n    // 3. Compute and store\n    memo[n] = fib(n - 1, memo) + fib(n - 2, memo);\n    return memo[n];\n}\n\nconsole.log(fib(40)); // 102334155\n```\n\n---\n\n### What changed?\n* **Without Memoization ($n=40$):** Takes roughly **1.1 trillion function calls**, taking minutes or hours to finish.\n* **With Memoization ($n=40$):** Takes only **40 function calls**, finishing in less than a millisecond.\n\n*(Let me know if you need this written in a different programming language like C++, Java, or Rust!)*",
            "thoughtSignature": "AY89a1+ctnO9pFN+e7hgW0eZao5X3ew4AhkhyjLFp8H/8277YIUwpU9afhv8Sqb+P9/tYhd+SuWIOyutodLO4F8akA+FkY8qD1Ib3js3+4tcLU9L1gxGKG+/EBA6Hdgh5EBtyf4/1KqsMTAsnPwV0UTF/HRo64vqoyXoX8FBnKiXYLsYDmnBXNMPSudVsSDuuPUOdQM9Siig8F7jLArxYFvDSeQcEgKw3PnAXMLFD3rHiNsAglqZvtsue/04p6JG/LwAswI0GOCXvt9T1iknzVFIAISWkGymKs+jSNF9uwRzcbmDcndEntX4pbKlOBztkB5Eo0m2zw+VecVXy/cScmGCQYUNONikvTWU7MeUlYWRYbLbN/v5GHpFn5nbgVtHzpQpdPhUJEJP6z8fVuRtx3UQOxGSHmpG3xNCDaWDuJEvk2qjBqW8lguRpFZIDO516CV8etHYCi53MkDMZPv8JGWy1+wkqu4/6TyKtG+O3q3NUx2OBQwsUYzfIl+487pmJ/2XtF3mq4eoL4HaXJ+lXBNfjDzJRuj8NyQuG/5yUFpzpAEllh3RoqplDYexbO9LhelfudqAUSiqsRS9yxHZZBMSEoVjpKBlLp5j5wCq5gNDR3MvdqOps4GR91jDiKfF1BWEh3m2x7XV6+L2NNi9KPP1hZBmTExR3W1OXeKpUJLr8t5ROT0650xPAj3Ch2cDzHAEBo67ScwwVUEt8zXRx67p5nmT8GT8IMuzqulPj33Kk/XGmBJ6xoHwgivUPhs2ZPjlV0oDVRRcXUdQkb3yBQMgPmrTK/yE96TIzLaY02f2X7RIpeG+aNi+WSd6DNHGadLXPV2+UbP6mE+0eGj/1eZiyHdH4uANyjIZ5vRQYrsq4R6WC4LWS2a7ClFIcEQOXNTe5YcdqgFc4D+XLubk7SwIGlaIvAAN3UgaPxphDcw0ci0GLKN5NWikEj5y05JnAP0k70I7eNDcvwC8utNX9nNYRdzvJm5tEVjhNhYFmLjtpi3ca8w0wlE+WK1qA+ILYaO5qrvjNm2jFllqRKdBE1i2glFTNZO+dNL43bTgydtXjjrWpFqFFTnx9mP8NLWV/6nA4XdE+JfQA4CQ3JHy6vJAJPbh5cEmS/FRreFwNfS8U6wGaNx3VioqLDnVf9aI0edEEI4m0f7XWsT9dkdWxThfycC95HSFkX9jvUpv5e4dqzNo8bccenbE++4M4qhiqFL9SP5Ov6arYpl33P4rTEDGOHWHIlzupvM5EJ1IkppuSjh2UQm/PtAgHxxuE68riJ3YgbVvY5J7BekLtQMOzvLuEGFU3VGa2ArMs/dtHsfYygv3Nlrzs4IwOKuMo4V0mXYpsKxDckn/Yu3eSxgZzALRcU3Vytm+g6Mutzc5fvZCi4kDVKlW2yDrGFtTk1v116ggtQDPwREyI4+DzO7Cl8NqIZPgvM0NLnuZgNAgF4mABtf6FaTe/C8I9sHYzYVFOft3h1BN993hcAUpJW2aJHYaIChCNKUKBbX7f5nCUtgZ93NhUedLiDnOasVZB9xeR30wWglInifB77Q2Ue1QGXrBlPWyolODYjOcg4ZG42eI80sb5lAojzh3dtfGcf7AUfnNnHWV5dlSVa4uvZw1FF+RyEJuV+UcnSa3Kgjr2YPvD0GxecqBnIP7R7Weahl+mvLx362MYqfOu7+0+l02BCUcyMjWCymfBc+I5O1ILCUxQMnVf/CQZLUKziWrXwXESxeZqkAFqkzYQltrtxwjBddq"
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 62,
    "candidatesTokenCount": 631,
    "totalTokenCount": 1031,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 62
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 631
      }
    ],
    "thoughtsTokenCount": 338
  },
  "modelVersion": "gemini-3.6-flash",
  "createTime": "2026-07-21T16:21:27.790920Z",
  "responseId": "h5xfaoijMIWq8sYPycj20Q0"
}
```

</details>

<details>

<summary>**Spatial Reasoning** — Higher thinking budget for a spatial reasoning task</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.6-flash',
  {
    contents: [
      {
        parts: [
          {
            text: 'A cube is painted red on all faces, then cut into 27 equal smaller cubes. How many of the smaller cubes have exactly two red faces?',
          },
        ],
        role: 'user',
      },
    ],
    generationConfig: { maxOutputTokens: 4096 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.6-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "A cube is painted red on all faces, then cut into 27 equal smaller cubes. How many of the smaller cubes have exactly two red faces?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 4096
    }
  }
}'
```

```
There are **12** smaller cubes that have exactly two red faces.

### Breakdown of the solution:

When a cube is cut into 27 equal smaller cubes, it forms a **$3 \times 3 \times 3$ grid**. The location of a small cube determines how many of its faces are painted red:

1. **Corner cubes (3 painted faces):** There are **8** corners on a cube, so 8 small cubes have 3 red faces.
2. **Edge cubes (2 painted faces):** These are the cubes along the edges, excluding the corners. A cube has **12 edges**, and with a $3 \times 3 \times 3$ grid, there is exactly 1 such cube per edge ($12 \times 1 = \mathbf{12}$).
3. **Face-center cubes (1 painted face):** There are **6** faces on a cube, and each face has 1 center cube ($6 \times 1 = 6$).
4. **Inside/Core cube (0 painted faces):** There is **1** cube hidden completely in the center.

**Total check:** $8 + 12 + 6 + 1 = 27$ cubes.
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "There are **12** smaller cubes that have exactly two red faces.\n\n### Breakdown of the solution:\n\nWhen a cube is cut into 27 equal smaller cubes, it forms a **$3 \\times 3 \\times 3$ grid**. The location of a small cube determines how many of its faces are painted red:\n\n1. **Corner cubes (3 painted faces):** There are **8** corners on a cube, so 8 small cubes have 3 red faces.\n2. **Edge cubes (2 painted faces):** These are the cubes along the edges, excluding the corners. A cube has **12 edges**, and with a $3 \\times 3 \\times 3$ grid, there is exactly 1 such cube per edge ($12 \\times 1 = \\mathbf{12}$).\n3. **Face-center cubes (1 painted face):** There are **6** faces on a cube, and each face has 1 center cube ($6 \\times 1 = 6$).\n4. **Inside/Core cube (0 painted faces):** There is **1** cube hidden completely in the center.\n\n**Total check:** $8 + 12 + 6 + 1 = 27$ cubes.",
            "thoughtSignature": "AY89a19pbjpH5K2G+uQep8Sf+P3G1IbQZffTYG3H42VJAG+qKUF6Kp3D7aoC5i33ePiT+Qyh6qAVi9f5n1QPEpDkGiAAqvk7cLOd8Tl8YGOIg2AAFqqBfnALSkK7bk++ViADaeJllbJTz0Mwnn0TLDDxhy7Lylqu0fNR5QMQDf6GNNka+DOufFA3PsiGt3byDrkkEA9hU2ACYq4vgaICecMAR0fR8voH8Y5qY46fZ4Ul1wvaMqLL6KEtKkQyR/TBVbAIGsRk/wwjE+11qwOgOm18MhfdcLC9UmNCQrjqVF9EaFOp1I2oL/nIj4M0bmpiDfrtYCLUYZFdoxrOECAdyR4tcds8c0FZi9KgZfVj2MoTPsYGIc1kzAkRBTIHVC5RAjPXuS5MowtUoniRaW6BVkv8FaDGi+VjSWP9cb72PHmdMY60r6b4f3kc15rji8IiiPy2DYXtxSjXwFHwIE52j4zQ7L8cUBbCeQC4VFL17h6H9ZPpa/qc6PFNqnX0zarqMl3RL9hJOu4Viqy7uxNZOleE0BtyTGGQBNKM5WZSAgF5V7kxLNivxPK5ZGkObV6KdEGyXjiUxZuTFkWhLQhTdN0I0iakTYI1Jtdkrosk4nTqCi+LkLGkFz3HGnY5ad8fJmid9YV9mECqF8LI2Sg/yXOY8diRsdCfgzlKHmtcmACyKoDP+imx4x5iPWTd+Ya4cYseWlC45H86qAGlt+ifqtzekq8YEGu9NFRTb17/OvB5FTfCYFig9+DbKbtK+sH4Kn86Inpj/hgAJ6Ql8icDfJP2dj9DXlcYZ317/A2dCi6oa2LJDLDZ4QfTbI19B133aXmD9Rag7Q2iwBtWiWMy0yfWqE7grFzCLinnQFrNEoIhgioE6PEqWIw4hcinvgFaviYEPEJepS2iFxXgpNbPj4thq/vDDIRdTvNIp3vX1+kCO37JqmiwFD9V9W6MouuZ/Pw76qwVnMGjTWAijiG6F/f90T0lHhK5aoPbbQr5GOOcQqlGSXl5AtrVxuPbFzZkeCmqYYvNmNKIaaMhlWrhxdtOYyk6tYtIdKF44f6zf2qHwdDggkXZRC1931Ba/92sTLoUWwOxZEbtIFoC7BZGQGH87WWEzPwWi1GapK012WtuxXmCNTpuJ7m3h+zFdwQnF9OtrvHW9rNJsjMu/hlJCqaLVNPk7HRT/w9c0F/wJ8BB7W6a2PlZ33IxygmTAWLBLuEUhG9zZBuPrMlZGzw7LmAH3joUFlCmfjSD3OPfhg80Ctc4wPSvYo4TcYbRClSQ58CDXJRj65QyKgs8Q/QfAu9QNB67gUxG8csdCDXD2Mu1Dcwd46Qb4qBpNveonh/kTH5Kz1jHT/gkr07lVawul7w6fiL2Q7P0QmDgGTrr2woLFiNb2o99EW6PaLHfQF/TfX6wiYDAuZ3qYNN06Z/9mo54sLdBiLvhVtCg1g/riqyMEgdUjVYahGGIj8LtyJwd6FP8Trj+GJUIaGXe0v43i7xlGBfy3ISc3ru4eueceeJCR8aOP8BEqNEAveFVhq/IZv0X/hfZYWLg4S8/MFTTBswhGCw6xzIIDcZelA8Tb44I+TEhBMqVBWNTi399qBz1vFnSoBi/fJ4igDDnnlxYVRFKQrVe7CGduTtsHvyxddbxhpfByq00LNLJ66Q/7Z1y8dBAVFqtFTrlYBz3Phmp83Hmq1Csrlrq5cKmDDnH8y69nMkW2AjvfUKbcP16hQ/2fyyPGNSuDe7Yq4ibPeYZ6K8O7gBlIBCo7VGNcHOsImTCzmvj1dWse+zp1Atd62rNAgjgrx4PzgOH5vzrXmERdA9GU5zAhrGLIQ9VHnNRVmJeiKiX30kM03rI2rNYmuHOLJPHK951nQEujwaC3IIVmo71FHhDB8i1O1ZhFS0bW3j1HMIyRyBsytHhBZRfi1jC3zlM+C4WtNB0wKUgAOMYXduKgL+C/iIVwrMqcFIHg+MQ2dVaxBdFc9jdX68q7g/NvkW++89Rr5+2jUG1ijRF5tZ2n/PvKlb6uOmOIKKrB5yk6aqEysTGQ/GdNcwVBLu6+FOsEPt7YmRK+1eEYv9/8QnJ4AJjNNzfwo0uqT0/M6fpibnd8vjF3mL4mWqO8yTtc+VWNkhYeLsiAtUKSIl/4KnsFHQHTa0R8olgngN4c6h1NyWj9uIZ3EK1wKXlYbzkVB/RZffp/zMr/ivLYw4qyS2Mqg3WVFtov06WFtCwCHfeFUrkdpTg5X1BAx7Gg0UYdX2rTyQ/Ayhcet3gUOUlAOxZda/U3oI57QU0MmieNY7gjmMLyJK95JxBwzynhtEfUPh/I+s/x3ebCGrQz6tbMPI/nlLcZuoFp4IzjCdqLATrqhhR4CXxSrg5Pt9mlF0sAFKBK3u2GptAZ8qRz7nnchnOJ5xfMD7K8IRBdXu2Ttidmn3Zm31nfmvPzsWjqIHB1Kwa8xhfQHM71ndx6lKjFGwBZU4Wutzo59RqfUCyw9nFLjvGn2frh228ZmcavxeocTZWk/RxXUyUfC8lAltkJ/WljXk7Xzq5p1Osz9PDSTQ2ffKt/em7jOB24Ghle/LUgENlbKTWD7zrQiVx55QJXNpeZzsVV2/GZoLLMEczGOPm4/+Ttn7BPvEdA/GAo2TgwCv+1DkVIfVmqDA0hw2xNJdDNj0ZxQazAVLkbTpMJZifWxRABj8xgw/MI4d4HBnhd2HK3fvvyQkMqIvV8XS4GjKCqNf+NA2YKMsxr/coupSXKwIBw5JjWdz0bcF/hiYVD0gTfvgVXqTQrTXcmUm7NbpHxRSzhs+lW7n5miyVjEt5WmsYTM7mWIdIWXN4DpRQSwJCz0Sq407VRkvPbHGdA2+UcQtZqQm5zNBCbgKkzSQvI7HjrZpRtWfp8N0rL1cEB6iKO/TIOms3T3MweSU/Xqw4IqIkgc4ef/EULrLui8vb0lVV9U+84mjpw7pGXsQxZoAmFm9KZbifjMwH3XXCWgkspES1HaTOfMhjl47e39pqYVPYz2Jx33I/XIvvd/QCedD+TAAU34cd/DMm8BWClbE4bp3u+zi/Gl3vQgTlotQwucxPf3N9W6FBUjaYsYWti40FqFDnxV932A8SuWdu4n51lSk1xL/2suhVOzGxAiO+sN27QZV6+t5I7SBouU4i3myqOPK86RwQ6PAJIb4dU00dleexfmPOEB9kNCyFF6/JRgoF/6sAfN5S/DBe3C7zUb1F58QhXgVSrYEjUOam86SDgj1BGwgGRDL4K++TrBISun3HoOLriVKL0YfF2Mv5qgfnxDQbLdV5QbnaBY8LUiBX29XO3I4+O+Qje5F8iVy8zLMn1nI38sZ5Crsl9kZEIX+xFDMr2eP8mMghV5OLQx02j88ZUI5vwrtH95VZcomG/4+t6Jr3FYdhbiTcakp6dpccYlbeDJ9n6i+DTbhAM40J"
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 31,
    "candidatesTokenCount": 265,
    "totalTokenCount": 1089,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 31
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 265
      }
    ],
    "thoughtsTokenCount": 793
  },
  "modelVersion": "gemini-3.6-flash",
  "createTime": "2026-07-21T16:21:32.579668Z",
  "responseId": "jJxfatSwI9jY8sYPgtSd8Ag"
}
```

</details>

## Parameters

Schema variant

Generate ContentChat Completions

▶contents\[]

`array`required

▶systemInstruction{}

`object`

▶generationConfig{}

`object`

▶safetySettings\[]

`array`

▶tools\[]

`array`

toolConfig

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶candidates\[]

`array`

▶usageMetadata{}

`object`

modelVersion

`string`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.6-flash/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.6-flash/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.6-flash/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.6-flash/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.6-flash/#page","headline":"Gemini 3.6 Flash","description":"Gemini 3.6 Flash provides sustained frontier-level intelligence optimized for real-world tasks at a higher speed and lower cost, excelling at code generation, agentic execution, and spatial reasoning.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.6-flash/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Gemini 3.7 Flash is a highly capable, natively multimodal reasoning model optimized for agentic workflows and real-world tasks.
title: Gemini 3.7 Flash
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 3.7 Flash

Text Generation • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-3.7-flash/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-3.7-flash`

- Third-party

Gemini 3.7 Flash is a highly capable, natively multimodal reasoning model optimized for agentic workflows and real-world tasks.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,048,576 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://ai.google.dev/gemini-api/docs/models/gemini-3.7-flash) |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.75</li><li>Output (per 1M tokens)$3.75</li><li>Cached input (per 1M tokens)$0.075</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-3.7-flash',
  { contents: [{ parts: [{ text: 'What are the three laws of thermodynamics?' }], role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.7-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the three laws of thermodynamics?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
The **laws of thermodynamics** define fundamental physical quantities (like temperature, energy, and entropy) and describe how they behave under various circumstances. 

While there are historically **three** main laws, scientists later added a foundational law called the **Zeroth Law**. Here are all four, clearly explained:

---

### **1. The First Law (Law of Conservation of Energy)**
> **"Energy cannot be created or destroyed; it can only change forms."**

* **What it means:** The total amount of energy in an isolated system (like the universe) remains constant. When heat is added to a system, it either increases the system's internal energy or does work on the surroundings.
* **Equation:** $\Delta U = Q - W$ 
  *(Change in internal energy = Heat added to the system $-$ Work done by the system)*
* **Everyday Example:** A car engine converts the *chemical energy* stored in gasoline into *thermal energy* (heat) and *mechanical energy* (motion). No new energy is created.

---

### **2. The Second Law (Law of Entropy)**
> **"The entropy of an isolated system always increases over time."**

* **What it means:** Natural processes are irreversible. Heat will spontaneously flow from hotter objects to colder objects, but never the reverse on its own. **Entropy** is a measure of disorder or unusable energy; because some energy is always lost as heat in any transfer, the universe becomes increasingly disordered.
* **Consequence:** It is impossible to build a machine that is 100% efficient (a perpetual motion machine).
* **Everyday Example:** If you drop an ice cube into a cup of hot coffee, the heat moves from the coffee to the ice, melting it. You will never see a cup of warm coffee spontaneously separate into boiling coffee and an ice cube.

---

### **3. The Third Law (Absolute Zero)**
> **"The entropy of a pure crystalline substance approaches zero as the temperature approaches absolute zero."**

* **What it means:** **Absolute zero** (0 Kelvin, or $-273.15^\circ\text{C} / -459.67^\circ\text{F}$) is the point where all atomic motion stops. At this temperature, a perfect crystal would have zero disorder (zero entropy). 
* **Consequence:** It is physically impossible to cool any object down to absolute zero in a finite number of steps, though scientists can get within billionths of a degree close.

---

### *Bonus: The Zeroth Law (Thermal Equilibrium)*
*(Formulated after the first two, but deemed so fundamental it was placed before them.)*

> **"If System A is in thermal equilibrium with System B, and System B is in thermal equilibrium with System C, then System A is also in thermal equilibrium with System C."**

* **What it means:** "Thermal equilibrium" simply means no heat flows between two objects because they are the same temperature. This law defines the concept of **temperature** and allows us to use **thermometers**.

---

### **A Common Memory Trick (Ginsberg’s Analogy)**
A humorous way physicists summarize the laws of thermodynamics:
1. **First Law:** You can't win; you can only break even (energy is conserved).
2. **Second Law:** You can't break even (entropy always increases, so energy is lost as unusable heat).
3. **Third Law:** You can't get out of the game (you can never reach absolute zero).
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "The **laws of thermodynamics** define fundamental physical quantities (like temperature, energy, and entropy) and describe how they behave under various circumstances. \n\nWhile there are historically **three** main laws, scientists later added a foundational law called the **Zeroth Law**. Here are all four, clearly explained:\n\n---\n\n### **1. The First Law (Law of Conservation of Energy)**\n> **\"Energy cannot be created or destroyed; it can only change forms.\"**\n\n* **What it means:** The total amount of energy in an isolated system (like the universe) remains constant. When heat is added to a system, it either increases the system's internal energy or does work on the surroundings.\n* **Equation:** $\\Delta U = Q - W$ \n  *(Change in internal energy = Heat added to the system $-$ Work done by the system)*\n* **Everyday Example:** A car engine converts the *chemical energy* stored in gasoline into *thermal energy* (heat) and *mechanical energy* (motion). No new energy is created.\n\n---\n\n### **2. The Second Law (Law of Entropy)**\n> **\"The entropy of an isolated system always increases over time.\"**\n\n* **What it means:** Natural processes are irreversible. Heat will spontaneously flow from hotter objects to colder objects, but never the reverse on its own. **Entropy** is a measure of disorder or unusable energy; because some energy is always lost as heat in any transfer, the universe becomes increasingly disordered.\n* **Consequence:** It is impossible to build a machine that is 100% efficient (a perpetual motion machine).\n* **Everyday Example:** If you drop an ice cube into a cup of hot coffee, the heat moves from the coffee to the ice, melting it. You will never see a cup of warm coffee spontaneously separate into boiling coffee and an ice cube.\n\n---\n\n### **3. The Third Law (Absolute Zero)**\n> **\"The entropy of a pure crystalline substance approaches zero as the temperature approaches absolute zero.\"**\n\n* **What it means:** **Absolute zero** (0 Kelvin, or $-273.15^\\circ\\text{C} / -459.67^\\circ\\text{F}$) is the point where all atomic motion stops. At this temperature, a perfect crystal would have zero disorder (zero entropy). \n* **Consequence:** It is physically impossible to cool any object down to absolute zero in a finite number of steps, though scientists can get within billionths of a degree close.\n\n---\n\n### *Bonus: The Zeroth Law (Thermal Equilibrium)*\n*(Formulated after the first two, but deemed so fundamental it was placed before them.)*\n\n> **\"If System A is in thermal equilibrium with System B, and System B is in thermal equilibrium with System C, then System A is also in thermal equilibrium with System C.\"**\n\n* **What it means:** \"Thermal equilibrium\" simply means no heat flows between two objects because they are the same temperature. This law defines the concept of **temperature** and allows us to use **thermometers**.\n\n---\n\n### **A Common Memory Trick (Ginsberg’s Analogy)**\nA humorous way physicists summarize the laws of thermodynamics:\n1. **First Law:** You can't win; you can only break even (energy is conserved).\n2. **Second Law:** You can't break even (entropy always increases, so energy is lost as unusable heat).\n3. **Third Law:** You can't get out of the game (you can never reach absolute zero).",
            "thoughtSignature": "AY89a19XdC4x/f+U8hCl13sukl2kjv7cr4AAfyhSwG6PrM0gqQI0UzuL58Cyc42V2aoktYrBm9y3PV9o8xeqfFmrMsWLhF+VRtKFVTFy0R1uAZksXMeolxKfpKEa1DQS+j7gJUzvuZ9NtB54RqMgqHalOz8fg9kq5X/PvmlBOxLZ4ySW5Sp9Rh3QWhASk3Cr7qDXk4tyOc6ylVN1OhT4DiuRjV99iN0SRFhyOAYPab79S4plWozrUu3D9u1m09areMRZhH5XbSiphOzrozdP9UT7juC/efYMePHY9GisNcNTIWiPv+bAjsSDd3rH9AKM0gGreJB60i54vKS3xHPgsKNjqxE7hOcxO6vl5T9bwOGWMOC/bv/NpuEYZYovEjBM+ZFs8XmDXe85xqc1IeyKLqtqevI0zAmLWiKIYJbGD5OSO+L6WVHLbP8ee4cnaQbJGcQ5mgOy59MqnKKcsTRN7rsScCDRRIS2aH8HsWRII7Nbvvc/lKj3JrdH+r0cWX6nFNy2KPSRu0PqfQcRhZV+6YnRwYq8POuuyAIkIZmBnUqNqd2e/dcKSJ3VfkR9Q631s1/b1lmawlMaVC/phXPMCwku0yFhh2c/xdrAy/LeSfJ8L2D5IqqvZZdvEyLsrLhk91vxDTbzfmvNNEIh7JanYx6nk9SpmItstFZEcXVX+kpwaoBBRP1JMWmZUbLXqdZYwDUFM9SwjMWt2ExEUF2KEBGw9L6OMTHXUlAIm46iHhWNQ43Cil3qg3MYoGxsmOvu2U+5Z02SWVXWS+hnf3plXMDtYK+Q3niMoIB0URUtAP2xjPVEuXvdq2cWGb0zD6ZTtqpJz0KCyWLsJMr9ATvLXbEQGDHLWjULKBRXqtgc9StuBsB8Vz4jVB4KlRoDfuYZcPXCXjDzwdVOVZUVc+2Q1StIeKBauPsdc43yodyqKOpzPBDo8J7N7Q9cxy9KI4fxHlF6K3QEaEkcRw4uFnau16r+2zxwbGrFUIfiyhLdzcOYMjwQXSYWW6Y0YOe+Ad5WxJxyvREZQRIu28RZLztT3tyRS89qO3IL+QtpJuwfqInYM7M6gVRmnnIYuRC0pAaYZowNyKtIUHXEVltBEdTEJwCexfzIllgNhN4vn1c3ThtKCIfnN3CPG7VKt6m08cbMZrGG5haK3gi2sI8A+DVrC/Z2iy/COAsOollhvPz4TKqb5kXVFXL+P3WiigLPVy/PMogONopBXc8BGTyA6Dzv8tMcX63UUzZvG7sJ6QXV1eQruIFER/IxeeB8CIFIfYLZILfrm4bKHi8jA3wKcuxcWSsRjM1mV35g3Wsz+dtrHKF9S4NwC7/XeOe6uRPz6Nke8NBjW+h4/6d6q1vZ627++Tn2cfHkMm1GeMDRDp+DjK4JjKxb6FRxDZEElUCL59p/e6m36K4aUJwFY0TDZuGWhV+Djf4RhdfITUJrzCGktv4WbzGmCCtb3a8abKt8F0vQReuZhlitJ+BvZnqjtDGaN6xjhjC86qwCBasdFId4s/r6qPAZOe1kvgTi2D7He5PDy0BPOqQGMQcDR60MUKVD8NxcgYhLohJSy1jvMwYLFFJ5ws2jPawRVx0bkGX6FjwtQ/sdZrkRdhnm+YZYa7QsrHynmCL1yZyxRSpmYlqqcXzGIhbAtI604wKG9K5iwH+2ywgaxp6hH8a64sj6bqnlGX3smE9ZVdPUjh6r1HCrMIhcxT35X586BVIilxeHiIq3tGobj/V3YXSVMT8njJamGC+auzVi1KoIZrORvGnoa0/VMVbwu9zE1XsWG6ImY1XssL5LKG8VMiJsIASfr0baAujU3OHzGYByvhLC0nsv4E6aWT0DE9HflmT7e9qY38Ywa/e5DRUO/TQK0kHjcSXcLhwTKWPBvbSAaOeatHIl+RjSz1XK6saPfzN2lPHQFNC4aoyZ7wQZsFF9isLmn7iQyobDZRoZOsSdlJNv6g2kg9ARKIWPLONT51df8Xa30KEaNCPj5x+O+IqIyFTKT3ITPzBkDD/OApA6SlbZNIGdxNyaVmEB2uugftGLRF5sJTH8AIP79DIMpJDLgEojDjLRr5p3rVu3SGQPAnmvFC0SGRf5bRJe5vn9mBcgv7lHa7RcMJNG5CyNYYXE4Ed7XR5HizMvk79XVY00cv4REn9T+afkyoROq/MeeFiPROQ0rLGm2pbVQFRNED9MJJeK4GJASz8eXKX6vj4rhy0pY6r1quW3BZ88HkdVw9IHVUuIvHXbHcXik9gJhEDUoFv+W6of4oqns6/qlfuY53FOSB3Fi3mFnIFj+7ksAL0Kp+La7SA0fdbAKw758lQEBIoEjQ7MbPPZ9HuiWWsTdAKqklApfUqDANf1UnveXRNq8k0FevEpq7wG8a7cmcwszRRCP2YKEIG22cpYMckzKgk+dVmzpOuLJTpKMDNvQsA5ZQWavc9hNbRy0g+VAJvNl+O9kqAkjkSRkpvHFipseRCQkwmQd//1LDry60yQexY0SK+H7ibKzbXoadDBN+jsyhyWs+pI7/bHVPk4YCLLP+9l0gmPqhfbkA1cHuEQwxA3/h3mIBa2XR2x9A91rwYyetxOT7JM3QCe1Oc9S8ABpqAd47UzMdVWtd9WEqF0wWqKTe8jfP2DqhTBov9goX3A05v+W1JUrcCZ8GA0gd1zPy8MIxhA9oHS8vUPSMJM1TysJQgaFl/ad7eVwvSComAngzWQ8m4SZ9JKWSWhcUGK3kb2uCNM4PdkGARx6gW/61RnyAOm6vZ9o8lxJprtim7gmmEz4PFLSa9psE34Fr6I6cYyGl27tl01/lh2LyXQrX4B5dv/eTWnVOCFeKR67AYABcW4qPzVrqY3uY8iQu5X5P3qlemYA92amgskdK9uT/AWeM5l7ncmUvZTcTSielzcd+FQZiNZGs8vJSKsl4Qr+j+cq4JCkzQEwwTzXagwPiUEbSiNj+hhHHjgeGoTvTJrz/Y3CAcUj4RW8FeDiFht0u9pjZoW5vcMrzSWOt93PvAe6DRS3XWWyMWrYWInCiCR9n6/d5k2DmGJlHlh3a/sTcAUo61U+fdIP7eSc9FURng4UgslifJOXjOAeOGSAYivxvuY28u6JhTVXWQPXLxMlOEUgOjZio+v3rkcJCCCgv+QOG/P2Ij5XAq2MWy82PAJjgNZlKoA6wEBMEt6P3zSvDxDk2a7zlUlLWOFlfBYp5LkqZ+iqRjaSmKrYCgzF3px25y1IdHZ3NY4OoZkpXW9K9X7bccxFVYgIBu7erDsBu/Rk2f5uPd44cEa2UcawNACsJz+COF+5G/eoiN3xBCkOY8joRT9s4f0/5XiH7zpIggw2XS9L3jqzMdUnkNLV+zwtUSWC3PlS6JRq1NbZ3hdihlTj2uF7XWEeL29M+QYvrNjhjAcKHk1+Z6mu3on0ONd087rTyjl+TXjW/dGZEL5MqWh8F8TeCvb+NsRFnKou+malXbUHjTtft8Du/M/0XcmH+7rM0VeUTvEiu9Xr5xzuichY0zO7w6eYBbcPrNVKBCxzamwBKCPNoaK3bQTzFhecucJDbPZuUvmp9qYZss8iPvyCNiA36xV49tvnycbKTI8KVTeTccYxqouN5js/fZvHbzQfoj5C7eWtlZlQqgrTGxNxcJ6eRuAwdQ1sytW9BTAahQjEZlSN5yOSTlg9iRoAx8LWyI="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 8,
    "candidatesTokenCount": 752,
    "totalTokenCount": 1433,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 8
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 752
      }
    ],
    "thoughtsTokenCount": 673
  },
  "modelVersion": "gemini-3.7-flash",
  "createTime": "2026-08-13T18:07:02.084997Z",
  "responseId": "xgd-aoWYBeumrb8Pht-PuQw"
}
```

## Examples

<details>

<summary>**With System Instruction** — Using a system instruction to set an agentic coding persona</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.7-flash',
  {
    contents: [
      {
        parts: [
          { text: 'Write a Python function that merges two sorted lists into one sorted list.' },
        ],
        role: 'user',
      },
    ],
    generationConfig: { temperature: 0.2 },
    systemInstruction: {
      parts: [
        {
          text: 'You are an expert software engineering agent. Write concise, correct, well-documented code.',
        },
      ],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.7-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a Python function that merges two sorted lists into one sorted list."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "temperature": 0.2
    },
    "systemInstruction": {
      "parts": [
        {
          "text": "You are an expert software engineering agent. Write concise, correct, well-documented code."
        }
      ]
    }
  }
}'
```

````
Here is a clean, efficient Python function using the two-pointer approach, running in $O(n + m)$ time and space complexity:

```python
from typing import TypeVar

T = TypeVar("T")


def merge_sorted_lists(list1: list[T], list2: list[T]) -> list[T]:
    """Merges two pre-sorted lists into a single sorted list.

    Args:
        list1: A sorted list of elements.
        list2: Another sorted list of elements (same comparable type).

    Returns:
        A new sorted list containing all elements from both lists.

    Complexity:
        Time: O(n + m) where n and m are lengths of list1 and list2.
        Space: O(n + m) for the resulting merged list.
    """
    merged: list[T] = []
    i, j = 0, 0
    len1, len2 = len(list1), len(list2)

    # Compare elements from both lists and append the smaller one
    while i < len1 and j < len2:
        if list1[i] <= list2[j]:
            merged.append(list1[i])
            i += 1
        else:
            merged.append(list2[j])
            j += 1

    # Append any remaining elements
    merged.extend(list1[i:])
    merged.extend(list2[j:])

    return merged


# Example usage:
if __name__ == "__main__":
    a = [1, 3, 5, 8]
    b = [2, 4, 6, 7, 9, 10]
    print(merge_sorted_lists(a, b))
    # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```

### Alternative: Standard Library (`heapq.merge`)
If you prefer a built-in generator approach that handles large streams without loading everything into memory upfront:

```python
import heapq


def merge_sorted_lists_lazy(list1: list, list2: list) -> list:
    return list(heapq.merge(list1, list2))
```
````

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Here is a clean, efficient Python function using the two-pointer approach, running in $O(n + m)$ time and space complexity:\n\n```python\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\n\n\ndef merge_sorted_lists(list1: list[T], list2: list[T]) -> list[T]:\n    \"\"\"Merges two pre-sorted lists into a single sorted list.\n\n    Args:\n        list1: A sorted list of elements.\n        list2: Another sorted list of elements (same comparable type).\n\n    Returns:\n        A new sorted list containing all elements from both lists.\n\n    Complexity:\n        Time: O(n + m) where n and m are lengths of list1 and list2.\n        Space: O(n + m) for the resulting merged list.\n    \"\"\"\n    merged: list[T] = []\n    i, j = 0, 0\n    len1, len2 = len(list1), len(list2)\n\n    # Compare elements from both lists and append the smaller one\n    while i < len1 and j < len2:\n        if list1[i] <= list2[j]:\n            merged.append(list1[i])\n            i += 1\n        else:\n            merged.append(list2[j])\n            j += 1\n\n    # Append any remaining elements\n    merged.extend(list1[i:])\n    merged.extend(list2[j:])\n\n    return merged\n\n\n# Example usage:\nif __name__ == \"__main__\":\n    a = [1, 3, 5, 8]\n    b = [2, 4, 6, 7, 9, 10]\n    print(merge_sorted_lists(a, b))\n    # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n```\n\n### Alternative: Standard Library (`heapq.merge`)\nIf you prefer a built-in generator approach that handles large streams without loading everything into memory upfront:\n\n```python\nimport heapq\n\n\ndef merge_sorted_lists_lazy(list1: list, list2: list) -> list:\n    return list(heapq.merge(list1, list2))\n```",
            "thoughtSignature": "AY89a1/7DiGkUrOuttOAy7k+sp7leERYwo5R3cg8S3yxDA+Tnd3ssAiNYC4uxqEr3xMAISGixJES6CVe74Cy/DiRvl2HSM0SiU4TmHHyAd3eUcNt3BKORH5fSqzgLyyUtHkzhDnFjO1VQT9///WfxmS8BLlIDp9dXaF44o4sr67Kw8Qi+3GMlh61cUPhmoYWYdeSI7d6CdDBw5Dw6kPR1NuFDbvo3serTTbyTOPptFmW2L5VgqS+gYz0RPHbLF3kp9fGVMfkmBIZpT3Mk4iJcGDXcMPS27T0HiBAVbZMTUjaaaYimCA1V8GQ1XrIMwbWz2T+S2/EeqTTtRY4uwWGd9sknn0v4SF33qjOykzkNucZSxEzEf4G6sXK21aVN/hoD4GDwE/WxLmc3Vr+stIjP54jr5KR9qaMyNro7PFS1S4VRvYbiygNq/E8y9qUqw3JAp+2er2LF4rVrdEsltxCxOW7LwRbMio96bqWrqojlA9jjnuOPpCIfY80C7uOWETHKLts6gn0YnobyJtPvyHQ+a1B2M+7l9rvJpA+t4brAdS2AeDLqqZn0FgAUAH+Wu1C51djsfqfFvGJboNH+07oEGEVKVlGbOKRidJjmvue2phH8qeawE01TWoufgreX+0enwSotxg5gWYq7Ev4O6MPrepgIkJE4MSZj+zVR0nBKnC0TqTPfdNeHqTeUBYF03SyEf/2q0svuQszgunk9bArOuGLD6KQ39FEgrBEpLJuv931cEwr66QiWLBqtrhUFKdYJIC0gNMUJuNOyWLpU/jpCW/lZOhlj6b9aq0NdJVYNAG4h9+WmEL5OCkLwWuTQ0xmG78HOmqUFwXR+RUja4don6dChHbNrDrMVUvm3+rWx6bxSdw0p/912qMfaW0nKciNzhsjZI+Nv1UKIN6Im7jYSkdh4r0wTmIrbx53F4AUBasxAChmkN+FqfsNbiV0l5oDAiGIRKJlLZxW59VFN80uWkkRfTWYBFvGolCyXo/lmpYc2TtXOyqOntM28epoxdGmaHB0Th70i8JhCCEYUs2uCcYSYruEiPcWHkWREGdDMF9niHCu3fDh6c38j+u7Cae5FdhT6y52vnz8VZ/A17aTvgjJU5AN+bt1Dd2FdO3aY+8NtMKZdjmOeVzlTtug26JhTSXKkmw6T2OJLTST+z/YjWLXYKXgGmhlvlRXjHrPp7iR183O3nsxqFCkA6UomW5XMHUAAM03qXWJFGRrIMiqyyusRn22lRM5ixajLgUhWlhWaE7vsVIePRVNos0MQlx4sc2l9+FV/oXqrDoR6QU5+7tbiBDRrZGq111UKgMhGP0i2+d7OVL+Tb8/+joZPAJcJLAXtbv+6LkbEXZjOy6ezHXmh/uouZxQX5kNd2L3l2Jf36e8rGEzzK7DNpC40mLqeL+lWyS/47miHGzCiHkgB+5SLEMJTXDdBwL9Gytse60WZk3fAhcAvtYTvEb2xTG2iyqclcR1pmiAHt4gYsHDRYBjR4eymvNaK7VePZSitm7LTPiIIUwxSLcsY6G44HFnunMO+eyTK4NZSHlWG9vDLuWcLdS+mRV9jd/hYW6qaxY7blzXndoBmxSEKaS2atUihtFMYoSA17JYxWRYN5MgaAQZf4j35E7B1gCVIt5m115umss7SN9FRUvu+QO0LmMPLqERx2uZ5YnU1Ic7/UNuVobxIMcfyxD/USe/tTKPcai4Sox9SrAt+U/RNzqmNo3OPS6NxVCEKgcW52b1R7AP5fPa0KAhV+6nivgeb4dh5onS0dqQFPDiM8OnidcVV7J5T6PXsRAA/Ii9F2TwUAS35EIYNdEuQpG6B3+DC6TcU5wRc9FNH0sfQwBPqxCq9Be43IZjOTygLRgYN5YRh6Zb+kyloNwdEx0woiMVqJ7EuY+7LCHPPrO5VOcsA2saHgvQaoVhyIlI3rfqkyo9NR7yPFQHL1pDaS/kdRdP6P+UaauqdV0+YHSyCPVlK01JeL/ceLLSn4AfNwFtbSd8LEu3CqOEgSti3Xs6pt7tsXn2jIFsWTtxcoLB60n01RYyAhjoSejrp3lwBYViBvTfiZ1yZcdy6YyIbo+yGei5udHXhXf+Kge51NJuR81+Ne9SQpmnsbSiIct4l0bgHl4TwWQ4cTF2V4JLZnVheCgFkIbdiakaJq3ol9MHi1PPBwNXZYSmfkh5TjvObwODh+OmXomMR82zOEZPqkCDp/7PGA4xkx61qtrqmdYUbwdUAq/qTlrwYOGt+R8yWjXjdRRtZq5rZLq5KOm9BK+m5hKborANJc4C4T1HtMYqI3kwcAGjMdAptWFZT3RHOl2UT2dSMvliJUeO+ybVG/nkfGF9jyzDPVPZG4QpDutXjfmFKVSPK+qYDn7UvLMrd/wSoWWllkejZzHSo855ZcMP/Z5Sx9ZU8VjgVtswxOfROo7UOKsvkHllWPhvqTznru3wo4WlywjAm7Ye0yhCUeXPlerHjLSYWg9YBb1nbo+ww0bHaUPkbgk1cI2rL4vZmqUiAHTm87NOqyUBi4tT7v0fFB5vsa8fcH3aUNmh2OlQYX5mS0T0GLFf0u27WEIh8eOve43M2G4WJq7uCxo6dRr2NN7tzwuoSN/8DHlzf8vP+VldLJF0gJ80a3vYaFxYkq4kmt9JCETPhE/LexW4zltdXAuEwSrLMJI5gKarpfGyeprJNwM23lzyJ8nYU8o8ROnBboniHLMv+LgtxIcomIPTOzsz"
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 32,
    "candidatesTokenCount": 517,
    "totalTokenCount": 1114,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 32
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 517
      }
    ],
    "thoughtsTokenCount": 565
  },
  "modelVersion": "gemini-3.7-flash",
  "createTime": "2026-08-13T19:07:35.820040Z",
  "responseId": "9xV-asiGMqyo3dAP3oHS-Qw"
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a multi-step coding conversation, typical of an agentic loop</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.7-flash',
  {
    contents: [
      {
        parts: [{ text: 'I have a bug where my recursive fibonacci function is too slow for n=40.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "That's expected with naive recursion since it recomputes overlapping subproblems exponentially. You can fix it with memoization or an iterative approach. Which would you like to see?",
          },
        ],
        role: 'model',
      },
      { parts: [{ text: 'Show me the memoized version.' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 2048 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.7-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I have a bug where my recursive fibonacci function is too slow for n=40."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "That'\''s expected with naive recursion since it recomputes overlapping subproblems exponentially. You can fix it with memoization or an iterative approach. Which would you like to see?"
          }
        ],
        "role": "model"
      },
      {
        "parts": [
          {
            "text": "Show me the memoized version."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 2048
    }
  }
}'
```

````
Here is how to memoize the recursive Fibonacci function.

### 1. Using a Dictionary / Cache (Explicit)

You store results of previous calculations in a dictionary and look them up before computing:

```python
def fib(n, memo=None):
    if memo is None:
        memo = {}

    # Check if already computed
    if n in memo:
        return memo[n]

    # Base cases
    if n <= 0:
        return 0
    elif n == 1:
        return 1

    # Store result in memo dictionary
    memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
    return memo[n]


# Test
print(fib(40))  # Returns 102334155 instantly
```

---

### 2. Using Python's Built-in `@lru_cache` (Idiomatic Python)

Python has a built-in decorator that handles memoization automatically:

```python
from functools import lru_cache


@lru_cache(maxsize=None)
def fib(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    return fib(n - 1) + fib(n - 2)


# Test
print(fib(40))  # Returns 102334155 instantly
```

---

### Why this fixes the issue:
* **Naive recursion:** Time complexity is $O(2^n)$ because it recomputes identical values millions of times.
* **Memoized recursion:** Time complexity drops to $O(n)$ because each Fibonacci number from $0$ to $n$ is calculated only once. Space complexity is $O(n)$ to store the cache and recursion stack.
````

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Here is how to memoize the recursive Fibonacci function.\n\n### 1. Using a Dictionary / Cache (Explicit)\n\nYou store results of previous calculations in a dictionary and look them up before computing:\n\n```python\ndef fib(n, memo=None):\n    if memo is None:\n        memo = {}\n\n    # Check if already computed\n    if n in memo:\n        return memo[n]\n\n    # Base cases\n    if n <= 0:\n        return 0\n    elif n == 1:\n        return 1\n\n    # Store result in memo dictionary\n    memo[n] = fib(n - 1, memo) + fib(n - 2, memo)\n    return memo[n]\n\n\n# Test\nprint(fib(40))  # Returns 102334155 instantly\n```\n\n---\n\n### 2. Using Python's Built-in `@lru_cache` (Idiomatic Python)\n\nPython has a built-in decorator that handles memoization automatically:\n\n```python\nfrom functools import lru_cache\n\n\n@lru_cache(maxsize=None)\ndef fib(n):\n    if n <= 0:\n        return 0\n    elif n == 1:\n        return 1\n    return fib(n - 1) + fib(n - 2)\n\n\n# Test\nprint(fib(40))  # Returns 102334155 instantly\n```\n\n---\n\n### Why this fixes the issue:\n* **Naive recursion:** Time complexity is $O(2^n)$ because it recomputes identical values millions of times.\n* **Memoized recursion:** Time complexity drops to $O(n)$ because each Fibonacci number from $0$ to $n$ is calculated only once. Space complexity is $O(n)$ to store the cache and recursion stack.",
            "thoughtSignature": "AY89a1+Wv/04SFz0MKQY8n+tFyT0cfnQ+6x5+vRQu2MbyVYQqMErpr6OvgnpAYufyK3yG/BXeedOilTz9V1KgVD1QWF0fywd6r7Yw6Hbfwl+RaCf+zGlEOeM7ZuqPAIjIrQEsfaYbR+THgipFCCvNuP//K5ObnatV7hRrDMt7pqltYwg5NWm/O+0H3YvLp55UZlztXfz8t91zLg4pJKMzutMMaupMh5AAHu/pe40KJg2Id/ZH9QCn0ZqrvwJA/vYoQjUNLmbHRQirXIF5W0o5w0yCF6HBkDHBRnu2OWUi7Ne4DIqAmJJYKv0ePurLSaDJLE09M5XS4WOyd7cSH3sBzVTfxYYRN5OeT5UUGZ16JjPcSc3eaT64u1Ng/erd2fT0NfSa5/P2cWGw9KvxOSsU/19OUoonpBQvhoMhioMg1aL2RyVI9ikxm8cl54JZJbmJpmR60vHsdXPFnBSGdG3DQ3MNv+HKZEr6kXQ1FliGJU8qXGcNOAMkgykbgunAecujeN/vpaC3SBNRdc7yMa6cT1T9FVL1l1Cuxx9OuWSQowkhoniTPsV22uOj6drYlKPU6AJJuhNjv/epFySrCJbB9F1rISGL4wYkAD6mDEmaT0rG15OxjEb97C/8OufUirZpcDDC1jR0sWj7FlS4KCQUsNzdhc5AJhLQPtA3IGgAZzDH3PHvQYhUo29VP6jMhOE5S3fmLa2TSiuKtoYwMaAIzkGdp0xKohPrVFtn9Zajb+7Y6I6TsA0WL7Pg/DTIiooTZBG+dGk49Tt6eFfW/ypKXDy9YErzQF6FTK/V9rgPHEpZdSVvFnOunGZ3I+o02B9esYSqSNQlaBI7Y0/5hpCfgf0Ap9G1sh1WMkuCL40d0jRevBbEZAKqrdG1Gr5whRbjNtWbD/Cx17clPpGT5K3dNq5NJY16xqzPwJyNgj7H9xgNFiJGh5xYzx4PBTN0NsgE1bK6t3BrPkWxG0vB7B4Flyj3HRzGHj43qkT2cRKEoNjsiTGIvvyBaa6QQOYZ5yu2hC6h7mpNntCeU5iaDtQA/NC010PqvELJpqmiGyYM9D9uazoHrelc5STEOyUH6Eei7cfhezFCB0ibUm795StAgZt4WvWpYXif4PMRc/gdsNoWZr9Wo0WhlCm4ivwwoiG71oPbzam8IRp+2PP8evgPm4AogOToIHUQMZFz2OnGXXX8E0I25wMe5D+q9zpLO+st7kOFLl1vITCPvDkjw=="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 62,
    "candidatesTokenCount": 412,
    "totalTokenCount": 698,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 62
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 412
      }
    ],
    "thoughtsTokenCount": 224
  },
  "modelVersion": "gemini-3.7-flash",
  "createTime": "2026-08-13T19:07:41.574572Z",
  "responseId": "_RV-auyII6ip3dAP16iw4Qw"
}
```

</details>

<details>

<summary>**Spatial Reasoning** — Higher thinking budget for a spatial reasoning task</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.7-flash',
  {
    contents: [
      {
        parts: [
          {
            text: 'A cube is painted red on all faces, then cut into 27 equal smaller cubes. How many of the smaller cubes have exactly two red faces?',
          },
        ],
        role: 'user',
      },
    ],
    generationConfig: { maxOutputTokens: 4096 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.7-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "A cube is painted red on all faces, then cut into 27 equal smaller cubes. How many of the smaller cubes have exactly two red faces?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 4096
    }
  }
}'
```

```
To find the number of smaller cubes with **exactly two red faces**, we can analyze how the $3 \times 3 \times 3$ cube is structured:

1. **Corner cubes (3 painted faces):** There are **8** corners in a cube.
2. **Edge cubes (excluding corners, 2 painted faces):** A cube has 12 edges. With a $3 \times 3 \times 3$ cut, each edge has 1 middle cube with 2 painted faces:
   $$\text{Number of cubes} = 12 \times (3 - 2) = 12$$
3. **Face-center cubes (1 painted face):** There is 1 in the center of each of the 6 faces = **6**.
4. **Interior cube (0 painted faces):** There is **1** cube completely inside.

*(Check: $8 + 12 + 6 + 1 = 27$ total cubes)*

Therefore, there are **12** smaller cubes with exactly two red faces.
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "To find the number of smaller cubes with **exactly two red faces**, we can analyze how the $3 \\times 3 \\times 3$ cube is structured:\n\n1. **Corner cubes (3 painted faces):** There are **8** corners in a cube.\n2. **Edge cubes (excluding corners, 2 painted faces):** A cube has 12 edges. With a $3 \\times 3 \\times 3$ cut, each edge has 1 middle cube with 2 painted faces:\n   $$\\text{Number of cubes} = 12 \\times (3 - 2) = 12$$\n3. **Face-center cubes (1 painted face):** There is 1 in the center of each of the 6 faces = **6**.\n4. **Interior cube (0 painted faces):** There is **1** cube completely inside.\n\n*(Check: $8 + 12 + 6 + 1 = 27$ total cubes)*\n\nTherefore, there are **12** smaller cubes with exactly two red faces.",
            "thoughtSignature": "AY89a18GhPrAzwD4+OG6wmLOGj2YZE0gv9PY76IqT4vccoHQerNJubk8VCyX0atC0qHPy/28tlQG5WlMvbqfovvGqrSJeNHSVC6RoyKD7SMGVnSOw83d5XDYxirhMa5XgVbtEF6O5t03QYpIyB/ice00yWw9US/osp4NOYRDYTPA6uekMJkCjFH8lNuYP4RnEFmEXHyxBtnlrcXvB2fy9bWxZEw3ck69faKWfJF/Ia0oy27SOdIaQTzcczJum9F+AnjliMkpY4EdIm+5KvOwrZCgcz+QWfNGQBu9SOK9qalhHHiI7diBhU8f4Dans3S1a1A9jKV8mOelXtaNDOXOKSk45muOSxds5JF/wb/2XAdTpgLt2cLE/vOuF4c4WBA+vpV9lvwlHKGMklvwFz7kSwnVOLnxglQwQl9ykyfdcInHzlaWAzfzEu7tq/Zkmp67DBtN7ZeG/teVlPIqm63uwBrQT8MOWVB27Ah59QI57TzclfNs0scwjmTlzFIzrzEKx+uz4Z4ekistTu8yGW12Gk8ypl5HEwZnOS8JpRR/ln20XV95oMb27LA6qnnW71S5SUva8+PdQsRw3NmeIp1FDmjxmuLE43UBcsGn/rj8KymrDRHkC1PHyOU+6je4J+/fma44zwfp4G2YJOit3f8btPUVsjrXH011krTONlK47hfKp08WJO7nCVaw7+gphzRrUMugxl8g7D3kVd5uym1c+lQstrs+FaaXj1VZwM5UUX3p/6ex+gso45qJ+h1OFhmZeOHKF8KTUw86RMdtFC+r1ULthumOSJHmb0nkQKnBqqV7qXdzNVep0rwZHk6rfULTPUQ0XaKAy9dtk8YOeeX7ULaTOHRe044Q9EcZk5eFCF5ktauTBwOG4+7B3R84/TS6DYOKQZSdYukuAQpq9SzlNnZaa1DHc9YLPP0CyPkEJ6yyZjEN78TiLvb+eXW06pPNC/wXVUdx47dq6w8MI16w4CiA8e8r/C7sqKSkD2j0Ksufr+mAq5gwSgOMRQx8vR+SfWp+3i1RvkRHpONZGftNyBuXfPLq1t/Hk6Wci4xkE8k8grwopKdghzHBpknmkz9783YjkeIFQMcoruEgfvzpElGERWmXKg7UqrMaOhY/HNcZ4auUoj8mUMBj+ejiCV/v+YrO6y3TAifJPYJEn4tiV3smbXTIA+UpilF4POrVSoeJkNhb6EVOrDK/UsjP2NNKNclL6F19JurykzmBrQZZs8vVn5KWLxkBXkdkdGMAjtPRdtX9ggfr+hhTNjBYSpo2sxVDjNhOs977Aie8wsRBejfR3a+OUVwyK9PptIaRqpJVQ9YTu0iUe3PcWUSo6YH+6gsOVSRjFrqj+1Ayq0SXfKisu9hF2HOp/vC03Bx0Weqw6XqYMnNvDSjIKEWTImfuGJyx0MK0VS4bvQm/T7T3OmbGnSsqHPx83n10xw=="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 31,
    "candidatesTokenCount": 228,
    "totalTokenCount": 602,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 31
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 228
      }
    ],
    "thoughtsTokenCount": 343
  },
  "modelVersion": "gemini-3.7-flash",
  "createTime": "2026-08-13T19:07:45.456897Z",
  "responseId": "ARZ-asHxG6mp3dAP9fHcoQ0"
}
```

</details>

## Parameters

Schema variant

Generate ContentChat Completions

▶contents\[]

`array`required

▶systemInstruction{}

`object`

▶generationConfig{}

`object`

▶safetySettings\[]

`array`

▶tools\[]

`array`

toolConfig

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶candidates\[]

`array`

▶usageMetadata{}

`object`

modelVersion

`string`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.7-flash/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.7-flash/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.7-flash/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.7-flash/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.7-flash/#page","headline":"Gemini 3.7 Flash","description":"Gemini 3.7 Flash is a highly capable, natively multimodal reasoning model optimized for agentic workflows and real-world tasks.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.7-flash/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Our most intelligent Flash model, engineered for long-horizon software engineering, autonomous agents, and complex enterprise workflows.
title: Gemini 3.8 Flash
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 3.8 Flash

Text Generation • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-3.8-flash`

- Third-party

Our most intelligent Flash model, engineered for long-horizon software engineering, autonomous agents, and complex enterprise workflows.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,048,576 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash) |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.75</li><li>Cached input (per 1M tokens)$0.075</li><li>Output (per 1M tokens)$3.75</li><li>Default (per second)$0.75</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-3.8-flash',
  {
    contents: [
      {
        parts: [
          {
            text: 'What are the key differences between optimistic and pessimistic concurrency control in distributed systems?',
          },
        ],
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.8-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the key differences between optimistic and pessimistic concurrency control in distributed systems?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
```

```
Concurrency control ensures that distributed transactions maintain the **ACID** properties (specifically Isolation and Consistency) when multiple nodes read and write to the same data simultaneously. 

The fundamental difference between **Optimistic Concurrency Control (OCC)** and **Pessimistic Concurrency Control (PCC)** lies in **when and how they handle conflicts**.

---

### 1. The Core Philosophy

*   **Pessimistic Concurrency Control (PCC):** *"Assume conflicts are likely."* 
    *   It prevents conflicts **before** they happen by acquiring locks or blocking access to resources.
*   **Optimistic Concurrency Control (OCC):** *"Assume conflicts are rare."* 
    *   It allows transactions to execute concurrently without locks, checking for conflicts only **at the moment of commit**.

---

### 2. How They Work

#### A. Pessimistic Concurrency Control (PCC)
1. **Lock Phase:** A transaction requests a lock (read/shared or write/exclusive) on the required data partitions or nodes.
2. **Execute Phase:** If locks are granted, the transaction reads and writes data. If a lock is unavailable, the transaction waits (blocks).
3. **Commit & Release Phase:** Once the transaction completes (often using **Two-Phase Commit / 2PC**), it writes changes and releases the locks.

#### B. Optimistic Concurrency Control (OCC)
1. **Read/Compute Phase:** The transaction reads data (often locally or from a replica) and buffers its writes without acquiring locks. It notes the version/timestamp of the data it read.
2. **Validation Phase:** At commit time, the transaction checks if any other transaction modified the data it read since the start of the transaction.
3. **Write/Abort Phase:** 
   * If **no conflict** is detected: The buffered writes are committed across nodes.
   * If a **conflict** is detected: The transaction is **aborted and must retry**.

---

### 3. Key Differences in a Distributed Context

| Feature | Pessimistic (PCC) | Optimistic (OCC) |
| :--- | :--- | :--- |
| **Locking Strategy** | Explicit locking (Shared/Exclusive). | Lock-free during execution; validation at commit. |
| **Network Latency Impact** | **High.** Multiple round-trips to acquire and release locks across network nodes. | **Low.** Computation happens locally; network round-trips occur mostly during commit/validation. |
| **Concurrency & Throughput** | Low to moderate. Transactions block each other. | High, provided conflict rates remain low. |
| **Conflict Resolution** | **Blocking / Queuing:** Transactions wait in line. | **Rollback / Retry:** Conflicted transactions abort and rerun. |
| **Deadlock Risk** | **High.** Requires complex Distributed Deadlock Detection (wait-for graphs, edge chasing) or timeouts. | **None (or minimal).** Since no long-term locks are held, transactions cannot deadlock, but they can suffer from **starvation/livelock**. |
| **Wasted Computation** | Low. If you have the lock, your work is guaranteed to commit (barring system crashes). | High under contention. Work must be discarded and repeated if validation fails. |
| **Best Used When...** | Contention is **high**, write-heavy workloads, or abort costs are extremely expensive. | Contention is **low**, read-heavy workloads, or network latency makes locks expensive. |

---

### 4. Distributed Systems Trade-offs

#### Network Overhead & Latency
*   **PCC suffers from latency compounding:** In a geographically distributed system, holding a distributed lock (e.g., via a Distributed Lock Manager like ZooKeeper) across high-latency WAN links holds up other transactions for tens or hundreds of milliseconds.
*   **OCC handles latency better:** By eliminating locks during execution, nodes do not hold resources while waiting on network packets.

#### The Cost of Partitions & Node Failures
*   **In PCC:** If a node holding a lock crashes or becomes network-partitioned, other transactions waiting for that lock stall indefinitely unless lease/heartbeat mechanisms aggressively revoke locks (which introduces its own consistency risks).
*   **In OCC:** If a node fails mid-transaction, no locks are left dangling. The transaction simply times out, aborts, and retries.

#### The "Abort Storm" (OCC's Achilles' Heel)
In high-contention distributed scenarios (e.g., thousands of users trying to buy the same concert ticket):
*   **PCC** gracefully queues requests; throughput slows down, but forward progress continues.
*   **OCC** collapses into an **abort storm** (livelock). All transactions validate at the same time, one succeeds, and 999 abort. All 999 retry simultaneously, repeating the cycle and burning massive amounts of CPU and network bandwidth without making progress.

---

### 5. Common Implementations & Real-World Examples

*   **Pessimistic Implementations:**
    *   **Two-Phase Locking (Strict 2PL):** Traditional distributed RDBMS (e.g., MySQL Cluster).
    *   **Distributed Lock Managers (DLM):** Chubby (Google), Apache ZooKeeper (using ephemeral nodes/recipes for locking).
*   **Optimistic Implementations:**
    *   **MVCC (Multi-Version Concurrency Control):** Used by **CockroachDB**, **Google Cloud Spanner**, and **PostgreSQL**. MVCC is fundamentally an optimistic mechanism where readers do not block writers and writers do not block readers (relying on timestamp ordering).
    *   **DynamoDB / Cassandra (Conditional Writes):** Uses version attributes or Lightweight Transactions (LWT with Paxos) to perform atomic `Compare-And-Swap` (CAS), which is an OCC pattern.
```

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Concurrency control ensures that distributed transactions maintain the **ACID** properties (specifically Isolation and Consistency) when multiple nodes read and write to the same data simultaneously. \n\nThe fundamental difference between **Optimistic Concurrency Control (OCC)** and **Pessimistic Concurrency Control (PCC)** lies in **when and how they handle conflicts**.\n\n---\n\n### 1. The Core Philosophy\n\n*   **Pessimistic Concurrency Control (PCC):** *\"Assume conflicts are likely.\"* \n    *   It prevents conflicts **before** they happen by acquiring locks or blocking access to resources.\n*   **Optimistic Concurrency Control (OCC):** *\"Assume conflicts are rare.\"* \n    *   It allows transactions to execute concurrently without locks, checking for conflicts only **at the moment of commit**.\n\n---\n\n### 2. How They Work\n\n#### A. Pessimistic Concurrency Control (PCC)\n1. **Lock Phase:** A transaction requests a lock (read/shared or write/exclusive) on the required data partitions or nodes.\n2. **Execute Phase:** If locks are granted, the transaction reads and writes data. If a lock is unavailable, the transaction waits (blocks).\n3. **Commit & Release Phase:** Once the transaction completes (often using **Two-Phase Commit / 2PC**), it writes changes and releases the locks.\n\n#### B. Optimistic Concurrency Control (OCC)\n1. **Read/Compute Phase:** The transaction reads data (often locally or from a replica) and buffers its writes without acquiring locks. It notes the version/timestamp of the data it read.\n2. **Validation Phase:** At commit time, the transaction checks if any other transaction modified the data it read since the start of the transaction.\n3. **Write/Abort Phase:** \n   * If **no conflict** is detected: The buffered writes are committed across nodes.\n   * If a **conflict** is detected: The transaction is **aborted and must retry**.\n\n---\n\n### 3. Key Differences in a Distributed Context\n\n| Feature | Pessimistic (PCC) | Optimistic (OCC) |\n| :--- | :--- | :--- |\n| **Locking Strategy** | Explicit locking (Shared/Exclusive). | Lock-free during execution; validation at commit. |\n| **Network Latency Impact** | **High.** Multiple round-trips to acquire and release locks across network nodes. | **Low.** Computation happens locally; network round-trips occur mostly during commit/validation. |\n| **Concurrency & Throughput** | Low to moderate. Transactions block each other. | High, provided conflict rates remain low. |\n| **Conflict Resolution** | **Blocking / Queuing:** Transactions wait in line. | **Rollback / Retry:** Conflicted transactions abort and rerun. |\n| **Deadlock Risk** | **High.** Requires complex Distributed Deadlock Detection (wait-for graphs, edge chasing) or timeouts. | **None (or minimal).** Since no long-term locks are held, transactions cannot deadlock, but they can suffer from **starvation/livelock**. |\n| **Wasted Computation** | Low. If you have the lock, your work is guaranteed to commit (barring system crashes). | High under contention. Work must be discarded and repeated if validation fails. |\n| **Best Used When...** | Contention is **high**, write-heavy workloads, or abort costs are extremely expensive. | Contention is **low**, read-heavy workloads, or network latency makes locks expensive. |\n\n---\n\n### 4. Distributed Systems Trade-offs\n\n#### Network Overhead & Latency\n*   **PCC suffers from latency compounding:** In a geographically distributed system, holding a distributed lock (e.g., via a Distributed Lock Manager like ZooKeeper) across high-latency WAN links holds up other transactions for tens or hundreds of milliseconds.\n*   **OCC handles latency better:** By eliminating locks during execution, nodes do not hold resources while waiting on network packets.\n\n#### The Cost of Partitions & Node Failures\n*   **In PCC:** If a node holding a lock crashes or becomes network-partitioned, other transactions waiting for that lock stall indefinitely unless lease/heartbeat mechanisms aggressively revoke locks (which introduces its own consistency risks).\n*   **In OCC:** If a node fails mid-transaction, no locks are left dangling. The transaction simply times out, aborts, and retries.\n\n#### The \"Abort Storm\" (OCC's Achilles' Heel)\nIn high-contention distributed scenarios (e.g., thousands of users trying to buy the same concert ticket):\n*   **PCC** gracefully queues requests; throughput slows down, but forward progress continues.\n*   **OCC** collapses into an **abort storm** (livelock). All transactions validate at the same time, one succeeds, and 999 abort. All 999 retry simultaneously, repeating the cycle and burning massive amounts of CPU and network bandwidth without making progress.\n\n---\n\n### 5. Common Implementations & Real-World Examples\n\n*   **Pessimistic Implementations:**\n    *   **Two-Phase Locking (Strict 2PL):** Traditional distributed RDBMS (e.g., MySQL Cluster).\n    *   **Distributed Lock Managers (DLM):** Chubby (Google), Apache ZooKeeper (using ephemeral nodes/recipes for locking).\n*   **Optimistic Implementations:**\n    *   **MVCC (Multi-Version Concurrency Control):** Used by **CockroachDB**, **Google Cloud Spanner**, and **PostgreSQL**. MVCC is fundamentally an optimistic mechanism where readers do not block writers and writers do not block readers (relying on timestamp ordering).\n    *   **DynamoDB / Cassandra (Conditional Writes):** Uses version attributes or Lightweight Transactions (LWT with Paxos) to perform atomic `Compare-And-Swap` (CAS), which is an OCC pattern.",
            "thoughtSignature": "AY89a1/MQe0q2eO6p69LBK2XlADS8H8WvuBNSBew6wjwwP/EBrVVPNgMe0UIQF5vuZzVPTxnedMrSH14awEqpY/K2Uhfpj3tHIHFZ6xO/TXGd8a7d63zBRk6Rch2VTtShr7tx1qXHT0TOcbANjA8YXN+LvODHrsnv4vjr7+mhMpt5ZctmF8p/i31nJmUmWggumY6vVlEXlYbL8qEMra7p2Oin63vthV9wP40DZnj/XNkHWYAf/3gfN3deWYiE1lX0AzKW1zw+wAL9MIwBBQ353DmbENb4Ex/MbcucLykMYSSx8XLCsenCiJdWH927aKZJpsZ22Nj7PzA90sQWGlMZg2Wj4Cf6bVcUUJKd6pDWrbWASlql2mIY4qQE31xYhINFMoEw2ZYwXDN0vG5rQxYU9ErRxRV9mAiY5seyS7o2WDFJZNfWmvcn5QJADk6zAfgYqcgVFBzb+OzO09csr0Uc1t2tmf+7VdjbsgS60kO1Qib++xsniIAwBY2RA3Py8o5OM+sDMkUa6Gaqmis1uOnIVWzZYYlQVD3kTUsrzKfsqSnOhcgWF8JRVGPh82ZAOCI1Ylc4g8mRXdXVafE1/5eGXfxJ6vLJLHyVd/LvPPEbWzdDWPUDpFQXMx4E0ZcCgBPHczWwCad1Lmf+6ACE2ApT0ys15FSRd2dd/gVKaJznnZsOtazfiRXLaZRn2/yuzbuK17UwS+xFruceTnlci5sF7BoUlwvlZ36eNM9++Kv+/ORfLBiIfmgyev5iTucDRi0pNLylgqKEP2xk6YfdI+DwPx9CoH0MeAbbTFoCI4QBx9Vjy+GtdTmi5e93fSmDHZ6iT95ryy6/7p05WXg5QqWF88u/QusIyLPJmDdIBNIa4gsePUYBekqXvjb+/R4p0RH79Mu8Ar0kPuYn5DrK3Mr+ha2KEXqlVm1K4IYOC0yGmHgFVlilGuDxf/AZQDJdVm7TdDPde/Uc15OV4rgF88gQ1fSv6PNO3pvjgpbGtZnLjZOeDUFieaZrCva6B+rEfSKT2g/47KVAlz/wsu897rZeKN8VEI+oqz1AEqbXucUSWiIrG2+4dcj19ntrIwHaIotICaDT0N++1srJkRUHrPEVnuxymt+mhSLIoVWYHQqSC1x3Bn8nqYeEiGj/rhnlQdP9wAtTNCNoNBdGl4DtSNcQH+UtoHnwi6aFqf79tmwyowmrN7nInjs0tgiBjuG5naGCaoFud6NctW2GbULaGyUPtRFl817mD7UIPL8Sfh4KlmxEt/nXZT9jqHv9QhGt4reIoWIobgg5etnnAMQwVEB6H1RCrU7W8EuMIqIO76sI5T+3eEIDuiNT9EofGIyuCuEv9Zf7mrs+xjSfDcsVDGBOjcZCq//D4696W08mmp/wAC1NeLe2enau5TSOY7hMGRDwI7VBQmDeFfEeS8DY/1qQZOO+x4QKPJiwFJOL4nqL4E2+ElPbDdG+XWC5La5A10jw7Ohob9zMH9Swjnu2jpirpqeOgS2I+YWI4/fgce0NZQGr1NY6gwbGA/NAsQifM1/iNAt9kuMhybUAulsvEpEJqSejGJJJ4kcGN+f3/DQOt2R32cEfRcFCcEvm9BcrkFB2DnVpR66jCM0JMVSZlxfMAjrzrXUg/ZcIKSdQJtNMuj0G0mx8plKWdvyRvQq2ylbkdf40It88wtV2hvylOqexA3Mlly7PykMyG1RD0iQf/QhqYgIX75KZuv3N32Nr8r2tkGkUTVJsVDbgrkm58F7zNBe1lVts1H5XGe3x5jahuO2YR6aIzIq+HHImdqBm0oGVxjE2ASI2QO8kStvO90aP4+Jy3MpEorECYXlUvHxieO9osAuw0XagyFBhBgcky6hRCMe4IfDPKZ1uadlegHF+XQoekhP49+BylM23rJnv5H5cbi9q1YZwZvU0NgamnKtpgBTyOazDdOZEwu0qCnfShBSOUiKQ/azV3cb20cMpDlRhT/jsjjl/deGmpeqwT50Q/vZvZNBs1Psv1TmQt0eemHXLirP8sbnoBrMNV1WSXR+ZTtS2KimMDOylHaYgZBvrBWyu3p7E2SO8FOcwggTuWZcpyJFPdGfXrEBAW3ML4U3obBm8VK6Ixg0+LBt1nDlxcB7l8o8fKs0dI5UDntoTQu5Xy5rwhpJ4RlygR4zUeTusqqCPbzxJJ08s1BukfeXbWCb38pknYB8L5Vg1f7ZUWw+zUP4YJSdPszSf4iuBI/3ir4nPT7Hn9xImrRdhtcou7mvCWeq/3ct//5Wy9ZXUcONnetr9C4LWA
... response truncated ...
```

## Examples

<details>

<summary>**Agentic Coding** — Coding task with a system instruction and constrained temperature</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.8-flash',
  {
    contents: [
      {
        parts: [
          { text: 'Write a Python function that merges two sorted lists into one sorted list.' },
        ],
        role: 'user',
      },
    ],
    generationConfig: { temperature: 0.2 },
    systemInstruction: {
      parts: [
        {
          text: 'You are an expert software engineering agent. Write concise, correct, well-documented code.',
        },
      ],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.8-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a Python function that merges two sorted lists into one sorted list."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "temperature": 0.2
    },
    "systemInstruction": {
      "parts": [
        {
          "text": "You are an expert software engineering agent. Write concise, correct, well-documented code."
        }
      ]
    }
  }
}'
```

````
Here is an efficient, standard two-pointer implementation with $O(n + m)$ time complexity:

```python
from typing import Any, List


def merge_sorted_lists(list1: List[Any], list2: List[Any]) -> List[Any]:
    """Merge two already sorted lists into a single sorted list.

    Time Complexity: O(n + m) where n and m are the lengths of the lists.
    Space Complexity: O(n + m) to store the merged result.

    Args:
        list1: The first sorted list.
        list2: The second sorted list.

    Returns:
        A new list containing all elements from both lists in sorted order.
    """
    merged: List[Any] = []
    i, j = 0, 0
    len1, len2 = len(list1), len(list2)

    # Traverse both lists and append the smaller element to `merged`
    while i < len1 and j < len2:
        if list1[i] <= list2[j]:
            merged.append(list1[i])
            i += 1
        else:
            merged.append(list2[j])
            j += 1

    # Append any remaining elements from either list
    merged.extend(list1[i:])
    merged.extend(list2[j:])

    return merged


# Example usage:
if __name__ == "__main__":
    a = [1, 3, 5, 8]
    b = [2, 4, 6, 7, 9, 10]
    print(merge_sorted_lists(a, b))
    # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```

### Alternative (Standard Library)
If you prefer using Python's standard library, `heapq.merge` provides an iterator-based solution that uses $O(1)$ auxiliary space:

```python
import heapq


def merge_sorted_lists_heapq(list1: list, list2: list) -> list:
    """Merge using Python's built-in heapq module."""
    return list(heapq.merge(list1, list2))
```
````

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Here is an efficient, standard two-pointer implementation with $O(n + m)$ time complexity:\n\n```python\nfrom typing import Any, List\n\n\ndef merge_sorted_lists(list1: List[Any], list2: List[Any]) -> List[Any]:\n    \"\"\"Merge two already sorted lists into a single sorted list.\n\n    Time Complexity: O(n + m) where n and m are the lengths of the lists.\n    Space Complexity: O(n + m) to store the merged result.\n\n    Args:\n        list1: The first sorted list.\n        list2: The second sorted list.\n\n    Returns:\n        A new list containing all elements from both lists in sorted order.\n    \"\"\"\n    merged: List[Any] = []\n    i, j = 0, 0\n    len1, len2 = len(list1), len(list2)\n\n    # Traverse both lists and append the smaller element to `merged`\n    while i < len1 and j < len2:\n        if list1[i] <= list2[j]:\n            merged.append(list1[i])\n            i += 1\n        else:\n            merged.append(list2[j])\n            j += 1\n\n    # Append any remaining elements from either list\n    merged.extend(list1[i:])\n    merged.extend(list2[j:])\n\n    return merged\n\n\n# Example usage:\nif __name__ == \"__main__\":\n    a = [1, 3, 5, 8]\n    b = [2, 4, 6, 7, 9, 10]\n    print(merge_sorted_lists(a, b))\n    # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n```\n\n### Alternative (Standard Library)\nIf you prefer using Python's standard library, `heapq.merge` provides an iterator-based solution that uses $O(1)$ auxiliary space:\n\n```python\nimport heapq\n\n\ndef merge_sorted_lists_heapq(list1: list, list2: list) -> list:\n    \"\"\"Merge using Python's built-in heapq module.\"\"\"\n    return list(heapq.merge(list1, list2))\n```",
            "thoughtSignature": "AY89a1/czemtyCXGVCK2P4eOWE2RysFkjJ/wuEOJhDOJ3QYU4daigY9JYFCTDRp7ZWJRgp4iPQBoHynLbpqmFI3dZCzKKONibIdXozwqr/Qnh04f0gJCHTERO4oLgUDplOyihnxn/wM/OdhnZZxocCdUpN9apM5qorKwGsl/XFKE/+rQDIe5WSguJihjLnHuQaUIbGx5kJfcnLkoRwHvnEYq0QjaRFQcIHxTIIUBABXzsFq42A3VF/s+KjqKmDVcFf68bEd8Vl64gKGqqFvFUJSxhuQuc0AYh+otH52oSU9gK74vIBBAomffgHojBHmBsB51u6rPSdpwaQN0GLmxWpdh1+6x03mfaqqeFcs7B5BTB8yPtsS5m9fEU9tMRChmYvQ342Ov6s4fU26nHXhI/S6Nkp2W6YS0XiGALK7rIa0WObLJ4IaRJ7pWu5WPBW1iScoDrZnrhOxUYUQ1NrbQhUUWngSy3Vza5BDWKOB300uLZZ2mysY1tYqvhEPsMrVscsNqozm4UvaHVtNHjPna6+L5qHqBQZN2aNpeO8y6caeYSLcoJkLJ75ZRnHQtrjn0X0Q4j2vz0R1t9j1oKE0KO5SL327+HmcB/qA1UGmINSJdsKslCMDixRHTasBfeCY5FK+Y9epbtJvajxD4LXECDtvmhm7aCs7JXX39wb1/fsqH70b+a+lHjd6wHRw9tPmmx7x+xOYXNCjY/atToqZ+X/3gtmxmPYzdl735S5cvAktd2oBvyTYx8rn6lBi6ZP6Lahx7Wcpx2NRhWmRiJ36TgxQV54qf1PjOd1IBKD5wLEqcHQwOC/aq0trIC4vjVd7oR1ygxPD9FmEUxNQMIJbvGpUgGv71k0DwPgPFoLYLti23h2x8M5TwAjCAE2NwC6V/iTvrq0FUP73xA/xv1JzQJmu4F4noFxvErOtI2wIXPdrC9IWS2ybm5YrOZyg6J4giOSwuKal7MP95q13nhBdxfRrEFuXj1o35GOPJ1BR6KohHIubOoCAkGpJoirpcBqKKjqGJNiwE9jgx824VNXd6dOx/s9finT+Asi2kom88E3ijWDukk9QdT6UPZ2ks4JvYAo6RU+kQ/px4LfQKwqOdbjplWqfhFfKZqxLVYLKS4qJ47C96rXLIsTiXHo1EJVs20dmrMvHKonZa5urz+LqLzL/iIm6ARgvoPf1h7/loDePJtYEJgULA0ydPipnEPfgsnkH9cFQtIkahXmxho5ngXdbn1A9Zh9mmKTnqyxpJnRrFNvC6gP9f7EVtJmZIVg4YoQvOkWzDBQelnJFEEvlBHpRdQ/s01Kbr783MeSBAmaiig2yWA9gEjkX4wZ3fAyypZ3x50q62yxf4oOGqPSPVKZylJf8j5yQ+AhCoFU5Pthk4yDn1ESotGjwb+uptmBlU2w0GWBRmgXqWHBujuVWeuvRdAK/QPUVYXim+fiDEJY0p94zidZI48EypvEquFDtOY5EpSEkuJx5inYwsVYDFuEVh3/CzSt1wC+Adq4P7b1C8/kDnFnxkjQFni0eyfGX6vvejB6+qTZikmJj1p5xX0f6oL9SkBAnju6wUt2ypckZjuL2v2nmVZ7jzVCa/mmE7mabFRov+VpMkmLB6mO+LlMsLalXQKIASYC+v4Xgbov+xXCEhQr6moq/IjsuKiC1wI4hb1C9dCvD40xPrEIEzsk/4JsLi4TVpV57XcaIwZQ=="
          }
        ]
      },
      "finishReason": "STOP",
      "citationMetadata": {
        "citations": [
          {
            "startIndex": 785,
            "endIndex": 1106,
            "uri": "https://github.com/s-m-quadri/geca-labs"
          }
        ]
      }
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 32,
    "candidatesTokenCount": 519,
    "totalTokenCount": 887,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 32
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 519
      }
    ],
    "thoughtsTokenCount": 336
  },
  "modelVersion": "gemini-3.8-flash",
  "createTime": "2026-09-02T16:35:51.064669Z",
  "responseId": "Z1CYap35A6-prb8Plfe7yAg",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

Generate ContentChat Completions

▶contents\[]

`array`required

▶systemInstruction{}

`object`

▶generationConfig{}

`object`

▶safetySettings\[]

`array`

▶tools\[]

`array`

toolConfig

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

▶candidates\[]

`array`

▶usageMetadata{}

`object`

modelVersion

`string`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash/#page","headline":"Gemini 3.8 Flash","description":"Our most intelligent Flash model, engineered for long-horizon software engineering, autonomous agents, and complex enterprise workflows.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Gemini 3.8 Flash-Lite TTS is a fast, cost-efficient text-to-speech model optimized for high-throughput production workloads.
title: Gemini 3.8 Flash-Lite TTS
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 3.8 Flash-Lite TTS

Text-to-Speech • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-lite-tts/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-3.8-flash-lite-tts`

- Third-party

Gemini 3.8 Flash-Lite TTS is a fast, cost-efficient text-to-speech model optimized for high-throughput production workloads.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 8,192 tokens |
| More information | [link ↗](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash-tts) |
| Pricing | <ul><li>Input text (per 1M tokens)$0.50</li><li>Cached input (per 1M tokens)$0.125</li><li>Output audio (per 1M tokens)$6.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-3.8-flash-lite-tts',
  { text: 'Hello, welcome to Cloudflare AI Gateway!' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.8-flash-lite-tts",
  "input": {
    "text": "Hello, welcome to Cloudflare AI Gateway!"
  }
}'
```

```json
{
  "audio": "https://examples.aig.cloudflare.com/google/gemini-3.8-flash-lite-tts/simple-text-to-speech.wav",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Expressive Pause** — Generate expressive speech with an inline vocal pause</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.8-flash-lite-tts',
  {
    text: 'Welcome to the future of voice. <short pause> Let us build something remarkable together.',
    voice: 'Puck',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.8-flash-lite-tts",
  "input": {
    "text": "Welcome to the future of voice. <short pause> Let us build something remarkable together.",
    "voice": "Puck"
  }
}'
```

```json
{
  "audio": "https://examples.aig.cloudflare.com/google/gemini-3.8-flash-lite-tts/expressive-pause.wav",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Narrated Passage** — Generate a longer narrated passage with a different voice</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.8-flash-lite-tts',
  {
    text: 'At sunrise, the research team opened the observatory and watched the first light move across the valley. Every sensor came online in sequence, and the quiet room filled with the soft rhythm of discovery.',
    voice: 'Charon',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.8-flash-lite-tts",
  "input": {
    "text": "At sunrise, the research team opened the observatory and watched the first light move across the valley. Every sensor came online in sequence, and the quiet room filled with the soft rhythm of discovery.",
    "voice": "Charon"
  }
}'
```

```json
{
  "audio": "https://examples.aig.cloudflare.com/google/gemini-3.8-flash-lite-tts/narrated-passage.wav",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**French Greeting** — Generate speech from a French greeting using a distinct voice</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.8-flash-lite-tts',
  {
    text: "Bonjour et bienvenue. Nous sommes ravis de vous accompagner aujourd'hui.",
    voice: 'Kore',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.8-flash-lite-tts",
  "input": {
    "text": "Bonjour et bienvenue. Nous sommes ravis de vous accompagner aujourd'\''hui.",
    "voice": "Kore"
  }
}'
```

```json
{
  "audio": "https://examples.aig.cloudflare.com/google/gemini-3.8-flash-lite-tts/french-greeting.wav",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

text

`string`requiredmaxLength: 10000The text to convert to speech. Maximum 10,000 characters.

voice

`string`enum: Zephyr, Puck, Charon, Kore, Fenrir, Leda, Orus, Aoede, Callirrhoe, Autonoe, Enceladus, Iapetus, Umbriel, Algieba, Despina, Erinome, Algenib, Rasalgethi, Laomedeia, Achernar, Alnilam, Schedar, Gacrux, Pulcherrima, Achird, Zubenelgenubi, Vindemiatrix, Sadachbia, Sadaltager, SulafatThe voice to use for speech synthesis

temperature

`number`minimum: 0maximum: 2Controls randomness in generation (0-2)

topP

`number`minimum: 0maximum: 1Nucleus sampling threshold (0-1). Tokens with cumulative probability up to topP are considered

topK

`integer`exclusiveMinimum: 0maximum: 9007199254740991Only sample from the top K tokens. Smaller K = more focused, larger K = more diverse

maxOutputTokens

`integer`exclusiveMinimum: 0maximum: 9007199254740991Maximum number of tokens to generate

▶stopSequences\[]

`array`Sequences where the model will stop generating further tokens

audio

`string`Base64-encoded audio data (WAV format)

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-lite-tts/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-lite-tts/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-lite-tts/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-lite-tts/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-lite-tts/#page","headline":"Gemini 3.8 Flash-Lite TTS","description":"Gemini 3.8 Flash-Lite TTS is a fast, cost-efficient text-to-speech model optimized for high-throughput production workloads.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-lite-tts/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Gemini 3.8 Flash TTS is Google's flagship text-to-speech model for expressive, natural speech generation.
title: Gemini 3.8 Flash TTS
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini 3.8 Flash TTS

Text-to-Speech • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-tts/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-3.8-flash-tts`

- Third-party

Gemini 3.8 Flash TTS is Google's flagship text-to-speech model for expressive, natural speech generation.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 8,192 tokens |
| More information | [link ↗](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash-tts) |
| Pricing | <ul><li>Input text (per 1M tokens)$0.50</li><li>Cached input (per 1M tokens)$0.125</li><li>Output audio (per 1M tokens)$9.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-3.8-flash-tts',
  { text: 'Hello, welcome to Cloudflare AI Gateway!' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.8-flash-tts",
  "input": {
    "text": "Hello, welcome to Cloudflare AI Gateway!"
  }
}'
```

```json
{
  "audio": "https://examples.aig.cloudflare.com/google/gemini-3.8-flash-tts/simple-text-to-speech.wav",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Expressive Pause** — Generate expressive speech with an inline vocal pause</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.8-flash-tts',
  {
    text: 'Welcome to the future of voice. <short pause> Let us build something remarkable together.',
    voice: 'Puck',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.8-flash-tts",
  "input": {
    "text": "Welcome to the future of voice. <short pause> Let us build something remarkable together.",
    "voice": "Puck"
  }
}'
```

```json
{
  "audio": "https://examples.aig.cloudflare.com/google/gemini-3.8-flash-tts/expressive-pause.wav",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Narrated Passage** — Generate a longer narrated passage with a different voice</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.8-flash-tts',
  {
    text: 'At sunrise, the research team opened the observatory and watched the first light move across the valley. Every sensor came online in sequence, and the quiet room filled with the soft rhythm of discovery.',
    voice: 'Charon',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.8-flash-tts",
  "input": {
    "text": "At sunrise, the research team opened the observatory and watched the first light move across the valley. Every sensor came online in sequence, and the quiet room filled with the soft rhythm of discovery.",
    "voice": "Charon"
  }
}'
```

```json
{
  "audio": "https://examples.aig.cloudflare.com/google/gemini-3.8-flash-tts/narrated-passage.wav",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**French Greeting** — Generate speech from a French greeting using a distinct voice</summary>



```ts
const response = await env.AI.run(
  'google/gemini-3.8-flash-tts',
  {
    text: "Bonjour et bienvenue. Nous sommes ravis de vous accompagner aujourd'hui.",
    voice: 'Kore',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.8-flash-tts",
  "input": {
    "text": "Bonjour et bienvenue. Nous sommes ravis de vous accompagner aujourd'\''hui.",
    "voice": "Kore"
  }
}'
```

```json
{
  "audio": "https://examples.aig.cloudflare.com/google/gemini-3.8-flash-tts/french-greeting.wav",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

text

`string`requiredmaxLength: 10000The text to convert to speech. Maximum 10,000 characters.

voice

`string`enum: Zephyr, Puck, Charon, Kore, Fenrir, Leda, Orus, Aoede, Callirrhoe, Autonoe, Enceladus, Iapetus, Umbriel, Algieba, Despina, Erinome, Algenib, Rasalgethi, Laomedeia, Achernar, Alnilam, Schedar, Gacrux, Pulcherrima, Achird, Zubenelgenubi, Vindemiatrix, Sadachbia, Sadaltager, SulafatThe voice to use for speech synthesis

temperature

`number`minimum: 0maximum: 2Controls randomness in generation (0-2)

topP

`number`minimum: 0maximum: 1Nucleus sampling threshold (0-1). Tokens with cumulative probability up to topP are considered

topK

`integer`exclusiveMinimum: 0maximum: 9007199254740991Only sample from the top K tokens. Smaller K = more focused, larger K = more diverse

maxOutputTokens

`integer`exclusiveMinimum: 0maximum: 9007199254740991Maximum number of tokens to generate

▶stopSequences\[]

`array`Sequences where the model will stop generating further tokens

audio

`string`Base64-encoded audio data (WAV format)

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-tts/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-tts/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-tts/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-tts/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-tts/#page","headline":"Gemini 3.8 Flash TTS","description":"Gemini 3.8 Flash TTS is Google's flagship text-to-speech model for expressive, natural speech generation.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.8-flash-tts/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: High-performance multimodal video generation and editing model with conversational controls and generated audio.
title: Gemini Omni Flash 1.1
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini Omni Flash 1.1

Text-to-Video • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-omni-1.1-flash/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-omni-1.1-flash`

- Third-party

High-performance multimodal video generation and editing model with conversational controls and generated audio.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| Pricing | <ul><li>Input text (per 1M tokens)$1.50</li><li>Input image (per 1M tokens)$1.50</li><li>Input audio (per 1M tokens)$1.50</li><li>Input video (per 1M tokens)$1.50</li><li>Output text (per 1M tokens)$9.00</li><li>Reasoning (per 1M tokens)$9.00</li><li>Output video (per 1M tokens)$17.50</li><li>Default (per second)$1.50</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-omni-1.1-flash',
  {
    text: 'A marble rolling fast on a chain reaction style track, continuous smooth shot.',
    aspect_ratio: '16:9',
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-omni-1.1-flash",
  "input": {
    "text": "A marble rolling fast on a chain reaction style track, continuous smooth shot.",
    "aspect_ratio": "16:9",
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/google/gemini-omni-1.1-flash/text-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Portrait city** — Generate a portrait-format cinematic city scene</summary>



```ts
const response = await env.AI.run(
  'google/gemini-omni-1.1-flash',
  {
    text: 'A futuristic city with neon lights and flying cars, cinematic camera movement and atmospheric haze.',
    aspect_ratio: '9:16',
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-omni-1.1-flash",
  "input": {
    "text": "A futuristic city with neon lights and flying cars, cinematic camera movement and atmospheric haze.",
    "aspect_ratio": "9:16",
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/google/gemini-omni-1.1-flash/portrait-city.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Mountain sunrise** — Generate a high-resolution landscape nature scene</summary>



```ts
const response = await env.AI.run(
  'google/gemini-omni-1.1-flash',
  {
    text: 'A drone shot flying over a mountain landscape at sunrise, golden light reflecting across a misty valley.',
    aspect_ratio: '16:9',
    resolution: '1080p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-omni-1.1-flash",
  "input": {
    "text": "A drone shot flying over a mountain landscape at sunrise, golden light reflecting across a misty valley.",
    "aspect_ratio": "16:9",
    "resolution": "1080p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/google/gemini-omni-1.1-flash/mountain-sunrise.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Chain reaction** — Generate a low-resolution landscape action scene</summary>



```ts
const response = await env.AI.run(
  'google/gemini-omni-1.1-flash',
  {
    text: 'A marble rolling quickly along a wooden track, knocking through a playful chain reaction in one continuous shot.',
    aspect_ratio: '16:9',
    resolution: '360p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-omni-1.1-flash",
  "input": {
    "text": "A marble rolling quickly along a wooden track, knocking through a playful chain reaction in one continuous shot.",
    "aspect_ratio": "16:9",
    "resolution": "360p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/google/gemini-omni-1.1-flash/chain-reaction.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

text

`string`Text prompt or editing instruction

image

`string`First-frame or primary reference image

last\_frame

`string`Last-frame reference image

▶reference\_images\[]

`array`maxItems: 10

video

`string`Reference video for editing or extension

audio

`string`Reference audio input

previous\_interaction\_id

`string`

aspect\_ratio

`string`enum: 16:9, 9:16

resolution

`string`enum: 360p, 720p, 1080p, 4k

▶video

`one of`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-omni-1.1-flash/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-omni-1.1-flash/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-omni-1.1-flash/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-omni-1.1-flash/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-omni-1.1-flash/#page","headline":"Gemini Omni Flash 1.1","description":"High-performance multimodal video generation and editing model with conversational controls and generated audio.","url":"https://developers.cloudflare.com/ai/models/google/gemini-omni-1.1-flash/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Preview high-performance multimodal video generation and editing model with conversational controls and generated audio.
title: Gemini Omni Flash
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Gemini Omni Flash

Text-to-Video • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/gemini-omni-flash/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/gemini-omni-flash`

- Third-party

Preview high-performance multimodal video generation and editing model with conversational controls and generated audio.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| Pricing | <ul><li>Input text (per 1M tokens)$1.50</li><li>Input image (per 1M tokens)$1.50</li><li>Input audio (per 1M tokens)$1.50</li><li>Input video (per 1M tokens)$1.50</li><li>Output text (per 1M tokens)$9.00</li><li>Reasoning (per 1M tokens)$9.00</li><li>Output video (per 1M tokens)$17.50</li><li>Default (per second)$1.50</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/gemini-omni-flash',
  {
    text: 'A school of silver fish moving through a sunlit coral reef, slow cinematic tracking shot with drifting particles.',
    aspect_ratio: '16:9',
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-omni-flash",
  "input": {
    "text": "A school of silver fish moving through a sunlit coral reef, slow cinematic tracking shot with drifting particles.",
    "aspect_ratio": "16:9",
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/google/gemini-omni-flash/underwater-reef.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Breakfast robot** — Generate a portrait-format character scene</summary>



```ts
const response = await env.AI.run(
  'google/gemini-omni-flash',
  {
    text: 'A friendly home robot preparing breakfast in a bright modern kitchen, gentle handheld camera movement.',
    aspect_ratio: '9:16',
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-omni-flash",
  "input": {
    "text": "A friendly home robot preparing breakfast in a bright modern kitchen, gentle handheld camera movement.",
    "aspect_ratio": "9:16",
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/google/gemini-omni-flash/breakfast-robot.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Desert train** — Generate a high-resolution desert scene</summary>



```ts
const response = await env.AI.run(
  'google/gemini-omni-flash',
  {
    text: 'A vintage train crossing a vast desert at golden hour, dust glowing in the sunset as the camera sweeps alongside.',
    aspect_ratio: '16:9',
    resolution: '1080p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-omni-flash",
  "input": {
    "text": "A vintage train crossing a vast desert at golden hour, dust glowing in the sunset as the camera sweeps alongside.",
    "aspect_ratio": "16:9",
    "resolution": "1080p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/google/gemini-omni-flash/desert-train.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Northern lights** — Generate a low-resolution night landscape</summary>



```ts
const response = await env.AI.run(
  'google/gemini-omni-flash',
  {
    text: 'Colorful northern lights dancing above a frozen lake, a small cabin glowing warmly in the foreground.',
    aspect_ratio: '16:9',
    resolution: '360p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-omni-flash",
  "input": {
    "text": "Colorful northern lights dancing above a frozen lake, a small cabin glowing warmly in the foreground.",
    "aspect_ratio": "16:9",
    "resolution": "360p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/google/gemini-omni-flash/northern-lights.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

text

`string`Text prompt or editing instruction

image

`string`First-frame or primary reference image

last\_frame

`string`Last-frame reference image

▶reference\_images\[]

`array`maxItems: 10

video

`string`Reference video for editing or extension

audio

`string`Reference audio input

previous\_interaction\_id

`string`

aspect\_ratio

`string`enum: 16:9, 9:16

resolution

`string`enum: 360p, 720p, 1080p, 4k

▶video

`one of`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/gemini-omni-flash/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-omni-flash/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/gemini-omni-flash/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/gemini-omni-flash/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-omni-flash/#page","headline":"Gemini Omni Flash","description":"Preview high-performance multimodal video generation and editing model with conversational controls and generated audio.","url":"https://developers.cloudflare.com/ai/models/google/gemini-omni-flash/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Google's fast image generation model producing high-quality images from text prompts.
title: Nano Banana
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Nano Banana

Text-to-Image • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/nano-banana/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/nano-banana`

- Third-party
- Zero data retention

Google's fast image generation model producing high-quality images from text prompts.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/imagen/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Input (per 1M tokens)$0.30</li><li>Output (per 1M tokens)$30.00</li><li>Cached input (per 1M tokens)$0.03</li><li>Cache creation (per 1M tokens)$0.083333</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/nano-banana',
  {
    prompt:
      'A cozy coffee shop interior with warm lighting, plants hanging from the ceiling, and a cat sleeping on a velvet armchair by the window',
    aspect_ratio: '16:9',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana",
  "input": {
    "prompt": "A cozy coffee shop interior with warm lighting, plants hanging from the ceiling, and a cat sleeping on a velvet armchair by the window",
    "aspect_ratio": "16:9"
  }
}'
```

![Cozy Coffee Shop](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/cozy-coffee-shop.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/cozy-coffee-shop.png"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Vintage Tokyo Poster** — Retro travel poster style illustration</summary>



```ts
const response = await env.AI.run(
  'google/nano-banana',
  {
    prompt:
      'A vintage travel poster for Tokyo, Japan in the style of 1960s airline advertisements, with Mount Fuji in the background and cherry blossoms framing the scene',
    aspect_ratio: '9:16',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana",
  "input": {
    "prompt": "A vintage travel poster for Tokyo, Japan in the style of 1960s airline advertisements, with Mount Fuji in the background and cherry blossoms framing the scene",
    "aspect_ratio": "9:16"
  }
}'
```

![Vintage Tokyo Poster](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/vintage-tokyo-poster.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/vintage-tokyo-poster.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Dewdrops Macro** — Photorealistic macro photography</summary>



```ts
const response = await env.AI.run(
  'google/nano-banana',
  {
    prompt:
      'A photorealistic macro shot of dewdrops on a spider web at sunrise, with rainbow light refracting through each droplet',
    aspect_ratio: '1:1',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana",
  "input": {
    "prompt": "A photorealistic macro shot of dewdrops on a spider web at sunrise, with rainbow light refracting through each droplet",
    "aspect_ratio": "1:1"
  }
}'
```

![Dewdrops Macro](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/dewdrops-macro.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/dewdrops-macro.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Pixel Art Marketplace** — Isometric pixel art scene</summary>



```ts
const response = await env.AI.run(
  'google/nano-banana',
  {
    prompt:
      'An isometric pixel art scene of a bustling medieval marketplace with merchants, knights, and a dragon perched on the town hall roof',
    aspect_ratio: '1:1',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana",
  "input": {
    "prompt": "An isometric pixel art scene of a bustling medieval marketplace with merchants, knights, and a dragon perched on the town hall roof",
    "aspect_ratio": "1:1"
  }
}'
```

![Pixel Art Marketplace](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/pixel-art-marketplace.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/pixel-art-marketplace.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**High Resolution Landscape** — Generate a high-resolution 4K landscape image</summary>



```ts
const response = await env.AI.run(
  'google/nano-banana',
  {
    prompt:
      'A dramatic mountain landscape at golden hour with snow-capped peaks and a crystal clear alpine lake',
    aspect_ratio: '16:9',
    image_size: '4K',
    output_format: 'png',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana",
  "input": {
    "prompt": "A dramatic mountain landscape at golden hour with snow-capped peaks and a crystal clear alpine lake",
    "aspect_ratio": "16:9",
    "image_size": "4K",
    "output_format": "png"
  }
}'
```

![High Resolution Landscape](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/high-resolution-landscape.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana/high-resolution-landscape.png"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

▶image\_input\[]

`array`maxItems: 3

aspect\_ratio

`string`enum: 1:1, 3:2, 2:3, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9

output\_format

`string`enum: jpg, png, webp

image\_size

`string`enum: 1K, 2K, 4K

image

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/nano-banana/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/nano-banana/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/nano-banana/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/nano-banana/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/nano-banana/#page","headline":"Nano Banana","description":"Google's fast image generation model producing high-quality images from text prompts.","url":"https://developers.cloudflare.com/ai/models/google/nano-banana/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Google's second-generation image generation model with improved quality and speed.
title: Nano Banana 2
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Nano Banana 2

Text-to-Image • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/nano-banana-2/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/nano-banana-2`

- Third-party
- Zero data retention

Google's second-generation image generation model with improved quality and speed.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/imagen/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Input (per 1M tokens)$0.50</li><li>Output (per 1M tokens)$60.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/nano-banana-2',
  {
    prompt:
      'A futuristic cyberpunk city at night with towering skyscrapers, neon signs in Japanese and English, flying cars, and rain-slicked streets reflecting colorful lights',
    aspect_ratio: '16:9',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana-2",
  "input": {
    "prompt": "A futuristic cyberpunk city at night with towering skyscrapers, neon signs in Japanese and English, flying cars, and rain-slicked streets reflecting colorful lights",
    "aspect_ratio": "16:9"
  }
}'
```

![Futuristic City](https://examples.aig.cloudflare.com/google/nano-banana-2/futuristic-city.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/google/nano-banana-2/futuristic-city.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Abstract Art** — Modern abstract expressionist painting</summary>



```ts
const response = await env.AI.run(
  'google/nano-banana-2',
  {
    prompt:
      'An abstract expressionist painting with bold splashes of cobalt blue, crimson red, and gold leaf accents on a large canvas',
    aspect_ratio: '1:1',
    output_format: 'jpg',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana-2",
  "input": {
    "prompt": "An abstract expressionist painting with bold splashes of cobalt blue, crimson red, and gold leaf accents on a large canvas",
    "aspect_ratio": "1:1",
    "output_format": "jpg"
  }
}'
```

![Abstract Art](https://examples.aig.cloudflare.com/google/nano-banana-2/abstract-art.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/google/nano-banana-2/abstract-art.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**With Google Search** — Use web search grounding for current events</summary>



```ts
const response = await env.AI.run(
  'google/nano-banana-2',
  {
    prompt: 'An illustration of the latest Mars rover exploring the Martian surface',
    aspect_ratio: '16:9',
    google_search: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana-2",
  "input": {
    "prompt": "An illustration of the latest Mars rover exploring the Martian surface",
    "aspect_ratio": "16:9",
    "google_search": true
  }
}'
```

![With Google Search](https://examples.aig.cloudflare.com/google/nano-banana-2/with-google-search.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/google/nano-banana-2/with-google-search.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**High Resolution Portrait** — 4K portrait with specific aspect ratio</summary>



```ts
const response = await env.AI.run(
  'google/nano-banana-2',
  {
    prompt:
      'A professional studio portrait of a woman with dramatic side lighting, wearing elegant jewelry',
    aspect_ratio: '3:4',
    output_format: 'jpg',
    resolution: '4K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana-2",
  "input": {
    "prompt": "A professional studio portrait of a woman with dramatic side lighting, wearing elegant jewelry",
    "aspect_ratio": "3:4",
    "output_format": "jpg",
    "resolution": "4K"
  }
}'
```

![High Resolution Portrait](https://examples.aig.cloudflare.com/google/nano-banana-2/high-resolution-portrait.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/google/nano-banana-2/high-resolution-portrait.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`required

▶image\_input\[]

`array`maxItems: 3

aspect\_ratio

`string`enum: match\_input\_image, 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9

output\_format

`string`enum: jpg, png

resolution

`string`enum: 1K, 2K, 4K

google\_search

`boolean`

image\_search

`boolean`

image

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/nano-banana-2/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/nano-banana-2/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/nano-banana-2/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/nano-banana-2/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/nano-banana-2/#page","headline":"Nano Banana 2","description":"Google's second-generation image generation model with improved quality and speed.","url":"https://developers.cloudflare.com/ai/models/google/nano-banana-2/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Google's fastest Gemini image generation model for rapid image creation and iteration.
title: Nano Banana 2 Lite
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Nano Banana 2 Lite

Text-to-Image • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/nano-banana-2-lite/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/nano-banana-2-lite`

- Third-party
- Zero data retention

Google's fastest Gemini image generation model for rapid image creation and iteration.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 65,536 tokens |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/imagen/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Input (per 1M tokens)$0.25</li><li>Output (per 1M tokens)$30.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/nano-banana-2-lite',
  {
    prompt:
      'A playful concept sketch of a compact solar-powered delivery robot rolling through a leafy neighborhood, bright morning light, clean product design',
    aspect_ratio: '16:9',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana-2-lite",
  "input": {
    "prompt": "A playful concept sketch of a compact solar-powered delivery robot rolling through a leafy neighborhood, bright morning light, clean product design",
    "aspect_ratio": "16:9"
  }
}'
```

![Concept Sketch](https://examples.aig.cloudflare.com/google/nano-banana-2-lite/concept-sketch.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/google/nano-banana-2-lite/concept-sketch.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Product Render** — Create a square PNG product image</summary>



```ts
const response = await env.AI.run(
  'google/nano-banana-2-lite',
  {
    prompt:
      'A studio product render of translucent wireless earbuds in a frosted glass charging case, soft gradient background, premium advertising style',
    aspect_ratio: '1:1',
    output_format: 'png',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana-2-lite",
  "input": {
    "prompt": "A studio product render of translucent wireless earbuds in a frosted glass charging case, soft gradient background, premium advertising style",
    "aspect_ratio": "1:1",
    "output_format": "png"
  }
}'
```

![Product Render](https://examples.aig.cloudflare.com/google/nano-banana-2-lite/product-render.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/google/nano-banana-2-lite/product-render.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`required

▶image\_input\[]

`array`maxItems: 3

aspect\_ratio

`string`enum: match\_input\_image, 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9

output\_format

`string`enum: jpg, png

resolution

`string`enum: 1K, 2K, 4K

image

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/nano-banana-2-lite/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/nano-banana-2-lite/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/nano-banana-2-lite/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/nano-banana-2-lite/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/nano-banana-2-lite/#page","headline":"Nano Banana 2 Lite","description":"Google's fastest Gemini image generation model for rapid image creation and iteration.","url":"https://developers.cloudflare.com/ai/models/google/nano-banana-2-lite/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Google's higher-quality image generation model with improved detail and prompt adherence.
title: Nano Banana Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Nano Banana Pro

Text-to-Image • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/nano-banana-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/nano-banana-pro`

- Third-party
- Zero data retention

Google's higher-quality image generation model with improved detail and prompt adherence.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/imagen/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Output (per 1M tokens)$120.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/nano-banana-pro',
  {
    prompt:
      'A sleek modern wireless headphone on a minimalist white marble surface with soft studio lighting and subtle shadows',
    aspect_ratio: '1:1',
    output_format: 'png',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana-pro",
  "input": {
    "prompt": "A sleek modern wireless headphone on a minimalist white marble surface with soft studio lighting and subtle shadows",
    "aspect_ratio": "1:1",
    "output_format": "png"
  }
}'
```

![Product Photography](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-pro/product-photography.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-pro/product-photography.png"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Fantasy Illustration** — Epic fantasy scene</summary>



```ts
const response = await env.AI.run(
  'google/nano-banana-pro',
  {
    prompt:
      'An epic fantasy illustration of a wizard casting a spell in an ancient library, magical runes floating in the air, dust motes catching golden light streaming through stained glass windows',
    aspect_ratio: '16:9',
    image_size: '2K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana-pro",
  "input": {
    "prompt": "An epic fantasy illustration of a wizard casting a spell in an ancient library, magical runes floating in the air, dust motes catching golden light streaming through stained glass windows",
    "aspect_ratio": "16:9",
    "image_size": "2K"
  }
}'
```

![Fantasy Illustration](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-pro/fantasy-illustration.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-pro/fantasy-illustration.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Architectural Visualization** — Modern architecture render</summary>



```ts
const response = await env.AI.run(
  'google/nano-banana-pro',
  {
    prompt:
      'A photorealistic architectural visualization of a modern glass house perched on a cliff overlooking the ocean at sunset',
    aspect_ratio: '16:9',
    image_size: '4K',
    output_format: 'jpg',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana-pro",
  "input": {
    "prompt": "A photorealistic architectural visualization of a modern glass house perched on a cliff overlooking the ocean at sunset",
    "aspect_ratio": "16:9",
    "image_size": "4K",
    "output_format": "jpg"
  }
}'
```

![Architectural Visualization](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-pro/architectural-visualization.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-pro/architectural-visualization.jpg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Character Design** — Game character concept art</summary>



```ts
const response = await env.AI.run(
  'google/nano-banana-pro',
  {
    prompt:
      'A detailed character design sheet for a steampunk inventor, showing front view, side view, and detail callouts for mechanical arm and goggles',
    aspect_ratio: '3:2',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/nano-banana-pro",
  "input": {
    "prompt": "A detailed character design sheet for a steampunk inventor, showing front view, side view, and detail callouts for mechanical arm and goggles",
    "aspect_ratio": "3:2"
  }
}'
```

![Character Design](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-pro/character-design.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__nano-banana-pro/character-design.png"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

▶image\_input\[]

`array`maxItems: 3

aspect\_ratio

`string`enum: 1:1, 3:2, 2:3, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9

output\_format

`string`enum: jpg, png, webp

image\_size

`string`enum: 1K, 2K, 4K

image

`string`format: uri

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/nano-banana-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/nano-banana-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/nano-banana-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/nano-banana-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/nano-banana-pro/#page","headline":"Nano Banana Pro","description":"Google's higher-quality image generation model with improved detail and prompt adherence.","url":"https://developers.cloudflare.com/ai/models/google/nano-banana-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Google's latest video generation model with improved quality, motion, and audio generation.
title: Veo 3.1
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Veo 3.1

Text-to-Video • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/veo-3.1/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/veo-3.1`

- Third-party
- Zero data retention

Google's latest video generation model with improved quality, motion, and audio generation.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/veo/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.40</li><li>@720p (per second)$0.20</li><li>@1080p (per second)$0.20</li><li>@4k (per second)$0.40</li><li>@720p w/ audio (per second)$0.40</li><li>@1080p w/ audio (per second)$0.40</li><li>@4k w/ audio (per second)$0.60</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/veo-3.1',
  {
    prompt:
      'A majestic eagle soaring over snow-capped mountains, tracking shot following the bird as it glides through clouds',
    aspect_ratio: '16:9',
    duration: '8s',
    generate_audio: true,
    resolution: '1080p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/veo-3.1",
  "input": {
    "prompt": "A majestic eagle soaring over snow-capped mountains, tracking shot following the bird as it glides through clouds",
    "aspect_ratio": "16:9",
    "duration": "8s",
    "generate_audio": true,
    "resolution": "1080p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__veo-3.1/nature-documentary.mp4"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Urban Time-lapse** — City life time-lapse video</summary>



```ts
const response = await env.AI.run(
  'google/veo-3.1',
  {
    prompt:
      'A time-lapse of a busy city intersection at night, car lights creating streaks, people walking in fast motion',
    aspect_ratio: '16:9',
    duration: '6s',
    generate_audio: true,
    resolution: '1080p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/veo-3.1",
  "input": {
    "prompt": "A time-lapse of a busy city intersection at night, car lights creating streaks, people walking in fast motion",
    "aspect_ratio": "16:9",
    "duration": "6s",
    "generate_audio": true,
    "resolution": "1080p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__veo-3.1/urban-time-lapse.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Abstract Art** — Abstract motion graphics</summary>



```ts
const response = await env.AI.run(
  'google/veo-3.1',
  {
    prompt:
      'Colorful ink drops falling into water in slow motion, creating organic swirling patterns',
    aspect_ratio: '16:9',
    duration: '6s',
    generate_audio: false,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/veo-3.1",
  "input": {
    "prompt": "Colorful ink drops falling into water in slow motion, creating organic swirling patterns",
    "aspect_ratio": "16:9",
    "duration": "6s",
    "generate_audio": false,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__veo-3.1/abstract-art.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Food Video** — Appetizing food footage</summary>



```ts
const response = await env.AI.run(
  'google/veo-3.1',
  {
    prompt: 'Melted chocolate being poured over fresh strawberries in slow motion, rich and glossy',
    aspect_ratio: '9:16',
    duration: '4s',
    generate_audio: true,
    resolution: '1080p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/veo-3.1",
  "input": {
    "prompt": "Melted chocolate being poured over fresh strawberries in slow motion, rich and glossy",
    "aspect_ratio": "9:16",
    "duration": "4s",
    "generate_audio": true,
    "resolution": "1080p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__veo-3.1/food-video.mp4"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`requiredText prompt describing the video to generate

image\_input

`string`Base64-encoded reference image for i2v

duration

`string`requireddefault: 6senum: 4s, 6s, 8sVideo duration

aspect\_ratio

`string`requireddefault: 16:9enum: 16:9, 9:16, 1:1Video aspect ratio

resolution

`string`requireddefault: 720penum: 720p, 1080pVideo resolution

generate\_audio

`boolean`requireddefault: trueWhether to generate audio with the video

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/veo-3.1/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/veo-3.1/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/veo-3.1/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/veo-3.1/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/veo-3.1/#page","headline":"Veo 3.1","description":"Google's latest video generation model with improved quality, motion, and audio generation.","url":"https://developers.cloudflare.com/ai/models/google/veo-3.1/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: A faster version of Veo 3.1 optimized for lower latency while maintaining high-quality video and audio output.
title: Veo 3.1 Fast
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Google logo](https://developers.cloudflare.com/_astro/google.DyXKPTPP.svg)

# Veo 3.1 Fast

Text-to-Video • Google

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/google/veo-3.1-fast/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`google/veo-3.1-fast`

- Third-party
- Zero data retention

A faster version of Veo 3.1 optimized for lower latency while maintaining high-quality video and audio output.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://ai.google.dev/gemini-api/terms) |
| More information | [link ↗](https://deepmind.google/technologies/veo/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.08</li><li>@720p (per second)$0.08</li><li>@1080p (per second)$0.10</li><li>@4k (per second)$0.25</li><li>@720p w/ audio (per second)$0.10</li><li>@1080p w/ audio (per second)$0.12</li><li>@4k w/ audio (per second)$0.30</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'google/veo-3.1-fast',
  {
    prompt: 'A butterfly landing on a colorful flower in a garden',
    aspect_ratio: '16:9',
    duration: '6s',
    generate_audio: true,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/veo-3.1-fast",
  "input": {
    "prompt": "A butterfly landing on a colorful flower in a garden",
    "aspect_ratio": "16:9",
    "duration": "6s",
    "generate_audio": true,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__veo-3.1-fast/quick-demo.mp4"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Social Content** — Quick vertical video for social media</summary>



```ts
const response = await env.AI.run(
  'google/veo-3.1-fast',
  {
    prompt: 'Aesthetic morning routine: sun rays through curtains, coffee being poured',
    aspect_ratio: '9:16',
    duration: '6s',
    generate_audio: true,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/veo-3.1-fast",
  "input": {
    "prompt": "Aesthetic morning routine: sun rays through curtains, coffee being poured",
    "aspect_ratio": "9:16",
    "duration": "6s",
    "generate_audio": true,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__veo-3.1-fast/social-content.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Motion Graphics** — Quick animated graphics</summary>



```ts
const response = await env.AI.run(
  'google/veo-3.1-fast',
  {
    prompt: 'Glowing neon lines forming geometric patterns on a dark background',
    aspect_ratio: '16:9',
    duration: '4s',
    generate_audio: false,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/veo-3.1-fast",
  "input": {
    "prompt": "Glowing neon lines forming geometric patterns on a dark background",
    "aspect_ratio": "16:9",
    "duration": "4s",
    "generate_audio": false,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__veo-3.1-fast/motion-graphics.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Ambient Scene** — Relaxing background video</summary>



```ts
const response = await env.AI.run(
  'google/veo-3.1-fast',
  {
    prompt: 'Rain falling on a window with a blurred city skyline in the background at night',
    aspect_ratio: '16:9',
    duration: '8s',
    generate_audio: true,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/veo-3.1-fast",
  "input": {
    "prompt": "Rain falling on a window with a blurred city skyline in the background at night",
    "aspect_ratio": "16:9",
    "duration": "8s",
    "generate_audio": true,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/google__veo-3.1-fast/ambient-scene.mp4"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`requiredText prompt describing the video to generate

image\_input

`string`Base64-encoded reference image for i2v

duration

`string`requireddefault: 6senum: 4s, 6s, 8sVideo duration

aspect\_ratio

`string`requireddefault: 16:9enum: 16:9, 9:16, 1:1Video aspect ratio

resolution

`string`requireddefault: 720penum: 720p, 1080pVideo resolution

generate\_audio

`boolean`requireddefault: trueWhether to generate audio with the video

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/google/veo-3.1-fast/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/google/veo-3.1-fast/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/google/veo-3.1-fast/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/google/veo-3.1-fast/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/veo-3.1-fast/#page","headline":"Veo 3.1 Fast","description":"A faster version of Veo 3.1 optimized for lower latency while maintaining high-quality video and audio output.","url":"https://developers.cloudflare.com/ai/models/google/veo-3.1-fast/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Highest-quality text-to-speech with under 200ms latency, emotion control, and 15-language support.
title: Inworld TTS 1.5 Max
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Inworld logo](https://developers.cloudflare.com/_astro/inworld.BDwMAXI2.svg)

# Inworld TTS 1.5 Max

Text-to-Speech • Inworld

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-max/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`inworld/tts-1.5-max`

- Third-party
- Zero data retention

Highest-quality text-to-speech with under 200ms latency, emotion control, and 15-language support.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://inworld.ai/terms) |
| More information | [link ↗](https://inworld.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per character$0.000035</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'inworld/tts-1.5-max',
  {
    output_format: 'mp3',
    temperature: 1,
    text: 'Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.',
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-1.5-max",
  "input": {
    "output_format": "mp3",
    "temperature": 1,
    "text": "Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-1.5-max/simple-speech.mp3"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Slow Narration** — Slower speech for narration</summary>



```ts
const response = await env.AI.run(
  'inworld/tts-1.5-max',
  {
    output_format: 'mp3',
    speaking_rate: 0.85,
    temperature: 1,
    text: 'In the beginning, the universe was a singularity of infinite density. Then, in a fraction of a second, it expanded into everything we know today.',
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-1.5-max",
  "input": {
    "output_format": "mp3",
    "speaking_rate": 0.85,
    "temperature": 1,
    "text": "In the beginning, the universe was a singularity of infinite density. Then, in a fraction of a second, it expanded into everything we know today.",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-1.5-max/slow-narration.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**High Quality Audio** — Higher sample rate for studio quality</summary>



```ts
const response = await env.AI.run(
  'inworld/tts-1.5-max',
  {
    output_format: 'mp3',
    sample_rate: 48000,
    temperature: 1,
    text: 'This recording is generated at studio quality for the best possible listening experience.',
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-1.5-max",
  "input": {
    "output_format": "mp3",
    "sample_rate": 48000,
    "temperature": 1,
    "text": "This recording is generated at studio quality for the best possible listening experience.",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-1.5-max/high-quality-audio.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**With Text Normalization** — Expand numbers and abbreviations before synthesis</summary>



```ts
const response = await env.AI.run(
  'inworld/tts-1.5-max',
  {
    apply_text_normalization: true,
    output_format: 'mp3',
    temperature: 1,
    text: 'The meeting is at 3:30 PM on Jan 15th, 2026. Please confirm by calling 555-0123.',
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-1.5-max",
  "input": {
    "apply_text_normalization": true,
    "output_format": "mp3",
    "temperature": 1,
    "text": "The meeting is at 3:30 PM on Jan 15th, 2026. Please confirm by calling 555-0123.",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-1.5-max/with-text-normalization.mp3"
  },
  "state": "Completed"
}
```

</details>

## Parameters

text

`string`requiredmaxLength: 2000The text to be synthesized into speech. Maximum input of 2,000 characters.

voice\_id

`string`requireddefault: Dennisenum: Loretta, Darlene, Marlene, Hank, Evelyn, Celeste, Pippa, Tessa, Liam, Callum, Hamish, Abby, Graham, Rupert, Mortimer, Snik, Anjali, Saanvi, Arjun, Claire, Oliver, Simon, Elliot, James, Serena, Gareth, Vinny, Lauren, Jessica, Ethan, Tyler, Jason, Chloe, Veronica, Victoria, Miranda, Sebastian, Victor, Malcolm, Nate, Brian, Amina, Kelsey, Derek, Evan, Kayla, Jake, Grant, Tristan, Nadia, Selene, Marcus, Riley, Damon, Cedric, Mia, Naomi, Jonah, Levi, Avery, Brandon, Conrad, Bianca, Lucian, Trevor, Alex, Ashley, Craig, Deborah, Dennis, Edward, Elizabeth, Hades, Julia, Pixie, Mark, Olivia, Priya, Ronald, Sarah, Shaun, Theodore, Timothy, Wendy, Dominus, Hana, Clive, Carter, Blake, Luna, Reed, Duncan, Felix, Eleanor, SophieThe ID of the voice to use for synthesizing speech. Defaults to Dennis.

output\_format

`string`requireddefault: mp3enum: mp3, opus, wav, flacThe output format for the audio. Supported formats are mp3, opus, wav, and flac. Defaults to mp3.

bit\_rate

`integer`minimum: -9007199254740991maximum: 9007199254740991Bits per second of the audio. Only for compressed audio formats (mp3, opus). The default is 128,000.

sample\_rate

`integer`minimum: -9007199254740991maximum: 9007199254740991The synthesis sample rate in hertz. Accepts: 8000, 16000, 22050, 24000, 32000, 44100, 48000. The default is 48,000.

speaking\_rate

`number`minimum: 0.5maximum: 1.5Speaking rate/speed, in the range \[0.5, 1.5]. The default is 1.0. We recommend using values above 0.8 to ensure high quality.

temperature

`number`requireddefault: 1minimum: 0.01maximum: 2Determines the degree of randomness when sampling audio tokens. Defaults to 1.0. Accepts values between 0 (exclusive) and 2 (inclusive). Higher values = more expressive, lower values = more deterministic.

timestamp\_type

`string`requireddefault: noneenum: none, word, characterControls timestamp metadata returned with the audio. "word" returns word-level timing, "character" returns character-level timing. Note: adds latency. Defaults to none.

apply\_text\_normalization

`boolean`When enabled, text normalization expands numbers, dates, times, and abbreviations before converting to speech. Turning this off may reduce latency.

audio

`string`URL to the generated audio file

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-max/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-max/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-max/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-max/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/inworld/tts-1.5-max/#page","headline":"Inworld TTS 1.5 Max","description":"Highest-quality text-to-speech with under 200ms latency, emotion control, and 15-language support.","url":"https://developers.cloudflare.com/ai/models/inworld/tts-1.5-max/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Ultra-fast, cost-efficient text-to-speech with approximately 120ms latency and 15-language support.
title: Inworld TTS 1.5 Mini
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Inworld logo](https://developers.cloudflare.com/_astro/inworld.BDwMAXI2.svg)

# Inworld TTS 1.5 Mini

Text-to-Speech • Inworld

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-mini/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`inworld/tts-1.5-mini`

- Third-party
- Zero data retention

Ultra-fast, cost-efficient text-to-speech with approximately 120ms latency and 15-language support.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://inworld.ai/terms) |
| More information | [link ↗](https://inworld.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per character$0.000015</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'inworld/tts-1.5-mini',
  {
    output_format: 'mp3',
    temperature: 1,
    text: 'Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.',
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-1.5-mini",
  "input": {
    "output_format": "mp3",
    "temperature": 1,
    "text": "Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-1.5-mini/simple-speech.mp3"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Fast Speech** — Speed up speech for quick playback</summary>



```ts
const response = await env.AI.run(
  'inworld/tts-1.5-mini',
  {
    output_format: 'mp3',
    speaking_rate: 1.4,
    temperature: 1,
    text: 'This is a fast-paced summary of the key findings from the quarterly report. Revenue is up fifteen percent and user growth exceeded expectations.',
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-1.5-mini",
  "input": {
    "output_format": "mp3",
    "speaking_rate": 1.4,
    "temperature": 1,
    "text": "This is a fast-paced summary of the key findings from the quarterly report. Revenue is up fifteen percent and user growth exceeded expectations.",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-1.5-mini/fast-speech.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Low Latency** — Minimize latency by disabling text normalization</summary>



```ts
const response = await env.AI.run(
  'inworld/tts-1.5-mini',
  {
    apply_text_normalization: false,
    output_format: 'mp3',
    temperature: 1,
    text: 'Quick response needed. The server is ready.',
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-1.5-mini",
  "input": {
    "apply_text_normalization": false,
    "output_format": "mp3",
    "temperature": 1,
    "text": "Quick response needed. The server is ready.",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-1.5-mini/low-latency.mp3"
  },
  "state": "Completed"
}
```

</details>

## Parameters

text

`string`requiredmaxLength: 2000The text to be synthesized into speech. Maximum input of 2,000 characters.

voice\_id

`string`requireddefault: Dennisenum: Loretta, Darlene, Marlene, Hank, Evelyn, Celeste, Pippa, Tessa, Liam, Callum, Hamish, Abby, Graham, Rupert, Mortimer, Snik, Anjali, Saanvi, Arjun, Claire, Oliver, Simon, Elliot, James, Serena, Gareth, Vinny, Lauren, Jessica, Ethan, Tyler, Jason, Chloe, Veronica, Victoria, Miranda, Sebastian, Victor, Malcolm, Nate, Brian, Amina, Kelsey, Derek, Evan, Kayla, Jake, Grant, Tristan, Nadia, Selene, Marcus, Riley, Damon, Cedric, Mia, Naomi, Jonah, Levi, Avery, Brandon, Conrad, Bianca, Lucian, Trevor, Alex, Ashley, Craig, Deborah, Dennis, Edward, Elizabeth, Hades, Julia, Pixie, Mark, Olivia, Priya, Ronald, Sarah, Shaun, Theodore, Timothy, Wendy, Dominus, Hana, Clive, Carter, Blake, Luna, Reed, Duncan, Felix, Eleanor, SophieThe ID of the voice to use for synthesizing speech. Defaults to Dennis.

output\_format

`string`requireddefault: mp3enum: mp3, opus, wav, flacThe output format for the audio. Supported formats are mp3, opus, wav, and flac. Defaults to mp3.

bit\_rate

`integer`minimum: -9007199254740991maximum: 9007199254740991Bits per second of the audio. Only for compressed audio formats (mp3, opus). The default is 128,000.

sample\_rate

`integer`minimum: -9007199254740991maximum: 9007199254740991The synthesis sample rate in hertz. Accepts: 8000, 16000, 22050, 24000, 32000, 44100, 48000. The default is 48,000.

speaking\_rate

`number`minimum: 0.5maximum: 1.5Speaking rate/speed, in the range \[0.5, 1.5]. The default is 1.0. We recommend using values above 0.8 to ensure high quality.

temperature

`number`requireddefault: 1minimum: 0.01maximum: 2Determines the degree of randomness when sampling audio tokens. Defaults to 1.0. Accepts values between 0 (exclusive) and 2 (inclusive). Higher values = more expressive, lower values = more deterministic.

timestamp\_type

`string`requireddefault: noneenum: none, word, characterControls timestamp metadata returned with the audio. "word" returns word-level timing, "character" returns character-level timing. Note: adds latency. Defaults to none.

apply\_text\_normalization

`boolean`When enabled, text normalization expands numbers, dates, times, and abbreviations before converting to speech. Turning this off may reduce latency.

audio

`string`URL to the generated audio file

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-mini/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-mini/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-mini/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/inworld/tts-1.5-mini/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/inworld/tts-1.5-mini/#page","headline":"Inworld TTS 1.5 Mini","description":"Ultra-fast, cost-efficient text-to-speech with approximately 120ms latency and 15-language support.","url":"https://developers.cloudflare.com/ai/models/inworld/tts-1.5-mini/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Inworld's most powerful and expressive text-to-speech model. Builds on TTS 1.5 with rich expressive speech, real-time latency, natural language steering (e.g. [whisper], [say excitedly]), and stronger multilingual support across 15 production languages plus 90+ experimental languages.
title: Inworld TTS 2
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Inworld logo](https://developers.cloudflare.com/_astro/inworld.BDwMAXI2.svg)

# Inworld TTS 2

Text-to-Speech • Inworld

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/inworld/tts-2/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`inworld/tts-2`

- Third-party
- Zero data retention

Inworld's most powerful and expressive text-to-speech model. Builds on TTS 1.5 with rich expressive speech, real-time latency, natural language steering (e.g. \[whisper], \[say excitedly]), and stronger multilingual support across 15 production languages plus 90+ experimental languages.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://inworld.ai/terms) |
| More information | [link ↗](https://docs.inworld.ai/tts/realtime-tts-2-preview) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per character$0.000025</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'inworld/tts-2',
  {
    output_format: 'mp3',
    temperature: 1,
    text: 'Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.',
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-2",
  "input": {
    "output_format": "mp3",
    "temperature": 1,
    "text": "Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-2/simple-speech.mp3"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Natural Language Steering** — Direct the voice with bracketed natural-language cues for emotion, pace, and style.</summary>



```ts
const response = await env.AI.run(
  'inworld/tts-2',
  {
    output_format: 'mp3',
    temperature: 1,
    text: "[speak with excitement] I'm really excited about Inworld's new model. Have you tried out the steering capabilities? It's pretty cool!",
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-2",
  "input": {
    "output_format": "mp3",
    "temperature": 1,
    "text": "[speak with excitement] I'\''m really excited about Inworld'\''s new model. Have you tried out the steering capabilities? It'\''s pretty cool!",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-2/natural-language-steering.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Whisper** — Use steering tags to whisper</summary>



```ts
const response = await env.AI.run(
  'inworld/tts-2',
  {
    output_format: 'mp3',
    temperature: 1,
    text: '[whisper] This is a secret just between us.',
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-2",
  "input": {
    "output_format": "mp3",
    "temperature": 1,
    "text": "[whisper] This is a secret just between us.",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-2/whisper.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**High Quality Audio** — Higher sample rate for studio quality</summary>



```ts
const response = await env.AI.run(
  'inworld/tts-2',
  {
    output_format: 'mp3',
    sample_rate: 48000,
    temperature: 1,
    text: 'This recording is generated at studio quality for the best possible listening experience.',
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-2",
  "input": {
    "output_format": "mp3",
    "sample_rate": 48000,
    "temperature": 1,
    "text": "This recording is generated at studio quality for the best possible listening experience.",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-2/high-quality-audio.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**With Text Normalization** — Expand numbers and abbreviations before synthesis</summary>



```ts
const response = await env.AI.run(
  'inworld/tts-2',
  {
    apply_text_normalization: true,
    output_format: 'mp3',
    temperature: 1,
    text: 'The meeting is at 3:30 PM on Jan 15th, 2026. Please confirm by calling 555-0123.',
    timestamp_type: 'none',
    voice_id: 'Dennis',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "inworld/tts-2",
  "input": {
    "apply_text_normalization": true,
    "output_format": "mp3",
    "temperature": 1,
    "text": "The meeting is at 3:30 PM on Jan 15th, 2026. Please confirm by calling 555-0123.",
    "timestamp_type": "none",
    "voice_id": "Dennis"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/inworld__tts-2/with-text-normalization.mp3"
  },
  "state": "Completed"
}
```

</details>

## Parameters

text

`string`requiredmaxLength: 2000The text to be synthesized into speech. Maximum input of 2,000 characters.

voice\_id

`string`requireddefault: Dennisenum: Loretta, Darlene, Marlene, Hank, Evelyn, Celeste, Pippa, Tessa, Liam, Callum, Hamish, Abby, Graham, Rupert, Mortimer, Snik, Anjali, Saanvi, Arjun, Claire, Oliver, Simon, Elliot, James, Serena, Gareth, Vinny, Lauren, Jessica, Ethan, Tyler, Jason, Chloe, Veronica, Victoria, Miranda, Sebastian, Victor, Malcolm, Nate, Brian, Amina, Kelsey, Derek, Evan, Kayla, Jake, Grant, Tristan, Nadia, Selene, Marcus, Riley, Damon, Cedric, Mia, Naomi, Jonah, Levi, Avery, Brandon, Conrad, Bianca, Lucian, Trevor, Alex, Ashley, Craig, Deborah, Dennis, Edward, Elizabeth, Hades, Julia, Pixie, Mark, Olivia, Priya, Ronald, Sarah, Shaun, Theodore, Timothy, Wendy, Dominus, Hana, Clive, Carter, Blake, Luna, Reed, Duncan, Felix, Eleanor, SophieThe ID of the voice to use for synthesizing speech. Defaults to Dennis.

output\_format

`string`requireddefault: mp3enum: mp3, opus, wav, flacThe output format for the audio. Supported formats are mp3, opus, wav, and flac. Defaults to mp3.

bit\_rate

`integer`minimum: -9007199254740991maximum: 9007199254740991Bits per second of the audio. Only for compressed audio formats (mp3, opus). The default is 128,000.

sample\_rate

`integer`minimum: -9007199254740991maximum: 9007199254740991The synthesis sample rate in hertz. Accepts: 8000, 16000, 22050, 24000, 32000, 44100, 48000. The default is 48,000.

speaking\_rate

`number`minimum: 0.5maximum: 1.5Speaking rate/speed, in the range \[0.5, 1.5]. The default is 1.0. We recommend using values above 0.8 to ensure high quality.

temperature

`number`requireddefault: 1minimum: 0.01maximum: 2Determines the degree of randomness when sampling audio tokens. Defaults to 1.0. Accepts values between 0 (exclusive) and 2 (inclusive). Higher values = more expressive, lower values = more deterministic.

timestamp\_type

`string`requireddefault: noneenum: none, word, characterControls timestamp metadata returned with the audio. "word" returns word-level timing, "character" returns character-level timing. Note: adds latency. Defaults to none.

apply\_text\_normalization

`boolean`When enabled, text normalization expands numbers, dates, times, and abbreviations before converting to speech. Turning this off may reduce latency.

audio

`string`URL to the generated audio file

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/inworld/tts-2/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/inworld/tts-2/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/inworld/tts-2/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/inworld/tts-2/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/inworld/tts-2/#page","headline":"Inworld TTS 2","description":"Inworld's most powerful and expressive text-to-speech model. Builds on TTS 1.5 with rich expressive speech, real-time latency, natural language steering (e.g. [whisper], [say excitedly]), and stronger multilingual support across 15 production languages plus 90+ experimental languages.","url":"https://developers.cloudflare.com/ai/models/inworld/tts-2/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: More than 2x the size of Medium, with softer post-training. Outputs are rawer, more textured, and more flexible — at its best, Large produces results Medium can't match. Strongest on photorealism, raw looks (motion blur, grain, low dynamic range), and expressive and artistic styles.
title: Krea 2 Large
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

k

# Krea 2 Large

Text-to-Image • krea

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/krea/krea-2-large/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`krea/krea-2-large`

- Third-party

More than 2x the size of Medium, with softer post-training. Outputs are rawer, more textured, and more flexible — at its best, Large produces results Medium can't match. Strongest on photorealism, raw looks (motion blur, grain, low dynamic range), and expressive and artistic styles.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.krea.ai/terms) |
| More information | [link ↗](https://docs.krea.ai/api-reference/krea/krea-2-large) |
| Pricing | <ul><li>Default (per second)$0.06</li><li>Per image$0.06</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'krea/krea-2-large',
  {
    prompt: 'a cinematic glass cabin beside a frozen lake at sunrise',
    aspect_ratio: '16:9',
    resolution: '1K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "krea/krea-2-large",
  "input": {
    "prompt": "a cinematic glass cabin beside a frozen lake at sunrise",
    "aspect_ratio": "16:9",
    "resolution": "1K"
  }
}'
```

![Default](https://examples.aig.cloudflare.com/krea/krea-2-large/default.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/krea/krea-2-large/default.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

prompt

`string`requiredText prompt describing the image to generate.

aspect\_ratio

`string`requiredenum: 1:1, 4:3, 3:2, 16:9, 2.35:1, 4:5, 2:3, 9:16Aspect ratio of the generated image.

resolution

`string`requiredenum: 1KResolution scale.

seed

`number`Random seed for reproducible generations. Pass null or omit for a random seed.

▶styles\[]

`array`Styles (typically LoRAs) to apply to the generation.

▶image\_style\_references\[]

`array`maxItems: 10Reference images to drive the visual style (up to 10).

creativity

`string`default: lowenum: raw, low, medium, highPrompt expansion mode. \`raw\` disables expansion; \`low\`, \`medium\`, \`high\` control strength. Does not affect the K2 Intensity, Complexity, or Movement slider LoRAs.

intensity

`integer`default: 0minimum: -100maximum: 100K2 Intensity slider (-100 to 100). 0 disables the slider LoRA.

complexity

`integer`default: 0minimum: -100maximum: 100K2 Complexity slider (-100 to 100). 0 disables the slider LoRA.

movement

`integer`default: 0minimum: -100maximum: 100K2 Movement slider (-100 to 100). 0 disables the slider LoRA.

▶moodboards\[]

`array`maxItems: 1Moodboard references (currently limited to one).

image

`string`format: uriPresigned URL for the generated image.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/krea/krea-2-large/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/krea/krea-2-large/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/krea/krea-2-large/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/krea/krea-2-large/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/krea/krea-2-large/#page","headline":"Krea 2 Large","description":"More than 2x the size of Medium, with softer post-training. Outputs are rawer, more textured, and more flexible — at its best, Large produces results Medium can't match. Strongest on photorealism, raw looks (motion blur, grain, low dynamic range), and expressive and artistic styles.","url":"https://developers.cloudflare.com/ai/models/krea/krea-2-large/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Smaller, faster, more cost-efficient. Extensive post-training makes outputs especially stable and consistent across generations. Strongest on illustration, anime, painting, and other expressive or artistic styles.
title: Krea 2 Medium
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

k

# Krea 2 Medium

Text-to-Image • krea

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/krea/krea-2-medium/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`krea/krea-2-medium`

- Third-party

Smaller, faster, more cost-efficient. Extensive post-training makes outputs especially stable and consistent across generations. Strongest on illustration, anime, painting, and other expressive or artistic styles.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.krea.ai/terms) |
| More information | [link ↗](https://docs.krea.ai/api-reference/krea/krea-2-medium) |
| Pricing | <ul><li>Default (per second)$0.03</li><li>Per image$0.03</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'krea/krea-2-medium',
  {
    prompt: "An igloo village glowing with Aurora's colors.",
    aspect_ratio: '1:1',
    resolution: '1K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "krea/krea-2-medium",
  "input": {
    "prompt": "An igloo village glowing with Aurora'\''s colors.",
    "aspect_ratio": "1:1",
    "resolution": "1K"
  }
}'
```

![Default](https://examples.aig.cloudflare.com/krea/krea-2-medium/default.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/krea/krea-2-medium/default.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

prompt

`string`requiredText prompt describing the image to generate.

aspect\_ratio

`string`requiredenum: 1:1, 4:3, 3:2, 16:9, 2.35:1, 4:5, 2:3, 9:16Aspect ratio of the generated image.

resolution

`string`requiredenum: 1KResolution scale.

seed

`number`Random seed for reproducible generations. Pass null or omit for a random seed.

▶styles\[]

`array`Styles (typically LoRAs) to apply to the generation.

▶image\_style\_references\[]

`array`maxItems: 10Reference images to drive the visual style (up to 10).

creativity

`string`default: lowenum: raw, low, medium, highPrompt expansion mode. \`raw\` disables expansion; \`low\`, \`medium\`, \`high\` control strength. Does not affect the K2 Intensity, Complexity, or Movement slider LoRAs.

intensity

`integer`default: 0minimum: -100maximum: 100K2 Intensity slider (-100 to 100). 0 disables the slider LoRA.

complexity

`integer`default: 0minimum: -100maximum: 100K2 Complexity slider (-100 to 100). 0 disables the slider LoRA.

movement

`integer`default: 0minimum: -100maximum: 100K2 Movement slider (-100 to 100). 0 disables the slider LoRA.

▶moodboards\[]

`array`maxItems: 1Moodboard references (currently limited to one).

image

`string`format: uriPresigned URL for the generated image.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/krea/krea-2-medium/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/krea/krea-2-medium/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/krea/krea-2-medium/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/krea/krea-2-medium/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/krea/krea-2-medium/#page","headline":"Krea 2 Medium","description":"Smaller, faster, more cost-efficient. Extensive post-training makes outputs especially stable and consistent across generations. Strongest on illustration, anime, painting, and other expressive or artistic styles.","url":"https://developers.cloudflare.com/ai/models/krea/krea-2-medium/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: The fastest Krea 2 model, built for low-cost iteration on expressive illustrations, style-driven concepts, and rapid visual exploration. Keeps the Krea 2 style system and expressive visual range but uses a distilled sampling schedule so you can move through ideas much faster. Especially useful for expressive illustration, graphic styles, typography experiments, and quick campaign or concept directions.
title: Krea 2 Medium Turbo
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

k

# Krea 2 Medium Turbo

Text-to-Image • krea

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/krea/krea-2-medium-turbo/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`krea/krea-2-medium-turbo`

- Third-party

The fastest Krea 2 model, built for low-cost iteration on expressive illustrations, style-driven concepts, and rapid visual exploration. Keeps the Krea 2 style system and expressive visual range but uses a distilled sampling schedule so you can move through ideas much faster. Especially useful for expressive illustration, graphic styles, typography experiments, and quick campaign or concept directions.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.krea.ai/terms) |
| More information | [link ↗](https://docs.krea.ai/api-reference/krea/krea-2-medium-turbo) |
| Pricing | <ul><li>Default (per second)$0.015</li><li>Per image$0.015</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'krea/krea-2-medium-turbo',
  {
    prompt: 'Ice citadel, frost mages and snow beasts, in a cool, fantasy anime style.',
    aspect_ratio: '1:1',
    resolution: '1K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "krea/krea-2-medium-turbo",
  "input": {
    "prompt": "Ice citadel, frost mages and snow beasts, in a cool, fantasy anime style.",
    "aspect_ratio": "1:1",
    "resolution": "1K"
  }
}'
```

![Default](https://examples.aig.cloudflare.com/krea/krea-2-medium-turbo/default.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/krea/krea-2-medium-turbo/default.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

prompt

`string`requiredText prompt describing the image to generate.

aspect\_ratio

`string`requiredenum: 1:1, 4:3, 3:2, 16:9, 2.35:1, 4:5, 2:3, 9:16Aspect ratio of the generated image.

resolution

`string`requiredenum: 1KResolution scale.

seed

`number`Random seed for reproducible generations. Pass null or omit for a random seed.

▶styles\[]

`array`Styles (typically LoRAs) to apply to the generation.

▶image\_style\_references\[]

`array`maxItems: 10Reference images to drive the visual style (up to 10).

creativity

`string`default: lowenum: raw, low, medium, highPrompt expansion mode. \`raw\` disables expansion; \`low\`, \`medium\`, \`high\` control strength. Does not affect the K2 Intensity, Complexity, or Movement slider LoRAs.

intensity

`integer`default: 0minimum: -100maximum: 100K2 Intensity slider (-100 to 100). 0 disables the slider LoRA.

complexity

`integer`default: 0minimum: -100maximum: 100K2 Complexity slider (-100 to 100). 0 disables the slider LoRA.

movement

`integer`default: 0minimum: -100maximum: 100K2 Movement slider (-100 to 100). 0 disables the slider LoRA.

▶moodboards\[]

`array`maxItems: 1Moodboard references (currently limited to one).

image

`string`format: uriPresigned URL for the generated image.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/krea/krea-2-medium-turbo/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/krea/krea-2-medium-turbo/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/krea/krea-2-medium-turbo/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/krea/krea-2-medium-turbo/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/krea/krea-2-medium-turbo/#page","headline":"Krea 2 Medium Turbo","description":"The fastest Krea 2 model, built for low-cost iteration on expressive illustrations, style-driven concepts, and rapid visual exploration. Keeps the Krea 2 style system and expressive visual range but uses a distilled sampling schedule so you can move through ideas much faster. Especially useful for expressive illustration, graphic styles, typography experiments, and quick campaign or concept directions.","url":"https://developers.cloudflare.com/ai/models/krea/krea-2-medium-turbo/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Lightricks LTX-2.5 Fast is a fast video generation model for text-to-video and image-to-video workflows, with synchronized audio, configurable duration, resolution, and frame rate.
title: LTX-2.5 Fast
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

l

# LTX-2.5 Fast

Text-to-Video • lightricks

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/lightricks/ltx-2-5-fast/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`lightricks/ltx-2-5-fast`

- Third-party

Lightricks LTX-2.5 Fast is a fast video generation model for text-to-video and image-to-video workflows, with synchronized audio, configurable duration, resolution, and frame rate.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://docs.ltx.io/api-documentation/api-reference/video-generation/text-to-video) |
| Pricing | <ul><li>Default (per second)$0.09</li><li>@720p (per second)$0.09</li><li>@1080p (per second)$0.15</li><li>@2k (per second)$0.19</li><li>@4k (per second)$0.37</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'lightricks/ltx-2-5-fast',
  {
    prompt: 'A cinematic aerial shot of ocean waves at sunset',
    duration: 8,
    resolution: '1920x1080',
    fps: 24,
    generate_audio: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "lightricks/ltx-2-5-fast",
  "input": {
    "prompt": "A cinematic aerial shot of ocean waves at sunset",
    "duration": 8,
    "resolution": "1920x1080",
    "fps": 24,
    "generate_audio": true
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/lightricks/ltx-2-5-fast/text-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Image-to-Video** — Animate a reference image with a final frame</summary>



```ts
const response = await env.AI.run(
  'lightricks/ltx-2-5-fast',
  {
    prompt: 'The camera moves forward while the trees sway in the wind',
    image_uri:
      'https://upload.wikimedia.org/wikipedia/commons/8/85/Tour_Eiffel_Wikimedia_Commons_%28cropped%29.jpg',
    last_frame_uri:
      'https://upload.wikimedia.org/wikipedia/commons/8/85/Tour_Eiffel_Wikimedia_Commons_%28cropped%29.jpg',
    duration: 8,
    resolution: '1920x1080',
    fps: 24,
    generate_audio: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "lightricks/ltx-2-5-fast",
  "input": {
    "prompt": "The camera moves forward while the trees sway in the wind",
    "image_uri": "https://upload.wikimedia.org/wikipedia/commons/8/85/Tour_Eiffel_Wikimedia_Commons_%28cropped%29.jpg",
    "last_frame_uri": "https://upload.wikimedia.org/wikipedia/commons/8/85/Tour_Eiffel_Wikimedia_Commons_%28cropped%29.jpg",
    "duration": 8,
    "resolution": "1920x1080",
    "fps": 24,
    "generate_audio": true
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/lightricks/ltx-2-5-fast/image-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredminLength: 1maxLength: 10000Text prompt describing the video

image\_uri

`string`format: uriHTTPS URI for the first frame

last\_frame\_uri

`string`format: uriHTTPS URI for the last frame

▶duration

`one of`required

resolution

`string`requireddefault: 1920x1080enum: 1280x720, 720x1280, 1920x1080, 1080x1920, 2560x1440, 1440x2560, 3840x2160, 2160x3840

▶fps

`one of`required

generate\_audio

`boolean`requireddefault: true

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/lightricks/ltx-2-5-fast/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/lightricks/ltx-2-5-fast/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/lightricks/ltx-2-5-fast/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/lightricks/ltx-2-5-fast/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/lightricks/ltx-2-5-fast/#page","headline":"LTX-2.5 Fast","description":"Lightricks LTX-2.5 Fast is a fast video generation model for text-to-video and image-to-video workflows, with synchronized audio, configurable duration, resolution, and frame rate.","url":"https://developers.cloudflare.com/ai/models/lightricks/ltx-2-5-fast/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: A multimodal video generation model supporting text-to-video, first and last frame image-to-video, and reference-to-video generation with 768P and 2K output.
title: MiniMax H3
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)

# MiniMax H3

Text-to-Video • MiniMax

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/minimax/h3/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`minimax/h3`

- Third-party

A multimodal video generation model supporting text-to-video, first and last frame image-to-video, and reference-to-video generation with 768P and 2K output.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://platform.minimax.io/docs/guides/terms-of-service.md) |
| More information | [link ↗](https://platform.minimax.io/docs/guides/video-generation.md) |
| Pricing | <ul><li>Default (per second)$0.08</li><li>@768p (per second)$0.08</li><li>@2k (per second)$0.13</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'minimax/h3',
  {
    content: [
      {
        type: 'text',
        text: 'A cinematic space-opera teaser: a fleet jumps into hyperspace above a purple nebula while a lone captain watches from a glass observation deck.',
      },
    ],
    duration: 5,
    ratio: '16:9',
    resolution: '2K',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/h3",
  "input": {
    "content": [
      {
        "type": "text",
        "text": "A cinematic space-opera teaser: a fleet jumps into hyperspace above a purple nebula while a lone captain watches from a glass observation deck."
      }
    ],
    "duration": 5,
    "ratio": "16:9",
    "resolution": "2K"
  }
}'
```

```json
{
  "task": {
    "id": "441812275253329",
    "model": "MiniMax-H3",
    "status": "succeeded",
    "created_at": 1789417263,
    "updated_at": 1789417606,
    "content": {
      "url": "https://examples.aig.cloudflare.com/minimax/h3/text-to-video-2k.mp4"
    },
    "resolution": "2K",
    "duration": 5,
    "usage": {
      "total_seconds": 5,
      "input_seconds": 0,
      "output_seconds": 5,
      "input_image_count": 0,
      "total_tokens": 260390,
      "prompt_tokens": 0,
      "completion_tokens": 260390
    },
    "ratio": "16:9",
    "task_type": "generation"
  }
}
```

## Examples

<details>

<summary>**First Frame Image to Video** — Animate a supplied image as the first frame.</summary>



```ts
const response = await env.AI.run(
  'minimax/h3',
  {
    content: [
      {
        type: 'text',
        text: 'Slowly push in while the leaves move gently in the breeze and warm sunlight flickers through the branches.',
      },
      {
        type: 'image_url',
        image_url: {
          url: 'https://filecdn.minimax.chat/public/85c96368-6ead-4eae-af9c-116be878eac3.png',
        },
        role: 'first_frame',
      },
    ],
    duration: 5,
    resolution: '768P',
    ratio: 'adaptive',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/h3",
  "input": {
    "content": [
      {
        "type": "text",
        "text": "Slowly push in while the leaves move gently in the breeze and warm sunlight flickers through the branches."
      },
      {
        "type": "image_url",
        "image_url": {
          "url": "https://filecdn.minimax.chat/public/85c96368-6ead-4eae-af9c-116be878eac3.png"
        },
        "role": "first_frame"
      }
    ],
    "duration": 5,
    "resolution": "768P",
    "ratio": "adaptive"
  }
}'
```

```json
{
  "task": {
    "id": "441814879252673",
    "model": "MiniMax-H3",
    "status": "succeeded",
    "created_at": 1789417772,
    "updated_at": 1789417915,
    "content": {
      "url": "https://examples.aig.cloudflare.com/minimax/h3/first-frame-image-to-video.mp4"
    },
    "resolution": "768P",
    "duration": 5,
    "usage": {
      "total_seconds": 5,
      "input_seconds": 0,
      "output_seconds": 5,
      "input_image_count": 1,
      "total_tokens": 175765,
      "prompt_tokens": 13020,
      "completion_tokens": 162745
    },
    "ratio": "adaptive",
    "task_type": "generation"
  }
}
```

</details>

<details>

<summary>**Last Frame Image to Video** — Generate a transition that ends on a supplied image.</summary>



```ts
const response = await env.AI.run(
  'minimax/h3',
  {
    content: [
      {
        type: 'text',
        text: 'A paper airplane flies through a city at sunset and gently lands on the desk shown in the final frame.',
      },
      {
        type: 'image_url',
        image_url: {
          url: 'https://filecdn.minimax.chat/public/97b7cd08-764e-4b8b-a7bf-87a0bd898575.jpeg',
        },
        role: 'last_frame',
      },
    ],
    duration: 6,
    resolution: '768P',
    ratio: 'adaptive',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/h3",
  "input": {
    "content": [
      {
        "type": "text",
        "text": "A paper airplane flies through a city at sunset and gently lands on the desk shown in the final frame."
      },
      {
        "type": "image_url",
        "image_url": {
          "url": "https://filecdn.minimax.chat/public/97b7cd08-764e-4b8b-a7bf-87a0bd898575.jpeg"
        },
        "role": "last_frame"
      }
    ],
    "duration": 6,
    "resolution": "768P",
    "ratio": "adaptive"
  }
}'
```

```json
{
  "task": {
    "id": "441808217669932",
    "model": "MiniMax-H3",
    "status": "succeeded",
    "created_at": 1789416497,
    "updated_at": 1789416694,
    "content": {
      "url": "https://examples.aig.cloudflare.com/minimax/h3/last-frame-image-to-video.mp4"
    },
    "resolution": "768P",
    "duration": 6,
    "usage": {
      "total_seconds": 6,
      "input_seconds": 0,
      "output_seconds": 6,
      "input_image_count": 1,
      "total_tokens": 208314,
      "prompt_tokens": 13020,
      "completion_tokens": 195294
    },
    "ratio": "adaptive",
    "task_type": "generation"
  }
}
```

</details>

<details>

<summary>**First and Last Frame** — Create a controlled transition between supplied first and last frames.</summary>



```ts
const response = await env.AI.run(
  'minimax/h3',
  {
    content: [
      {
        type: 'text',
        text: 'Show the character growing from childhood into adulthood through a continuous, emotional camera move.',
      },
      {
        type: 'image_url',
        image_url: {
          url: 'https://filecdn.minimax.chat/public/fe9d04da-f60e-444d-a2e0-18ae743add33.jpeg',
        },
        role: 'first_frame',
      },
      {
        type: 'image_url',
        image_url: {
          url: 'https://filecdn.minimax.chat/public/97b7cd08-764e-4b8b-a7bf-87a0bd898575.jpeg',
        },
        role: 'last_frame',
      },
    ],
    duration: 5,
    resolution: '2K',
    ratio: 'adaptive',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/h3",
  "input": {
    "content": [
      {
        "type": "text",
        "text": "Show the character growing from childhood into adulthood through a continuous, emotional camera move."
      },
      {
        "type": "image_url",
        "image_url": {
          "url": "https://filecdn.minimax.chat/public/fe9d04da-f60e-444d-a2e0-18ae743add33.jpeg"
        },
        "role": "first_frame"
      },
      {
        "type": "image_url",
        "image_url": {
          "url": "https://filecdn.minimax.chat/public/97b7cd08-764e-4b8b-a7bf-87a0bd898575.jpeg"
        },
        "role": "last_frame"
      }
    ],
    "duration": 5,
    "resolution": "2K",
    "ratio": "adaptive"
  }
}'
```

```json
{
  "task": {
    "id": "441811301478471",
    "model": "MiniMax-H3",
    "status": "succeeded",
    "created_at": 1789416926,
    "updated_at": 1789417242,
    "content": {
      "url": "https://examples.aig.cloudflare.com/minimax/h3/first-and-last-frame.mp4"
    },
    "resolution": "2K",
    "duration": 5,
    "usage": {
      "total_seconds": 5,
      "input_seconds": 0,
      "output_seconds": 5,
      "input_image_count": 2,
      "total_tokens": 286430,
      "prompt_tokens": 26040,
      "completion_tokens": 260390
    },
    "ratio": "adaptive",
    "task_type": "generation"
  }
}
```

</details>

<details>

<summary>**Multiple Reference Images** — Use multiple reference images to preserve character appearance and style.</summary>



```ts
const response = await env.AI.run(
  'minimax/h3',
  {
    content: [
      {
        type: 'text',
        text: "The character walks through a rainy city street, preserving the character's appearance from the first reference and the visual style from the second.",
      },
      {
        type: 'image_url',
        image_url: {
          url: 'https://cdn.hailuoai.com/prod/hailuo_demo/testsets/h3_promo_eval_ref2va/gallery/sr_v2p26_trio_seed42_20260724/inputs/9d5c7a33fa6e_01_%E5%9B%BE1_MHGgbVga3o_gpt4o-image-1780651118146.png',
        },
        role: 'reference_image',
      },
      {
        type: 'image_url',
        image_url: {
          url: 'https://cdn.hailuoai.com/prod/hailuo_demo/testsets/h3_promo_eval_ref2va/gallery/sr_v2p26_trio_seed42_20260724/inputs/7af326902315_00_%E5%9B%BE2_YqtKbY1jpo_u4391985813_Young_male_wearing_cream_hoodie_and_dark_brown_sh_45d56ed0-d626-4c37-9a5b-77f51f374982_1.png',
        },
        role: 'reference_image',
      },
    ],
    duration: 5,
    resolution: '2K',
    ratio: '16:9',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/h3",
  "input": {
    "content": [
      {
        "type": "text",
        "text": "The character walks through a rainy city street, preserving the character'\''s appearance from the first reference and the visual style from the second."
      },
      {
        "type": "image_url",
        "image_url": {
          "url": "https://cdn.hailuoai.com/prod/hailuo_demo/testsets/h3_promo_eval_ref2va/gallery/sr_v2p26_trio_seed42_20260724/inputs/9d5c7a33fa6e_01_%E5%9B%BE1_MHGgbVga3o_gpt4o-image-1780651118146.png"
        },
        "role": "reference_image"
      },
      {
        "type": "image_url",
        "image_url": {
          "url": "https://cdn.hailuoai.com/prod/hailuo_demo/testsets/h3_promo_eval_ref2va/gallery/sr_v2p26_trio_seed42_20260724/inputs/7af326902315_00_%E5%9B%BE2_YqtKbY1jpo_u4391985813_Young_male_wearing_cream_hoodie_and_dark_brown_sh_45d56ed0-d626-4c37-9a5b-77f51f374982_1.png"
        },
        "role": "reference_image"
      }
    ],
    "duration": 5,
    "resolution": "2K",
    "ratio": "16:9"
  }
}'
```

```json
{
  "task": {
    "id": "441814469210409",
    "model": "MiniMax-H3",
    "status": "succeeded",
    "created_at": 1789417917,
    "updated_at": 1789418171,
    "content": {
      "url": "https://examples.aig.cloudflare.com/minimax/h3/multiple-reference-images.mp4"
    },
    "resolution": "2K",
    "duration": 5,
    "usage": {
      "total_seconds": 5,
      "input_seconds": 0,
      "output_seconds": 5,
      "input_image_count": 2,
      "total_tokens": 286430,
      "prompt_tokens": 26040,
      "completion_tokens": 260390
    },
    "ratio": "16:9",
    "task_type": "generation"
  }
}
```

</details>

## Parameters

▶content\[]

`array`requiredminItems: 1

resolution

`string`requiredenum: 768P, 2K

duration

`integer`requiredminimum: 4maximum: 15

ratio

`string`enum: adaptive, 21:9, 16:9, 4:3, 1:1, 3:4, 9:16

callback\_url

`string`format: uri

▶task{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/minimax/h3/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/minimax/h3/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/minimax/h3/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/minimax/h3/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/minimax/h3/#page","headline":"MiniMax H3","description":"A multimodal video generation model supporting text-to-video, first and last frame image-to-video, and reference-to-video generation with 768P and 2K output.","url":"https://developers.cloudflare.com/ai/models/minimax/h3/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: A fast multimodal video generation model supporting text-to-video and image-to-video generation at 480P and 768P.
title: MiniMax H3 Max
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)

# MiniMax H3 Max

Text-to-Video • MiniMax

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/minimax/h3-max/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`minimax/h3-max`

- Third-party

A fast multimodal video generation model supporting text-to-video and image-to-video generation at 480P and 768P.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://platform.minimax.io/docs/guides/terms-of-service.md) |
| More information | [link ↗](https://platform.minimax.io/docs/guides/video-generation.md) |
| Pricing | <ul><li>Default (per second)$0.05</li><li>@480p (per second)$0.05</li><li>@768p (per second)$0.08</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'minimax/h3-max',
  {
    content: [
      {
        type: 'text',
        text: 'A golden retriever runs along a beach at sunrise while the camera tracks beside it in a cinematic slow motion shot.',
      },
    ],
    duration: 5,
    extra: { prompt_expansion_mode: 'balanced' },
    ratio: '16:9',
    resolution: '768P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/h3-max",
  "input": {
    "content": [
      {
        "type": "text",
        "text": "A golden retriever runs along a beach at sunrise while the camera tracks beside it in a cinematic slow motion shot."
      }
    ],
    "duration": 5,
    "extra": {
      "prompt_expansion_mode": "balanced"
    },
    "ratio": "16:9",
    "resolution": "768P"
  }
}'
```

```json
{
  "task": {
    "id": "441805798383681",
    "model": "MiniMax-H3-Max",
    "status": "succeeded",
    "created_at": 1789415547,
    "updated_at": 1789415554,
    "content": {
      "url": "https://examples.aig.cloudflare.com/minimax/h3-max/balanced-text-to-video.mp4"
    },
    "resolution": "768P",
    "duration": 5,
    "usage": {
      "total_seconds": 5,
      "input_seconds": 0,
      "output_seconds": 5,
      "input_image_count": 0
    },
    "ratio": "16:9",
    "task_type": "generation"
  }
}
```

## Examples

<details>

<summary>**Disabled Prompt Expansion** — Generate a fast 480P vertical social video with prompt expansion disabled.</summary>



```ts
const response = await env.AI.run(
  'minimax/h3-max',
  {
    content: [
      {
        type: 'text',
        text: 'A chef tosses vegetables in a wok in a bright street-food kitchen, energetic handheld camera.',
      },
    ],
    duration: 5,
    extra: { prompt_expansion_mode: 'disabled' },
    ratio: '9:16',
    resolution: '480P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/h3-max",
  "input": {
    "content": [
      {
        "type": "text",
        "text": "A chef tosses vegetables in a wok in a bright street-food kitchen, energetic handheld camera."
      }
    ],
    "duration": 5,
    "extra": {
      "prompt_expansion_mode": "disabled"
    },
    "ratio": "9:16",
    "resolution": "480P"
  }
}'
```

```json
{
  "task": {
    "id": "441804654764158",
    "model": "MiniMax-H3-Max",
    "status": "succeeded",
    "created_at": 1789415577,
    "updated_at": 1789415583,
    "content": {
      "url": "https://examples.aig.cloudflare.com/minimax/h3-max/disabled-prompt-expansion.mp4"
    },
    "resolution": "480P",
    "duration": 5,
    "usage": {
      "total_seconds": 5,
      "input_seconds": 0,
      "output_seconds": 5,
      "input_image_count": 0
    },
    "ratio": "9:16",
    "task_type": "generation"
  }
}
```

</details>

<details>

<summary>**Quality Prompt Expansion** — Prioritize prompt expansion quality for a detailed 768P scene.</summary>



```ts
const response = await env.AI.run(
  'minimax/h3-max',
  {
    content: [
      {
        type: 'text',
        text: 'A detailed miniature railway travels through a glowing underground crystal cavern, with tiny passengers looking out of the windows.',
      },
    ],
    duration: 8,
    extra: { prompt_expansion_mode: 'quality' },
    ratio: '21:9',
    resolution: '768P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/h3-max",
  "input": {
    "content": [
      {
        "type": "text",
        "text": "A detailed miniature railway travels through a glowing underground crystal cavern, with tiny passengers looking out of the windows."
      }
    ],
    "duration": 8,
    "extra": {
      "prompt_expansion_mode": "quality"
    },
    "ratio": "21:9",
    "resolution": "768P"
  }
}'
```

```json
{
  "task": {
    "id": "441805071421550",
    "model": "MiniMax-H3-Max",
    "status": "succeeded",
    "created_at": 1789415588,
    "updated_at": 1789415659,
    "content": {
      "url": "https://examples.aig.cloudflare.com/minimax/h3-max/quality-prompt-expansion.mp4"
    },
    "resolution": "768P",
    "duration": 8,
    "usage": {
      "total_seconds": 8,
      "input_seconds": 0,
      "output_seconds": 8,
      "input_image_count": 0
    },
    "ratio": "21:9",
    "task_type": "generation"
  }
}
```

</details>

<details>

<summary>**H3 Max Image to Video** — Animate a supplied first-frame image at 480P.</summary>



```ts
const response = await env.AI.run(
  'minimax/h3-max',
  {
    content: [
      {
        type: 'text',
        text: 'The camera slowly pans across the scene while fabric and hair move naturally in the wind.',
      },
      {
        type: 'image_url',
        image_url: {
          url: 'https://filecdn.minimax.chat/public/85c96368-6ead-4eae-af9c-116be878eac3.png',
        },
        role: 'first_frame',
      },
    ],
    duration: 5,
    extra: { prompt_expansion_mode: 'balanced' },
    ratio: 'adaptive',
    resolution: '480P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/h3-max",
  "input": {
    "content": [
      {
        "type": "text",
        "text": "The camera slowly pans across the scene while fabric and hair move naturally in the wind."
      },
      {
        "type": "image_url",
        "image_url": {
          "url": "https://filecdn.minimax.chat/public/85c96368-6ead-4eae-af9c-116be878eac3.png"
        },
        "role": "first_frame"
      }
    ],
    "duration": 5,
    "extra": {
      "prompt_expansion_mode": "balanced"
    },
    "ratio": "adaptive",
    "resolution": "480P"
  }
}'
```

```json
{
  "task": {
    "id": "441804606931065",
    "model": "MiniMax-H3-Max",
    "status": "succeeded",
    "created_at": 1789415661,
    "updated_at": 1789415668,
    "content": {
      "url": "https://examples.aig.cloudflare.com/minimax/h3-max/h3-max-image-to-video.mp4"
    },
    "resolution": "480P",
    "duration": 5,
    "usage": {
      "total_seconds": 5,
      "input_seconds": 0,
      "output_seconds": 5,
      "input_image_count": 1
    },
    "ratio": "adaptive",
    "task_type": "generation"
  }
}
```

</details>

<details>

<summary>**H3 Max Reference Images** — Use multiple reference images to guide a fast character generation.</summary>



```ts
const response = await env.AI.run(
  'minimax/h3-max',
  {
    content: [
      {
        type: 'text',
        text: 'Create a short cinematic portrait of the character walking through a modern gallery, preserving the face and clothing from the references.',
      },
      {
        type: 'image_url',
        image_url: {
          url: 'https://cdn.hailuoai.com/prod/hailuo_demo/testsets/h3_promo_eval_ref2va/gallery/sr_v2p26_trio_seed42_20260724/inputs/9d5c7a33fa6e_01_%E5%9B%BE1_MHGgbVga3o_gpt4o-image-1780651118146.png',
        },
        role: 'reference_image',
      },
      {
        type: 'image_url',
        image_url: {
          url: 'https://cdn.hailuoai.com/prod/hailuo_demo/testsets/h3_promo_eval_ref2va/gallery/sr_v2p26_trio_seed42_20260724/inputs/7af326902315_00_%E5%9B%BE2_YqtKbY1jpo_u4391985813_Young_male_wearing_cream_hoodie_and_dark_brown_sh_45d56ed0-d626-4c37-9a5b-77f51f374982_1.png',
        },
        role: 'reference_image',
      },
    ],
    duration: 5,
    extra: { prompt_expansion_mode: 'balanced' },
    resolution: '768P',
    ratio: '16:9',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/h3-max",
  "input": {
    "content": [
      {
        "type": "text",
        "text": "Create a short cinematic portrait of the character walking through a modern gallery, preserving the face and clothing from the references."
      },
      {
        "type": "image_url",
        "image_url": {
          "url": "https://cdn.hailuoai.com/prod/hailuo_demo/testsets/h3_promo_eval_ref2va/gallery/sr_v2p26_trio_seed42_20260724/inputs/9d5c7a33fa6e_01_%E5%9B%BE1_MHGgbVga3o_gpt4o-image-1780651118146.png"
        },
        "role": "reference_image"
      },
      {
        "type": "image_url",
        "image_url": {
          "url": "https://cdn.hailuoai.com/prod/hailuo_demo/testsets/h3_promo_eval_ref2va/gallery/sr_v2p26_trio_seed42_20260724/inputs/7af326902315_00_%E5%9B%BE2_YqtKbY1jpo_u4391985813_Young_male_wearing_cream_hoodie_and_dark_brown_sh_45d56ed0-d626-4c37-9a5b-77f51f374982_1.png"
        },
        "role": "reference_image"
      }
    ],
    "duration": 5,
    "extra": {
      "prompt_expansion_mode": "balanced"
    },
    "resolution": "768P",
    "ratio": "16:9"
  }
}'
```

```json
{
  "task": {
    "id": "441805100810489",
    "model": "MiniMax-H3-Max",
    "status": "succeeded",
    "created_at": 1789415671,
    "updated_at": 1789415685,
    "content": {
      "url": "https://examples.aig.cloudflare.com/minimax/h3-max/h3-max-reference-images.mp4"
    },
    "resolution": "768P",
    "duration": 5,
    "usage": {
      "total_seconds": 5,
      "input_seconds": 0,
      "output_seconds": 5,
      "input_image_count": 2
    },
    "ratio": "16:9",
    "task_type": "generation"
  }
}
```

</details>

## Parameters

▶content\[]

`array`requiredminItems: 1

duration

`integer`requiredminimum: 5maximum: 15

ratio

`string`enum: adaptive, 21:9, 16:9, 4:3, 1:1, 3:4, 9:16

callback\_url

`string`format: uri

resolution

`string`requiredenum: 480P, 768P

▶extra{}

`object`

▶task{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/minimax/h3-max/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/minimax/h3-max/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/minimax/h3-max/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/minimax/h3-max/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/minimax/h3-max/#page","headline":"MiniMax H3 Max","description":"A fast multimodal video generation model supporting text-to-video and image-to-video generation at 480P and 768P.","url":"https://developers.cloudflare.com/ai/models/minimax/h3-max/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: A high-fidelity video generation model optimized for realistic human motion, cinematic VFX, expressive characters, and strong prompt and style adherence across text-to-video and image-to-video workflows.
title: MiniMax Hailuo 2.3
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)

# MiniMax Hailuo 2.3

Text-to-Video • MiniMax

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`minimax/hailuo-2.3`

- Third-party
- Zero data retention

A high-fidelity video generation model optimized for realistic human motion, cinematic VFX, expressive characters, and strong prompt and style adherence across text-to-video and image-to-video workflows.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://hailuoai.com/terms) |
| More information | [link ↗](https://hailuoai.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.047</li><li>6s @768p$0.28</li><li>10s @768p$0.56</li><li>6s @1080p$0.49</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'minimax/hailuo-2.3',
  {
    prompt: 'A golden retriever playing fetch on a sandy beach at sunset',
    duration: 6,
    fast_pretreatment: false,
    prompt_optimizer: true,
    resolution: '768P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/hailuo-2.3",
  "input": {
    "prompt": "A golden retriever playing fetch on a sandy beach at sunset",
    "duration": 6,
    "fast_pretreatment": false,
    "prompt_optimizer": true,
    "resolution": "768P"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "status": "Success",
    "task_id": "388507504709991",
    "video": "https://video-product.cdn.minimax.io/inference_output/video/2026-04-17/97d0c2d0-45ab-4ce8-a1f4-177401f43073/output.mp4"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**High Resolution** — 1080P video for higher quality output</summary>



```ts
const response = await env.AI.run(
  'minimax/hailuo-2.3',
  {
    prompt:
      'A professional chef preparing sushi in a traditional Japanese kitchen, detailed close-up shots',
    duration: 6,
    fast_pretreatment: false,
    prompt_optimizer: true,
    resolution: '1080P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/hailuo-2.3",
  "input": {
    "prompt": "A professional chef preparing sushi in a traditional Japanese kitchen, detailed close-up shots",
    "duration": 6,
    "fast_pretreatment": false,
    "prompt_optimizer": true,
    "resolution": "1080P"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "status": "Success",
    "task_id": "388510158565457",
    "video": "https://video-product.cdn.minimax.io/inference_output/video/2026-04-17/1ee6a770-eb88-4b6a-86ea-61981f01ed65/output.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Image to Video** — Animate a still image with I2V</summary>



```ts
const response = await env.AI.run(
  'minimax/hailuo-2.3',
  {
    prompt: 'Slowly zoom in with subtle parallax movement, gentle atmospheric motion',
    duration: 6,
    fast_pretreatment: false,
    first_frame_image:
      'https://replicate.delivery/xezq/MQpUhqkESIIQDlWUxtNcsznZLfUTmhEbCV3vdAZGHGPwwaMLA/tmpgl4gvv5n.jpeg',
    prompt_optimizer: true,
    resolution: '768P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/hailuo-2.3",
  "input": {
    "prompt": "Slowly zoom in with subtle parallax movement, gentle atmospheric motion",
    "duration": 6,
    "fast_pretreatment": false,
    "first_frame_image": "https://replicate.delivery/xezq/MQpUhqkESIIQDlWUxtNcsznZLfUTmhEbCV3vdAZGHGPwwaMLA/tmpgl4gvv5n.jpeg",
    "prompt_optimizer": true,
    "resolution": "768P"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "status": "Success",
    "task_id": "388509844320343",
    "video": "https://video-product.cdn.minimax.io/inference_output/video/2026-04-17/a19c7850-6f3b-47dd-b6f1-decb592a11ff/output.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Fast Processing** — Enable fast pretreatment for quicker results</summary>



```ts
const response = await env.AI.run(
  'minimax/hailuo-2.3',
  {
    prompt: 'Fireworks exploding over a city skyline at night, colorful reflections on water',
    duration: 6,
    fast_pretreatment: true,
    prompt_optimizer: true,
    resolution: '768P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/hailuo-2.3",
  "input": {
    "prompt": "Fireworks exploding over a city skyline at night, colorful reflections on water",
    "duration": 6,
    "fast_pretreatment": true,
    "prompt_optimizer": true,
    "resolution": "768P"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "status": "Success",
    "task_id": "388509805367378",
    "video": "https://video-product.cdn.minimax.io/inference_output/video/2026-04-17/438b5433-5d32-4760-9564-c86da3d22aee/output.mp4"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`maxLength: 2000

first\_frame\_image

`string`

prompt\_optimizer

`boolean`requireddefault: true

fast\_pretreatment

`boolean`requireddefault: false

▶duration

`one of`required

resolution

`string`requireddefault: 768Penum: 768P, 1080P

video

`string`format: uri

task\_id

`string`

status

`string`enum: Preparing, Queueing, Processing, Success, Fail

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3/#page","headline":"MiniMax Hailuo 2.3","description":"A high-fidelity video generation model optimized for realistic human motion, cinematic VFX, expressive characters, and strong prompt and style adherence across text-to-video and image-to-video workflows.","url":"https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: A lower-latency version of Hailuo 2.3 that preserves core motion quality, visual consistency, and stylization while enabling faster iteration.
title: MiniMax Hailuo 2.3 Fast
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)

# MiniMax Hailuo 2.3 Fast

Text-to-Video • MiniMax

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3-fast/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`minimax/hailuo-2.3-fast`

- Third-party
- Zero data retention

A lower-latency version of Hailuo 2.3 that preserves core motion quality, visual consistency, and stylization while enabling faster iteration.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://hailuoai.com/terms) |
| More information | [link ↗](https://hailuoai.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.032</li><li>6s @768p$0.19</li><li>10s @768p$0.32</li><li>6s @1080p$0.33</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'minimax/hailuo-2.3-fast',
  {
    prompt: 'Gentle movement and subtle animation, natural-looking motion',
    duration: 6,
    fast_pretreatment: false,
    first_frame_image:
      'https://replicate.delivery/xezq/MQpUhqkESIIQDlWUxtNcsznZLfUTmhEbCV3vdAZGHGPwwaMLA/tmpgl4gvv5n.jpeg',
    prompt_optimizer: true,
    resolution: '768P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/hailuo-2.3-fast",
  "input": {
    "prompt": "Gentle movement and subtle animation, natural-looking motion",
    "duration": 6,
    "fast_pretreatment": false,
    "first_frame_image": "https://replicate.delivery/xezq/MQpUhqkESIIQDlWUxtNcsznZLfUTmhEbCV3vdAZGHGPwwaMLA/tmpgl4gvv5n.jpeg",
    "prompt_optimizer": true,
    "resolution": "768P"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "status": "Success",
    "task_id": "388514752192863",
    "video": "https://video-product.cdn.minimax.io/inference_output/video/2026-04-17/eff40703-0339-4d1d-b66a-db050e878038/output.mp4"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**High Resolution I2V** — Animate a photo in 1080P</summary>



```ts
const response = await env.AI.run(
  'minimax/hailuo-2.3-fast',
  {
    prompt: 'Camera slowly pans across the scene with cinematic depth of field',
    duration: 6,
    fast_pretreatment: false,
    first_frame_image:
      'https://replicate.delivery/xezq/IeNNble3XUqhpUZTd3CkYTUf8EgkFU1fl1Jnyive3B26MsGzC/tmp51dpln4i.jpeg',
    prompt_optimizer: true,
    resolution: '1080P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/hailuo-2.3-fast",
  "input": {
    "prompt": "Camera slowly pans across the scene with cinematic depth of field",
    "duration": 6,
    "fast_pretreatment": false,
    "first_frame_image": "https://replicate.delivery/xezq/IeNNble3XUqhpUZTd3CkYTUf8EgkFU1fl1Jnyive3B26MsGzC/tmp51dpln4i.jpeg",
    "prompt_optimizer": true,
    "resolution": "1080P"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "status": "Success",
    "task_id": "388515984507205",
    "video": "https://video-product.cdn.minimax.io/inference_output/video/2026-04-17/2b6251d2-d4ae-4d58-b12f-2609c50fadc2/output.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Fast Processing** — Quick I2V with fast pretreatment enabled</summary>



```ts
const response = await env.AI.run(
  'minimax/hailuo-2.3-fast',
  {
    prompt: 'Hair blowing in the wind, eyes blinking naturally',
    duration: 6,
    fast_pretreatment: true,
    first_frame_image:
      'https://replicate.delivery/xezq/jfh37lJpnDQhaKcAfCrxSCEh7HA7lv5cCWmJW284tYXwh1YWA/tmpw2i437qe.jpeg',
    prompt_optimizer: true,
    resolution: '768P',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/hailuo-2.3-fast",
  "input": {
    "prompt": "Hair blowing in the wind, eyes blinking naturally",
    "duration": 6,
    "fast_pretreatment": true,
    "first_frame_image": "https://replicate.delivery/xezq/jfh37lJpnDQhaKcAfCrxSCEh7HA7lv5cCWmJW284tYXwh1YWA/tmpw2i437qe.jpeg",
    "prompt_optimizer": true,
    "resolution": "768P"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "status": "Success",
    "task_id": "388515980755024",
    "video": "https://video-product.cdn.minimax.io/inference_output/video/2026-04-17/b64303a0-0227-4d42-983a-dcaec397b6b1/output.mp4"
  },
  "state": "Completed"
}
```

</details>

## Parameters

first\_frame\_image

`string`requiredURL or base64 data URI of the first frame image

prompt

`string`maxLength: 2000

prompt\_optimizer

`boolean`requireddefault: true

fast\_pretreatment

`boolean`requireddefault: false

▶duration

`one of`required

resolution

`string`requireddefault: 768Penum: 768P, 1080P

video

`string`format: uri

task\_id

`string`

status

`string`enum: Preparing, Queueing, Processing, Success, Fail

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3-fast/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3-fast/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3-fast/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3-fast/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3-fast/#page","headline":"MiniMax Hailuo 2.3 Fast","description":"A lower-latency version of Hailuo 2.3 that preserves core motion quality, visual consistency, and stylization while enabling faster iteration.","url":"https://developers.cloudflare.com/ai/models/minimax/hailuo-2.3-fast/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: MiniMax's M2.7 language model with multilingual capabilities.
title: MiniMax M2.7
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)

# MiniMax M2.7

Text Generation • MiniMax

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/minimax/m2.7/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`minimax/m2.7`

- Third-party
- Zero data retention

MiniMax's M2.7 language model with multilingual capabilities.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 128,000 tokens |
| Terms and License | [link ↗](https://www.minimaxi.com/terms) |
| More information | [link ↗](https://www.minimaxi.com/) |
| Zero data retention | Yes |
| Request formats | Chat Completions, Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$0.30</li><li>Output (per 1M tokens)$1.20</li><li>Cached input (per 1M tokens)$0.06</li><li>Cache creation (per 1M tokens)$0.375</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'minimax/m2.7',
  { max_tokens: 2048, messages: [{ content: 'What is the capital of France?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/m2.7",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "What is the capital of France?",
      "role": "user"
    }
  ]
}'
```

```
The capital of France is **Paris**.
```

```json
{
  "id": "066cf8dd69cbfedefa3ee5b16006f2bd",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The capital of France is **Paris**.",
        "name": "MiniMax AI",
        "audio_content": "",
        "reasoning_content": "The user asks: \"What is the capital of France?\" This is a straightforward factual question. The answer: Paris. The user likely wants the answer. No policy issues. There's no disallowed content. Just answer with \"Paris\". Should be simple. Possibly also elaborate slightly. But answer is \"Paris\". Provide answer concisely.",
        "reasoning_details": [
          {
            "type": "reasoning.text",
            "id": "reasoning-text-1",
            "format": "MiniMax-response-v1",
            "index": 0,
            "text": "The user asks: \"What is the capital of France?\" This is a straightforward factual question. The answer: Paris. The user likely wants the answer. No policy issues. There's no disallowed content. Just answer with \"Paris\". Should be simple. Possibly also elaborate slightly. But answer is \"Paris\". Provide answer concisely."
          }
        ]
      },
      "finish_reason": "stop"
    }
  ],
  "created": 1780336093,
  "model": "MiniMax-M2.7",
  "object": "chat.completion",
  "usage": {
    "total_tokens": 126,
    "prompt_tokens": 48,
    "completion_tokens": 78,
    "total_characters": 0,
    "completion_tokens_details": {
      "reasoning_tokens": 70
    }
  },
  "input_sensitive": false,
  "output_sensitive": false,
  "base_resp": {
    "status_code": 0,
    "status_msg": ""
  },
  "input_sensitive_type": 0,
  "output_sensitive_type": 0,
  "output_sensitive_int": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Prompt** — Using a system prompt to guide behavior</summary>



```ts
const response = await env.AI.run(
  'minimax/m2.7',
  {
    max_tokens: 2048,
    messages: [
      {
        content:
          'You are a helpful cooking assistant. Give concise recipes with metric measurements.',
        role: 'system',
      },
      { content: 'How do I make a simple pasta aglio e olio?', role: 'user' },
    ],
    temperature: 0.7,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/m2.7",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "You are a helpful cooking assistant. Give concise recipes with metric measurements.",
      "role": "system"
    },
    {
      "content": "How do I make a simple pasta aglio e olio?",
      "role": "user"
    }
  ],
  "temperature": 0.7
}'
```

```
# Pasta Aglio e Olio

**Serves 2 | Prep: 5 min | Cook: 15 min**

## Ingredients
- 200g spaghetti
- 60ml extra virgin olive oil
- 4 garlic cloves, thinly sliced
- 1/2 tsp dried chili flakes
- Fresh parsley, chopped
- Salt to taste

## Method

1. **Cook pasta** in well-salted boiling water until al dente. Reserve 120ml pasta water before draining.

2. **Heat olive oil** in a large pan over medium-low heat. Add garlic slices.

3. **Gently cook** garlic for 2-3 minutes until golden (not brown). Add chili flakes.

4. **Add pasta** to the pan with 60ml pasta water. Toss vigorously for 2 minutes, adding more water if needed.

5. **Finish** with parsley and serve immediately.

## Tips
- Low heat is key—garlic burns quickly
- Use good quality olive oil
- The starchy water creates the silky sauce
```

```json
{
  "id": "066cf8e09497cc6c53d2b14969cbe3d8",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "# Pasta Aglio e Olio\n\n**Serves 2 | Prep: 5 min | Cook: 15 min**\n\n## Ingredients\n- 200g spaghetti\n- 60ml extra virgin olive oil\n- 4 garlic cloves, thinly sliced\n- 1/2 tsp dried chili flakes\n- Fresh parsley, chopped\n- Salt to taste\n\n## Method\n\n1. **Cook pasta** in well-salted boiling water until al dente. Reserve 120ml pasta water before draining.\n\n2. **Heat olive oil** in a large pan over medium-low heat. Add garlic slices.\n\n3. **Gently cook** garlic for 2-3 minutes until golden (not brown). Add chili flakes.\n\n4. **Add pasta** to the pan with 60ml pasta water. Toss vigorously for 2 minutes, adding more water if needed.\n\n5. **Finish** with parsley and serve immediately.\n\n## Tips\n- Low heat is key—garlic burns quickly\n- Use good quality olive oil\n- The starchy water creates the silky sauce",
        "name": "MiniMax AI",
        "audio_content": "",
        "reasoning_content": "The user wants a simple pasta aglio e olio recipe. This is a classic Italian dish that's quick and uses few ingredients. I should provide concise instructions with metric measurements as requested.",
        "reasoning_details": [
          {
            "type": "reasoning.text",
            "id": "reasoning-text-1",
            "format": "MiniMax-response-v1",
            "index": 0,
            "text": "The user wants a simple pasta aglio e olio recipe. This is a classic Italian dish that's quick and uses few ingredients. I should provide concise instructions with metric measurements as requested."
          }
        ]
      },
      "finish_reason": "stop"
    }
  ],
  "created": 1780336096,
  "model": "MiniMax-M2.7",
  "object": "chat.completion",
  "usage": {
    "total_tokens": 297,
    "prompt_tokens": 41,
    "completion_tokens": 256,
    "total_characters": 0,
    "completion_tokens_details": {
      "reasoning_tokens": 41
    }
  },
  "input_sensitive": false,
  "output_sensitive": false,
  "base_resp": {
    "status_code": 0,
    "status_msg": ""
  },
  "input_sensitive_type": 0,
  "output_sensitive_type": 0,
  "output_sensitive_int": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'minimax/m2.7',
  {
    max_tokens: 2048,
    messages: [
      { content: 'What are the main differences between TCP and UDP?', role: 'user' },
      {
        content:
          'TCP is connection-oriented and guarantees delivery, while UDP is connectionless and faster but without delivery guarantees.',
        role: 'assistant',
      },
      { content: 'When would I choose UDP over TCP?', role: 'user' },
    ],
    temperature: 0.5,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/m2.7",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "What are the main differences between TCP and UDP?",
      "role": "user"
    },
    {
      "content": "TCP is connection-oriented and guarantees delivery, while UDP is connectionless and faster but without delivery guarantees.",
      "role": "assistant"
    },
    {
      "content": "When would I choose UDP over TCP?",
      "role": "user"
    }
  ],
  "temperature": 0.5
}'
```

```
UDP is preferred in situations where speed matters more than reliability. Here are common scenarios:

**Real-time applications**

- Video/audio streaming (Zoom, Skype, gaming)
- VoIP calls where slight packet loss is tolerable
- Live broadcasts

**Low-latency requirements**

- Online gaming
- Real-time financial trading
- Time-sensitive sensor data

**Simple query-response**

- DNS lookups (quick, fire-and-forget)
- DHCP
- NTP time synchronization

**Broadcast/Multicast**

- Service discovery (mDNS)
- IPTV streaming to multiple recipients

**Why not TCP in these cases?**

- TCP's retransmission and ordering can cause latency spikes
- Connection overhead adds delay
- Unnecessary for data that becomes stale quickly (old video frames)

**Trade-offs to consider**

- Application-level error handling may be needed
- You must handle packet loss, reordering, and duplicates yourself
- Some protocols layer reliability on top of UDP (QUIC, DNS over QUIC)

If you need guaranteed delivery and ordered data with no gaps, TCP remains the safer choice.
```

```json
{
  "id": "066cf8e412153a383389e1601d684033",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "UDP is preferred in situations where speed matters more than reliability. Here are common scenarios:\n\n**Real-time applications**\n\n- Video/audio streaming (Zoom, Skype, gaming)\n- VoIP calls where slight packet loss is tolerable\n- Live broadcasts\n\n**Low-latency requirements**\n\n- Online gaming\n- Real-time financial trading\n- Time-sensitive sensor data\n\n**Simple query-response**\n\n- DNS lookups (quick, fire-and-forget)\n- DHCP\n- NTP time synchronization\n\n**Broadcast/Multicast**\n\n- Service discovery (mDNS)\n- IPTV streaming to multiple recipients\n\n**Why not TCP in these cases?**\n\n- TCP's retransmission and ordering can cause latency spikes\n- Connection overhead adds delay\n- Unnecessary for data that becomes stale quickly (old video frames)\n\n**Trade-offs to consider**\n\n- Application-level error handling may be needed\n- You must handle packet loss, reordering, and duplicates yourself\n- Some protocols layer reliability on top of UDP (QUIC, DNS over QUIC)\n\nIf you need guaranteed delivery and ordered data with no gaps, TCP remains the safer choice.",
        "name": "MiniMax AI",
        "audio_content": "",
        "reasoning_content": "The user is asking about when to choose UDP over TCP. This is a follow-up question about networking concepts. I should explain the use cases where UDP is preferable, such as real-time applications where slight data loss is acceptable, broadcasting, DNS queries, etc.\n\nLet me provide a clear, helpful answer about scenarios where UDP is the better choice.",
        "reasoning_details": [
          {
            "type": "reasoning.text",
            "id": "reasoning-text-1",
            "format": "MiniMax-response-v1",
            "index": 0,
            "text": "The user is asking about when to choose UDP over TCP. This is a follow-up question about networking concepts. I should explain the use cases where UDP is preferable, such as real-time applications where slight data loss is acceptable, broadcasting, DNS queries, etc.\n\nLet me provide a clear, helpful answer about scenarios where UDP is the better choice."
          }
        ]
      },
      "finish_reason": "stop"
    }
  ],
  "created": 1780336100,
  "model": "MiniMax-M2.7",
  "object": "chat.completion",
  "usage": {
    "total_tokens": 384,
    "prompt_tokens": 89,
    "completion_tokens": 295,
    "total_characters": 0,
    "completion_tokens_details": {
      "reasoning_tokens": 73
    }
  },
  "input_sensitive": false,
  "output_sensitive": false,
  "base_resp": {
    "status_code": 0,
    "status_msg": ""
  },
  "input_sensitive_type": 0,
  "output_sensitive_type": 0,
  "output_sensitive_int": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'minimax/m2.7',
  {
    max_tokens: 2048,
    messages: [{ content: 'Write a haiku about programming.', role: 'user' }],
    temperature: 0.9,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/m2.7",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "Write a haiku about programming.",
      "role": "user"
    }
  ],
  "temperature": 0.9
}'
```

```
Code flows like water  
Logic weaves in silent streams  
Bugs fade in sunrise
```

```json
{
  "id": "066cf8eba419a621e81c91dd2899b9e6",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Code flows like water  \nLogic weaves in silent streams  \nBugs fade in sunrise",
        "name": "MiniMax AI",
        "audio_content": "",
        "reasoning_content": "The user asks: \"Write a haiku about programming.\" We need to respond with a haiku (5-7-5 syllable structure) about programming. No disallowed content. So simply produce a haiku. Perhaps a nice one. Let's think.\n\nDefinition: Haiku is a short poem with three lines: first line five syllables, second line seven syllables, third line five syllables. Must convey something about programming. Let's craft a haiku.\n\nPossible lines:\n\nLine1: \"Code flows like water\" (Count syllables: Code(1) flows(1) like(1) wa(1) ter(1) -> \"water\" is two syllables: wa-ter = 2, so total = 1+1+1+2 =5) Actually: \"Code flows like water\": Co-de (2) flows (1) like (1) wa-ter (2) = total 6? Let's count: \"Code\" is one syllable? Actually \"code\" is one syllable. So \"Code flows like water\": Code (1) flows (1) like (1) water (2) = total 5. Wait: Code = 1, flows = 1, like = 1, water = 2 => total = 5. Yes. So line1 is 5.\n\nLine2: \"Logic weaves in silent streams\" Count: Logic (2) weaves (1) in (1) si-lent (2) streams (1) = total = 2+1+1+2+1=7. Yes, 7.\n\nLine3: \"Bugs fade in sunrise\" Count: Bugs (1) fade (1) in (1) sun-rise (2) = total =5? Actually \"sunrise\" is two syllables: sun-rise. So Bugs (1) fade (1) in (1) sun-rise (2) = 5. Yes.\n\nAlternatively something about \"silicon dreams\" etc.\n\nMake sure we follow haiku structure: 5-7-5 syllables. Let's double-check.\n\nHaiku about programming:\n\nLine1: \"Code flows like water\" (5)\nLine2: \"Logic weaves in silent streams\" (7)\nLine3: \"Bugs fade in sunrise\" (5)\n\nAll good.\n\nAlternatively: \"Silent code compiles\" (5? Count: Si-lent (2) code (1) com-piles (2) =5) But it's okay.\n\nOk let's produce a haiku: maybe:\n\n\"Silicon sighs at night,\nfunctions dance in bright loops,\nbugs dissolve in dawn.\" Let's count.\n\nLine1: \"Silicon sighs at night\" Count: Si-li-con (3) sighs (1) at (1) night (1) =6? Actually \"silicon\" is three syllables: Si-li-con. sighs=1, at=1, night=1 => total = 3+1+1+1=6. Too many.\n\nMaybe \"Silicon sighs at dusk\" Count: Si-li-con (3) sighs (1) at (1) dusk (1) =6.\n\nOk not that.\n\nBetter to go with first attempt.\n\nMaybe \"Infinite loops at night\" Count: In-fi-nite (3) loops (1) at (1) night (1) =6.\n\nThus keep original.\n\nCheck:\n\nLine1: Code flows like water (5)\nLine2: Logic weaves in silent streams (7)\nLine3: Bugs fade in sunrise (5)\n\nBetter ensure second line count: Logic (2) weaves (1) in (1) silent (2) streams (1) =2+1+1+2+1=7.\n\nThird line: Bugs (1) fade (1) in (1) sunrise (2) =5.\n\nThus ok.\n\nOne could also add a title? The user only asked to write a haiku. So just output the haiku.\n\nThus final answer: the haiku.\n\nMake sure not to have any extra commentary beyond the haiku? The user just asked for a haiku. Typically we can output just the poem. Might add a short line like \"Here's a haiku:\" but that's extra. Safer to just output the poem.\n\nThus final.",
        "reasoning_details": [
          {
            "type": "reasoning.text",
            "id": "reasoning-text-1",
            "format": "MiniMax-response-v1",
            "index": 0,
            "text": "The user asks: \"Write a haiku about programming.\" We need to respond with a haiku (5-7-5 syllable structure) about programming. No disallowed content. So simply produce a haiku. Perhaps a nice one. Let's think.\n\nDefinition: Haiku is a short poem with three lines: first line five syllables, second line seven syllables, third line five syllables. Must convey something about programming. Let's craft a haiku.\n\nPossible lines:\n\nLine1: \"Code flows like water\" (Count syllables: Code(1) flows(1) like(1) wa(1) ter(1) -> \"water\" is two syllables: wa-ter = 2, so total = 1+1+1+2 =5) Actually: \"Code flows like water\": Co-de (2) flows (1) like (1) wa-ter (2) = total 6? Let's count: \"Code\" is one syllable? Actually \"code\" is one syllable. So \"Code flows like water\": Code (1) flows (1) like (1) water (2) = total 5. Wait: Code = 1, flows = 1, like = 1, water = 2 => total = 5. Yes. So line1 is 5.\n\nLine2: \"Logic weaves in silent streams\" Count: Logic (2) weaves (1) in (1) si-lent (2) streams (1) = total = 2+1+1+2+1=7. Yes, 7.\n\nLine3: \"Bugs fade in sunrise\" Count: Bugs (1) fade (1) in (1) sun-rise (2) = total =5? Actually \"sunrise\" is two syllables: sun-rise. So Bugs (1) fade (1) in (1) sun-rise (2) = 5. Yes.\n\nAlternatively something about \"silicon dreams\" etc.\n\nMake sure we follow haiku structure: 5-7-5 syllables. Let's double-check.\n\nHaiku about programming:\n\nLine1: \"Code flows like water\" (5)\nLine2: \"Logic weaves in silent streams\" (7)\nLine3: \"Bugs fade in sunrise\" (5)\n\nAll good.\n\nAlternatively: \"Silent code compiles\" (5? Count: Si-lent (2) code (1) com-piles (2) =5) But it's okay.\n\nOk let's produce a haiku: maybe:\n\n\"Silicon sighs at night,\nfunctions dance in bright loops,\nbugs dissolve in dawn.\" Let's count.\n\nLine1: \"Silicon sighs at night\" Count: Si-li-con (3) sighs (1) at (1) night (1) =6? Actually \"silicon\" is three syllables: Si-li-con. sighs=1, at=1, night=1 => total = 3+1+1+1=6. Too many.\n\nMaybe \"Silicon sighs at dusk\" Count: Si-li-con (3) sighs (1) at (1) dusk (1) =6.\n\nOk not that.\n\nBetter to go with first attempt.\n\nMaybe \"Infinite loops at night\" Count: In-fi-nite (3) loops (1) at (1) night (1) =6.\n\nThus keep original.\n\nCheck:\n\nLine1: Code flows like water (5)\nLine2: Logic weaves in silent streams (7)\nLine3: Bugs fade in sunrise (5)\n\nBetter ensure second line count: Logic (2) weaves (1) in (1) silent (2) streams (1) =2+1+1+2+1=7.\n\nThird line: Bugs (1) fade (1) in (1) sunrise (2) =5.\n\nThus ok.\n\nOne could also add a title? The user only asked to write a haiku. So just output the haiku.\n\nThus final answer: the haiku.\n\nMake sure not to have any extra commentary beyond the haiku? The user just asked for a haiku. Typically we can output just the poem. Might add a short line like \"Here's a haiku:\" but that's extra. Safer to just output the poem.\n\nThus final."
          }
        ]
      },
      "finish_reason": "stop"
    }
  ],
  "created": 1780336107,
  "model": "MiniMax-M2.7",
  "object": "chat.completion",
  "usage": {
    "total_tokens": 936,
    "prompt_tokens": 48,
    "completion_tokens": 888,
    "total_characters": 0,
    "completion_tokens_details": {
      "reasoning_tokens": 872
    }
  },
  "input_sensitive": false,
  "output_sensitive": false,
  "base_resp": {
    "status_code": 0,
    "status_msg": ""
  },
  "input_sensitive_type": 0,
  "output_sensitive_type": 0,
  "output_sensitive_int": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

Chat CompletionsMessages

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 1

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

`string`enum: none, auto

▶response\_format{}

`object`

mask\_sensitive\_info

`boolean`

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

temperature

`number`minimum: 0maximum: 1

top\_p

`number`minimum: 0maximum: 1

top\_k

`number`exclusiveMinimum: 0

stream

`boolean`

▶metadata{}

`object`

id

`string`

▶choices\[]

`array`

created

`number`

model

`string`

object

`string`enum: chat.completion, chat.completion.chunk

▶usage{}

`object`

input\_sensitive

`boolean`

output\_sensitive

`boolean`

▶base\_resp{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/minimax/m2.7/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/minimax/m2.7/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/minimax/m2.7/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/minimax/m2.7/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/minimax/m2.7/#page","headline":"MiniMax M2.7","description":"MiniMax's M2.7 language model with multilingual capabilities.","url":"https://developers.cloudflare.com/ai/models/minimax/m2.7/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: MiniMax's M3 language model with frontier coding and agentic capabilities, a 1M token context window, and multilingual support.
title: MiniMax M3
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)

# MiniMax M3

Text Generation • MiniMax

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/minimax/m3/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`minimax/m3`

- Third-party
- Zero data retention

MiniMax's M3 language model with frontier coding and agentic capabilities, a 1M token context window, and multilingual support.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://www.minimaxi.com/terms) |
| More information | [link ↗](https://www.minimax.io/blog/minimax-m3) |
| Zero data retention | Yes |
| Request formats | Chat Completions, Anthropic Messages |
| Pricing | <ul><li>Input <=512k (per 1M)$0.30</li><li>Cached input <=512k (per 1M)$0.06</li><li>Output <=512k (per 1M)$1.20</li><li>Input >512k (per 1M)$1.20</li><li>Cached input >512k (per 1M)$0.24</li><li>Output >512k (per 1M)$4.80</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'minimax/m3',
  { max_tokens: 2048, messages: [{ content: 'What is the capital of France?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/m3",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "What is the capital of France?",
      "role": "user"
    }
  ]
}'
```

```
The capital of France is **Paris**.
```

```json
{
  "id": "066cf8a95614a7ebfcaa6ffd7f2cd663",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The capital of France is **Paris**.",
        "name": "MiniMax AI",
        "audio_content": "",
        "reasoning_content": "The user is asking a simple factual question: \"What is the capital of France?\" This is straightforward - the capital of France is Paris.",
        "reasoning_details": [
          {
            "type": "reasoning.text",
            "id": "reasoning-text-1",
            "format": "MiniMax-response-v1",
            "index": 0,
            "text": "The user is asking a simple factual question: \"What is the capital of France?\" This is straightforward - the capital of France is Paris."
          }
        ]
      },
      "finish_reason": "stop"
    }
  ],
  "created": 1780336041,
  "model": "MiniMax-M3",
  "object": "chat.completion",
  "usage": {
    "total_tokens": 221,
    "prompt_tokens": 183,
    "completion_tokens": 38,
    "total_characters": 0,
    "prompt_tokens_details": {
      "cached_tokens": 114
    }
  },
  "input_sensitive": false,
  "output_sensitive": false,
  "base_resp": {
    "status_code": 0,
    "status_msg": ""
  },
  "input_sensitive_type": 0,
  "output_sensitive_type": 0,
  "output_sensitive_int": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Prompt** — Using a system prompt to guide behavior</summary>



```ts
const response = await env.AI.run(
  'minimax/m3',
  {
    max_tokens: 2048,
    messages: [
      {
        content:
          'You are a helpful cooking assistant. Give concise recipes with metric measurements.',
        role: 'system',
      },
      { content: 'How do I make a simple pasta aglio e olio?', role: 'user' },
    ],
    temperature: 0.7,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/m3",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "You are a helpful cooking assistant. Give concise recipes with metric measurements.",
      "role": "system"
    },
    {
      "content": "How do I make a simple pasta aglio e olio?",
      "role": "user"
    }
  ],
  "temperature": 0.7
}'
```

```
# Pasta Aglio e Olio

A classic Italian dish that comes together in minutes with just a few ingredients.

**Serves:** 2 | **Prep:** 5 min | **Cook:** 15 min

## Ingredients
- 200 g spaghetti or linguine
- 80 ml extra virgin olive oil
- 4 garlic cloves, thinly sliced
- 1–2 small dried red chilies, crushed (or ¼ tsp chili flakes)
- Salt, for pasta water
- 15 g fresh flat-leaf parsley, chopped
- Grated Parmesan or Pecorino (optional, traditionalists skip it)

## Method
1. **Boil pasta:** Bring a large pot of well-salted water to a rolling boil. Cook the pasta until al dente (about 1 minute less than package instructions). Reserve 1 cup of pasta water before draining.
2. **Infuse oil:** While the pasta cooks, gently heat the olive oil in a wide pan over low-medium heat. Add the garlic and chilies, and cook slowly for 2–3 minutes until the garlic turns pale golden. **Don't let it brown** — it will turn bitter.
3. **Combine:** Add the drained pasta to the pan with a splash of reserved pasta water. Toss vigorously over medium heat for about 1 minute so the pasta absorbs the oil.
4. **Finish:** Add more pasta water as needed to create a light, silky sauce that coats the noodles. Stir in the parsley and season with salt.
5. **Serve** immediately, topped with cheese if using.

## Tips
- Cold olive oil + slow heat = better flavor extraction.
- The starch in the pasta water is key to a glossy, emulsified sauce.

Buon appetito! 🍝
```

```json
{
  "id": "066cf8abfaba58c357c660ebfad38073",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "# Pasta Aglio e Olio\n\nA classic Italian dish that comes together in minutes with just a few ingredients.\n\n**Serves:** 2 | **Prep:** 5 min | **Cook:** 15 min\n\n## Ingredients\n- 200 g spaghetti or linguine\n- 80 ml extra virgin olive oil\n- 4 garlic cloves, thinly sliced\n- 1–2 small dried red chilies, crushed (or ¼ tsp chili flakes)\n- Salt, for pasta water\n- 15 g fresh flat-leaf parsley, chopped\n- Grated Parmesan or Pecorino (optional, traditionalists skip it)\n\n## Method\n1. **Boil pasta:** Bring a large pot of well-salted water to a rolling boil. Cook the pasta until al dente (about 1 minute less than package instructions). Reserve 1 cup of pasta water before draining.\n2. **Infuse oil:** While the pasta cooks, gently heat the olive oil in a wide pan over low-medium heat. Add the garlic and chilies, and cook slowly for 2–3 minutes until the garlic turns pale golden. **Don't let it brown** — it will turn bitter.\n3. **Combine:** Add the drained pasta to the pan with a splash of reserved pasta water. Toss vigorously over medium heat for about 1 minute so the pasta absorbs the oil.\n4. **Finish:** Add more pasta water as needed to create a light, silky sauce that coats the noodles. Stir in the parsley and season with salt.\n5. **Serve** immediately, topped with cheese if using.\n\n## Tips\n- Cold olive oil + slow heat = better flavor extraction.\n- The starch in the pasta water is key to a glossy, emulsified sauce.\n\nBuon appetito! 🍝",
        "name": "MiniMax AI",
        "audio_content": "",
        "reasoning_content": "The user is asking for a simple pasta aglio e olio recipe. The system prompt says I should give concise recipes with metric measurements. Let me provide a classic, simple recipe.",
        "reasoning_details": [
          {
            "type": "reasoning.text",
            "id": "reasoning-text-1",
            "format": "MiniMax-response-v1",
            "index": 0,
            "text": "The user is asking for a simple pasta aglio e olio recipe. The system prompt says I should give concise recipes with metric measurements. Let me provide a classic, simple recipe."
          }
        ]
      },
      "finish_reason": "stop"
    }
  ],
  "created": 1780336043,
  "model": "MiniMax-M3",
  "object": "chat.completion",
  "usage": {
    "total_tokens": 595,
    "prompt_tokens": 197,
    "completion_tokens": 398,
    "total_characters": 0,
    "prompt_tokens_details": {
      "cached_tokens": 114
    }
  },
  "input_sensitive": false,
  "output_sensitive": false,
  "base_resp": {
    "status_code": 0,
    "status_msg": ""
  },
  "input_sensitive_type": 0,
  "output_sensitive_type": 0,
  "output_sensitive_int": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'minimax/m3',
  {
    max_tokens: 2048,
    messages: [
      { content: 'What are the main differences between TCP and UDP?', role: 'user' },
      {
        content:
          'TCP is connection-oriented and guarantees delivery, while UDP is connectionless and faster but without delivery guarantees.',
        role: 'assistant',
      },
      { content: 'When would I choose UDP over TCP?', role: 'user' },
    ],
    temperature: 0.5,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/m3",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "What are the main differences between TCP and UDP?",
      "role": "user"
    },
    {
      "content": "TCP is connection-oriented and guarantees delivery, while UDP is connectionless and faster but without delivery guarantees.",
      "role": "assistant"
    },
    {
      "content": "When would I choose UDP over TCP?",
      "role": "user"
    }
  ],
  "temperature": 0.5
}'
```

```
Use UDP for time-sensitive applications like video streaming, online gaming, or VoIP where speed matters more than perfect reliability.
```

```json
{
  "id": "066cf8bb1c666fc68c6810518100c7ba",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Use UDP for time-sensitive applications like video streaming, online gaming, or VoIP where speed matters more than perfect reliability.",
        "name": "MiniMax AI",
        "audio_content": "",
        "reasoning_content": ""
      },
      "finish_reason": "stop"
    }
  ],
  "created": 1780336059,
  "model": "MiniMax-M3",
  "object": "chat.completion",
  "usage": {
    "total_tokens": 250,
    "prompt_tokens": 225,
    "completion_tokens": 25,
    "total_characters": 0,
    "prompt_tokens_details": {
      "cached_tokens": 114
    }
  },
  "input_sensitive": false,
  "output_sensitive": false,
  "base_resp": {
    "status_code": 0,
    "status_msg": ""
  },
  "input_sensitive_type": 0,
  "output_sensitive_type": 0,
  "output_sensitive_int": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>



```ts
const response = await env.AI.run(
  'minimax/m3',
  {
    max_tokens: 2048,
    messages: [{ content: 'Write a haiku about programming.', role: 'user' }],
    temperature: 0.9,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/m3",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "Write a haiku about programming.",
      "role": "user"
    }
  ],
  "temperature": 0.9
}'
```

```
Fingers on the keys,
Building worlds from empty void—
Code becomes the light.
```

```json
{
  "id": "066cf8be5675980f2ff647974879fb77",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Fingers on the keys,\nBuilding worlds from empty void—\nCode becomes the light.",
        "name": "MiniMax AI",
        "audio_content": "",
        "reasoning_content": "The user wants a haiku about programming. A haiku is a traditional Japanese poem with three lines following a 5-7-5 syllable pattern. I should create one that captures something meaningful about programming.\n\nLet me think of a few options:\n\n1. About debugging:\nLines (5-7-5):\n- \"Bugs hide in the code\" (4) - need 5\n- \"Silent errors whisper\" (6) - need 7\n- \"Find them, fix, deploy\" (5) ✓\n\nLet me recount:\n- \"Bugs hide in the code\" - Bugs(1) hide(2) in(3) the(4) code(5) = 5 ✓\n- \"Silent errors whisper\" - Si-lent(2) er-rors(4) whis-per(6) = 6, need 7\n- Try: \"Silent errors always whisper\" - 7 ✓\n- \"Find them, fix, deploy\" - Find(1) them(2) fix(3) de-ploy(5) = 5 ✓\n\n2. About code in general:\n- \"Logic flows like streams\" (5) - Lo-gic(2) flows(3) like(4) streams(5) = 5 ✓\n- \"Through brackets and curved braces\" (7) - Through(1) brack-ets(3) and(4) curved(5) bra-ces(7) = 7 ✓\n- \"Dreams made into life\" (5) - Dreams(1) made(2) in-to(4) life(5) = 5 ✓\n\n3. Another option:\n- \"Fingers on the keys\" (5) - Fin-gers(2) on(3) the(4) keys(5) = 5 ✓\n- \"Building worlds from nothing\" (7) - Build-ing(2) worlds(3) from(4) no-thing(6) = 6, need 7\n- Try: \"Building worlds from empty void\" - Build-ing(2) worlds(3) from(4) emp-ty(6) void(7) = 7 ✓\n- \"Code becomes the light\" (5) - Code(1) be-comes(3) the(4) light(5) = 5 ✓\n\nLet me go with option 2 or 3, both are nice. I'll provide one clean haiku and maybe offer an alternative.\n\nActually, let me just give one good one. Option 3 feels more poetic and evocative.\n\nLet me verify option 3 once more:\n- \"Fingers on the keys\" - Fin-gers(2) on(3) the(4) keys(5) = 5 ✓\n- \"Building worlds from empty void\" - Build-ing(2) worlds(3) from(4) emp-ty(6) void(7) = 7 ✓\n- \"Code becomes the light\" - Code(1) be-comes(3) the(4) light(5) = 5 ✓\n\nThat works well. I could also provide a simpler one focused on a different aspect of programming.\n\nI'll give a haiku with a clean delivery. Let me also think about a second option to make it more useful, or just stick with one well-crafted one.\n\nI'll provide one haiku and keep it concise.",
        "reasoning_details": [
          {
            "type": "reasoning.text",
            "id": "reasoning-text-1",
            "format": "MiniMax-response-v1",
            "index": 0,
            "text": "The user wants a haiku about programming. A haiku is a traditional Japanese poem with three lines following a 5-7-5 syllable pattern. I should create one that captures something meaningful about programming.\n\nLet me think of a few options:\n\n1. About debugging:\nLines (5-7-5):\n- \"Bugs hide in the code\" (4) - need 5\n- \"Silent errors whisper\" (6) - need 7\n- \"Find them, fix, deploy\" (5) ✓\n\nLet me recount:\n- \"Bugs hide in the code\" - Bugs(1) hide(2) in(3) the(4) code(5) = 5 ✓\n- \"Silent errors whisper\" - Si-lent(2) er-rors(4) whis-per(6) = 6, need 7\n- Try: \"Silent errors always whisper\" - 7 ✓\n- \"Find them, fix, deploy\" - Find(1) them(2) fix(3) de-ploy(5) = 5 ✓\n\n2. About code in general:\n- \"Logic flows like streams\" (5) - Lo-gic(2) flows(3) like(4) streams(5) = 5 ✓\n- \"Through brackets and curved braces\" (7) - Through(1) brack-ets(3) and(4) curved(5) bra-ces(7) = 7 ✓\n- \"Dreams made into life\" (5) - Dreams(1) made(2) in-to(4) life(5) = 5 ✓\n\n3. Another option:\n- \"Fingers on the keys\" (5) - Fin-gers(2) on(3) the(4) keys(5) = 5 ✓\n- \"Building worlds from nothing\" (7) - Build-ing(2) worlds(3) from(4) no-thing(6) = 6, need 7\n- Try: \"Building worlds from empty void\" - Build-ing(2) worlds(3) from(4) emp-ty(6) void(7) = 7 ✓\n- \"Code becomes the light\" (5) - Code(1) be-comes(3) the(4) light(5) = 5 ✓\n\nLet me go with option 2 or 3, both are nice. I'll provide one clean haiku and maybe offer an alternative.\n\nActually, let me just give one good one. Option 3 feels more poetic and evocative.\n\nLet me verify option 3 once more:\n- \"Fingers on the keys\" - Fin-gers(2) on(3) the(4) keys(5) = 5 ✓\n- \"Building worlds from empty void\" - Build-ing(2) worlds(3) from(4) emp-ty(6) void(7) = 7 ✓\n- \"Code becomes the light\" - Code(1) be-comes(3) the(4) light(5) = 5 ✓\n\nThat works well. I could also provide a simpler one focused on a different aspect of programming.\n\nI'll give a haiku with a clean delivery. Let me also think about a second option to make it more useful, or just stick with one well-crafted one.\n\nI'll provide one haiku and keep it concise."
          }
        ]
      },
      "finish_reason": "stop"
    }
  ],
  "created": 1780336062,
  "model": "MiniMax-M3",
  "object": "chat.completion",
  "usage": {
    "total_tokens": 912,
    "prompt_tokens": 183,
    "completion_tokens": 729,
    "total_characters": 0,
    "prompt_tokens_details": {
      "cached_tokens": 114
    }
  },
  "input_sensitive": false,
  "output_sensitive": false,
  "base_resp": {
    "status_code": 0,
    "status_msg": ""
  },
  "input_sensitive_type": 0,
  "output_sensitive_type": 0,
  "output_sensitive_int": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

Chat CompletionsMessages

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 1

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

`string`enum: none, auto

▶response\_format{}

`object`

mask\_sensitive\_info

`boolean`

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

temperature

`number`minimum: 0maximum: 1

top\_p

`number`minimum: 0maximum: 1

top\_k

`number`exclusiveMinimum: 0

stream

`boolean`

▶metadata{}

`object`

id

`string`

▶choices\[]

`array`

created

`number`

model

`string`

object

`string`enum: chat.completion, chat.completion.chunk

▶usage{}

`object`

input\_sensitive

`boolean`

output\_sensitive

`boolean`

▶base\_resp{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/minimax/m3/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/minimax/m3/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/minimax/m3/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/minimax/m3/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/minimax/m3/#page","headline":"MiniMax M3","description":"MiniMax's M3 language model with frontier coding and agentic capabilities, a 1M token context window, and multilingual support.","url":"https://developers.cloudflare.com/ai/models/minimax/m3/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: MiniMax's music generation model that creates full-length songs with vocals from text prompts and lyrics, or instrumental tracks. Supports BPM/key control and auto-generated lyrics.
title: MiniMax Music 2.6
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)

# MiniMax Music 2.6

Music Generation • MiniMax

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/minimax/music-2.6/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`minimax/music-2.6`

- Third-party
- Zero data retention

MiniMax's music generation model that creates full-length songs with vocals from text prompts and lyrics, or instrumental tracks. Supports BPM/key control and auto-generated lyrics.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.minimaxi.com/terms) |
| More information | [link ↗](https://www.minimaxi.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per track$0.15</li><li>Per lyrics generation$0.01</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'minimax/music-2.6',
  {
    prompt: 'An upbeat electronic dance track with a catchy synth melody and driving beat',
    is_instrumental: false,
    lyrics_optimizer: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/music-2.6",
  "input": {
    "prompt": "An upbeat electronic dance track with a catchy synth melody and driving beat",
    "is_instrumental": false,
    "lyrics_optimizer": true
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://minimax-algeng-chat-tts-us.oss-us-east-1.aliyuncs.com/music%2Fprod%2Ftts-20260417092034-QxSPMzdbiRxBSbDb.mp3"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**With Lyrics** — Generate a song with custom lyrics</summary>



```ts
const response = await env.AI.run(
  'minimax/music-2.6',
  {
    prompt: 'A warm acoustic folk ballad with fingerpicked guitar and gentle vocals',
    is_instrumental: false,
    lyrics:
      'Walking down a dusty road\nWith the sunset painting gold\nEvery step a story told\nOf the places I call home',
    lyrics_optimizer: false,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/music-2.6",
  "input": {
    "prompt": "A warm acoustic folk ballad with fingerpicked guitar and gentle vocals",
    "is_instrumental": false,
    "lyrics": "Walking down a dusty road\nWith the sunset painting gold\nEvery step a story told\nOf the places I call home",
    "lyrics_optimizer": false
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://minimax-algeng-chat-tts-us.oss-us-east-1.aliyuncs.com/music%2Fprod%2Ftts-20260417091919-YiIxwmvIqXtREDcu.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Instrumental** — Generate instrumental music without vocals</summary>



```ts
const response = await env.AI.run(
  'minimax/music-2.6',
  {
    prompt: 'A calm lo-fi hip hop instrumental with vinyl crackle and mellow piano chords',
    is_instrumental: true,
    lyrics_optimizer: false,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/music-2.6",
  "input": {
    "prompt": "A calm lo-fi hip hop instrumental with vinyl crackle and mellow piano chords",
    "is_instrumental": true,
    "lyrics_optimizer": false
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://minimax-algeng-chat-tts-us.oss-us-east-1.aliyuncs.com/music%2Fprod%2Ftts-20260417092057-LOwvBOOdyGvAyHkQ.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**High Quality Audio** — Specify audio format and sample rate</summary>



```ts
const response = await env.AI.run(
  'minimax/music-2.6',
  {
    prompt: 'An orchestral cinematic score building to an epic crescendo with full symphony',
    format: 'wav',
    is_instrumental: false,
    lyrics_optimizer: true,
    sample_rate: 44100,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/music-2.6",
  "input": {
    "prompt": "An orchestral cinematic score building to an epic crescendo with full symphony",
    "format": "wav",
    "is_instrumental": false,
    "lyrics_optimizer": true,
    "sample_rate": 44100
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://minimax-algeng-chat-tts-us.oss-us-east-1.aliyuncs.com/music%2Fprod%2Ftts-20260417092208-UGTfqDggHaemCDAW.wav"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Auto-Generated Lyrics** — Let the model generate lyrics from the prompt</summary>



```ts
const response = await env.AI.run(
  'minimax/music-2.6',
  {
    prompt: 'A cheerful pop song about a summer road trip with friends',
    is_instrumental: false,
    lyrics_optimizer: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/music-2.6",
  "input": {
    "prompt": "A cheerful pop song about a summer road trip with friends",
    "is_instrumental": false,
    "lyrics_optimizer": true
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://minimax-algeng-chat-tts-us.oss-us-east-1.aliyuncs.com/music%2Fprod%2Ftts-20260417092245-UlqOBbhqSXtRPopt.mp3"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`requiredmaxLength: 2000Description of the music style, mood, and scenario

lyrics

`string`minLength: 1maxLength: 3500Song lyrics, using \\n to separate lines

▶sample\_rate

`one of`

▶bitrate

`one of`

format

`string`enum: mp3, wavAudio format

lyrics\_optimizer

`boolean`requireddefault: falseAutomatically generate lyrics based on the prompt description

is\_instrumental

`boolean`requireddefault: falseGenerate instrumental music (no vocals)

audio

`string`format: uriURL to the generated audio file

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/minimax/music-2.6/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/minimax/music-2.6/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/minimax/music-2.6/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/minimax/music-2.6/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/minimax/music-2.6/#page","headline":"MiniMax Music 2.6","description":"MiniMax's music generation model that creates full-length songs with vocals from text prompts and lyrics, or instrumental tracks. Supports BPM/key control and auto-generated lyrics.","url":"https://developers.cloudflare.com/ai/models/minimax/music-2.6/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: MiniMax Speech 2.8 HD focuses on studio-grade audio generation with emotion control, multilingual support (40+ languages), and voice cloning.
title: MiniMax Speech 2.8 HD
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)

# MiniMax Speech 2.8 HD

Text-to-Speech • MiniMax

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-hd/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`minimax/speech-2.8-hd`

- Third-party
- Zero data retention

MiniMax Speech 2.8 HD focuses on studio-grade audio generation with emotion control, multilingual support (40+ languages), and voice cloning.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.minimaxi.com/terms) |
| More information | [link ↗](https://www.minimaxi.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per character$0.0001</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'minimax/speech-2.8-hd',
  {
    format: 'mp3',
    pitch: 0,
    speed: 1,
    text: 'Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.',
    voice_id: 'English_expressive_narrator',
    volume: 1,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/speech-2.8-hd",
  "input": {
    "format": "mp3",
    "pitch": 0,
    "speed": 1,
    "text": "Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.",
    "voice_id": "English_expressive_narrator",
    "volume": 1
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/minimax__speech-2.8-hd/simple-speech.mp3"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Custom Voice** — Use a specific voice and adjust speed</summary>



```ts
const response = await env.AI.run(
  'minimax/speech-2.8-hd',
  {
    format: 'mp3',
    pitch: 0,
    speed: 0.9,
    text: 'The weather today is sunny with a high of 72 degrees. Perfect for a walk in the park.',
    voice_id: 'English_expressive_narrator',
    volume: 1,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/speech-2.8-hd",
  "input": {
    "format": "mp3",
    "pitch": 0,
    "speed": 0.9,
    "text": "The weather today is sunny with a high of 72 degrees. Perfect for a walk in the park.",
    "voice_id": "English_expressive_narrator",
    "volume": 1
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/minimax__speech-2.8-hd/custom-voice.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**With Emotion** — Apply emotional tone to speech</summary>



```ts
const response = await env.AI.run(
  'minimax/speech-2.8-hd',
  {
    emotion: 'happy',
    format: 'mp3',
    pitch: 0,
    speed: 1,
    text: "Congratulations! You've just won the grand prize! This is absolutely incredible news!",
    voice_id: 'English_expressive_narrator',
    volume: 1,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/speech-2.8-hd",
  "input": {
    "emotion": "happy",
    "format": "mp3",
    "pitch": 0,
    "speed": 1,
    "text": "Congratulations! You'\''ve just won the grand prize! This is absolutely incredible news!",
    "voice_id": "English_expressive_narrator",
    "volume": 1
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/minimax__speech-2.8-hd/with-emotion.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**High Sample Rate** — Studio quality at 44.1kHz sample rate</summary>



```ts
const response = await env.AI.run(
  'minimax/speech-2.8-hd',
  {
    format: 'mp3',
    pitch: 0,
    sample_rate: 44100,
    speed: 1,
    text: 'This recording is generated at studio quality sample rate for the highest possible audio fidelity.',
    voice_id: 'English_expressive_narrator',
    volume: 1,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/speech-2.8-hd",
  "input": {
    "format": "mp3",
    "pitch": 0,
    "sample_rate": 44100,
    "speed": 1,
    "text": "This recording is generated at studio quality sample rate for the highest possible audio fidelity.",
    "voice_id": "English_expressive_narrator",
    "volume": 1
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/minimax__speech-2.8-hd/high-sample-rate.mp3"
  },
  "state": "Completed"
}
```

</details>

## Parameters

text

`string`requiredmaxLength: 10000The text to convert to speech. Maximum 10,000 characters.

voice\_id

`string`requireddefault: English\_expressive\_narratorThe voice ID to use for synthesis

speed

`number`requireddefault: 1minimum: 0.5maximum: 2Speech speed (0.5 to 2)

volume

`number`requireddefault: 1minimum: 0maximum: 10Speech volume (0 to 10)

pitch

`integer`requireddefault: 0minimum: -12maximum: 12Pitch adjustment (-12 to 12)

emotion

`string`enum: happy, sad, angry, fearful, disgusted, surprised, calm, fluentEmotion control for synthesized speech

format

`string`requireddefault: mp3enum: mp3, flac, wavOutput audio format

▶sample\_rate

`one of`

audio

`string`URL to the generated audio file

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-hd/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-hd/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-hd/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-hd/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/minimax/speech-2.8-hd/#page","headline":"MiniMax Speech 2.8 HD","description":"MiniMax Speech 2.8 HD focuses on studio-grade audio generation with emotion control, multilingual support (40+ languages), and voice cloning.","url":"https://developers.cloudflare.com/ai/models/minimax/speech-2.8-hd/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: MiniMax Speech 2.8 Turbo turns text into natural, expressive speech with voice cloning, emotion control, and 40+ language support at faster speeds.
title: MiniMax Speech 2.8 Turbo
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![MiniMax logo](https://developers.cloudflare.com/_astro/minimax.B0Y99aoe.svg)

# MiniMax Speech 2.8 Turbo

Text-to-Speech • MiniMax

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-turbo/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`minimax/speech-2.8-turbo`

- Third-party
- Zero data retention

MiniMax Speech 2.8 Turbo turns text into natural, expressive speech with voice cloning, emotion control, and 40+ language support at faster speeds.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.minimaxi.com/terms) |
| More information | [link ↗](https://www.minimaxi.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per character$0.00006</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'minimax/speech-2.8-turbo',
  {
    format: 'mp3',
    pitch: 0,
    speed: 1,
    text: 'Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.',
    voice_id: 'English_expressive_narrator',
    volume: 1,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/speech-2.8-turbo",
  "input": {
    "format": "mp3",
    "pitch": 0,
    "speed": 1,
    "text": "Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.",
    "voice_id": "English_expressive_narrator",
    "volume": 1
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/minimax__speech-2.8-turbo/simple-speech.mp3"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Fast Narration** — Speed up narration for quick playback</summary>



```ts
const response = await env.AI.run(
  'minimax/speech-2.8-turbo',
  {
    format: 'mp3',
    pitch: 0,
    speed: 1.5,
    text: 'This is a fast-paced summary of the key findings from the quarterly report. Revenue is up fifteen percent and user growth exceeded expectations.',
    voice_id: 'English_expressive_narrator',
    volume: 1,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/speech-2.8-turbo",
  "input": {
    "format": "mp3",
    "pitch": 0,
    "speed": 1.5,
    "text": "This is a fast-paced summary of the key findings from the quarterly report. Revenue is up fifteen percent and user growth exceeded expectations.",
    "voice_id": "English_expressive_narrator",
    "volume": 1
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/minimax__speech-2.8-turbo/fast-narration.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Calm Tone** — Calm and steady speech for meditation or relaxation</summary>



```ts
const response = await env.AI.run(
  'minimax/speech-2.8-turbo',
  {
    emotion: 'calm',
    format: 'mp3',
    pitch: 0,
    speed: 0.8,
    text: 'Take a deep breath in. Hold it for a moment. Now slowly exhale. Let your shoulders relax and release any tension.',
    voice_id: 'English_expressive_narrator',
    volume: 1,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/speech-2.8-turbo",
  "input": {
    "emotion": "calm",
    "format": "mp3",
    "pitch": 0,
    "speed": 0.8,
    "text": "Take a deep breath in. Hold it for a moment. Now slowly exhale. Let your shoulders relax and release any tension.",
    "voice_id": "English_expressive_narrator",
    "volume": 1
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/minimax__speech-2.8-turbo/calm-tone.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Adjusted Pitch** — Lower the pitch for a deeper voice</summary>



```ts
const response = await env.AI.run(
  'minimax/speech-2.8-turbo',
  {
    format: 'mp3',
    pitch: -6,
    speed: 1,
    text: 'Good evening. Tonight we explore the mysteries of the deep ocean and the creatures that live in total darkness.',
    voice_id: 'English_expressive_narrator',
    volume: 1,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "minimax/speech-2.8-turbo",
  "input": {
    "format": "mp3",
    "pitch": -6,
    "speed": 1,
    "text": "Good evening. Tonight we explore the mysteries of the deep ocean and the creatures that live in total darkness.",
    "voice_id": "English_expressive_narrator",
    "volume": 1
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/minimax__speech-2.8-turbo/adjusted-pitch.mp3"
  },
  "state": "Completed"
}
```

</details>

## Parameters

text

`string`requiredmaxLength: 10000The text to convert to speech. Maximum 10,000 characters.

voice\_id

`string`requireddefault: English\_expressive\_narratorThe voice ID to use for synthesis

speed

`number`requireddefault: 1minimum: 0.5maximum: 2Speech speed (0.5 to 2)

volume

`number`requireddefault: 1minimum: 0maximum: 10Speech volume (0 to 10)

pitch

`integer`requireddefault: 0minimum: -12maximum: 12Pitch adjustment (-12 to 12)

emotion

`string`enum: happy, sad, angry, fearful, disgusted, surprised, calm, fluentEmotion control for synthesized speech

format

`string`requireddefault: mp3enum: mp3, flac, wavOutput audio format

▶sample\_rate

`one of`

audio

`string`URL to the generated audio file

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-turbo/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-turbo/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-turbo/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/minimax/speech-2.8-turbo/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/minimax/speech-2.8-turbo/#page","headline":"MiniMax Speech 2.8 Turbo","description":"MiniMax Speech 2.8 Turbo turns text into natural, expressive speech with voice cloning, emotion control, and 40+ language support at faster speeds.","url":"https://developers.cloudflare.com/ai/models/minimax/speech-2.8-turbo/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Kimi K3 is Moonshot's flagship 2.8 trillion-parameter model, built on Kimi Delta Attention (a hybrid linear attention mechanism) with Attention Residuals. It offers native visual understanding, always-on reasoning, and a 1M-token context window for long-horizon coding, knowledge work, and deep reasoning tasks.
title: Kimi K3
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Moonshot AI logo](https://developers.cloudflare.com/_astro/moonshotai.DjWMkXUS.svg)

# Kimi K3

Text Generation • Moonshot AI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/moonshotai/kimi-k3/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`moonshotai/kimi-k3`

- Third-party

Kimi K3 is Moonshot's flagship 2.8 trillion-parameter model, built on Kimi Delta Attention (a hybrid linear attention mechanism) with Attention Residuals. It offers native visual understanding, always-on reasoning, and a 1M-token context window for long-horizon coding, knowledge work, and deep reasoning tasks.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,048,576 tokens |
| More information | [link ↗](https://platform.kimi.ai/docs/guide/kimi-k3-quickstart) |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$3.00</li><li>Output (per 1M tokens)$15.00</li><li>Cached input (per 1M tokens)$0.30</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'moonshotai/kimi-k3',
  { messages: [{ content: 'Explain quantum entanglement in simple terms.', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "moonshotai/kimi-k3",
  "messages": [
    {
      "content": "Explain quantum entanglement in simple terms.",
      "role": "user"
    }
  ]
}'
```

```
Quantum entanglement is when two particles become linked in such a way that they behave as a single system — even when separated by vast distances.

**An analogy to start:**
Imagine two coins that are mysteriously connected. You shuffle them, keep one, and mail the other to a friend across the world. The moment you look at your coin and see heads, you instantly know your friend's coin shows tails.

**Here's where it gets weird:**
With ordinary coins, the outcome was fixed all along — your coin was *already* heads before you looked. But quantum mechanics says something stranger: before measurement, entangled particles don't have definite properties at all. Each exists in a haze of possibilities (called "superposition"). The instant you measure one, it "settles" into a state — and its partner instantly takes on the matching state, no matter how far away it is.

**Why this bothered Einstein:**
He famously called it "spooky action at a distance," because it seemed like the particles were communicating faster than light — which relativity says is impossible. He suspected the particles carried hidden instructions all along. But experiments over the past few decades (recognized with the 2022 Nobel Prize in Physics) proved Einstein wrong: the correlations are real, and the particles genuinely don't have definite states until measured.

**One important caveat:**
You *can't* use entanglement to send messages faster than light. The outcome you see is random, so there's no way to encode information in it. The connection only becomes apparent when both sides compare their results through normal, slower-than-light channels.

**Why it matters:**
Entanglement isn't just a curiosity — it's the foundation of quantum computing, ultra-secure quantum cryptography, and emerging quantum communication networks.

In short: entangled particles share one fate, and measuring one instantly shapes the other — a phenomenon so strange that even Einstein refused to believe it.
```

```json
{
  "id": "chatcmpl-6a592349f5fee221445e964f",
  "object": "chat.completion",
  "created": 1784226633,
  "model": "moonshotai/kimi-k3",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Quantum entanglement is when two particles become linked in such a way that they behave as a single system — even when separated by vast distances.\n\n**An analogy to start:**\nImagine two coins that are mysteriously connected. You shuffle them, keep one, and mail the other to a friend across the world. The moment you look at your coin and see heads, you instantly know your friend's coin shows tails.\n\n**Here's where it gets weird:**\nWith ordinary coins, the outcome was fixed all along — your coin was *already* heads before you looked. But quantum mechanics says something stranger: before measurement, entangled particles don't have definite properties at all. Each exists in a haze of possibilities (called \"superposition\"). The instant you measure one, it \"settles\" into a state — and its partner instantly takes on the matching state, no matter how far away it is.\n\n**Why this bothered Einstein:**\nHe famously called it \"spooky action at a distance,\" because it seemed like the particles were communicating faster than light — which relativity says is impossible. He suspected the particles carried hidden instructions all along. But experiments over the past few decades (recognized with the 2022 Nobel Prize in Physics) proved Einstein wrong: the correlations are real, and the particles genuinely don't have definite states until measured.\n\n**One important caveat:**\nYou *can't* use entanglement to send messages faster than light. The outcome you see is random, so there's no way to encode information in it. The connection only becomes apparent when both sides compare their results through normal, slower-than-light channels.\n\n**Why it matters:**\nEntanglement isn't just a curiosity — it's the foundation of quantum computing, ultra-secure quantum cryptography, and emerging quantum communication networks.\n\nIn short: entangled particles share one fate, and measuring one instantly shapes the other — a phenomenon so strange that even Einstein refused to believe it.",
        "reasoning_content": "The user wants a simple explanation of quantum entanglement. This is a physics concept that many people find confusing, so my goal is to make it accessible without dumbing it down to the point of inaccuracy.\n\nLet me think about what quantum entanglement actually is:\n- Quantum entanglement is a phenomenon where two or more particles become correlated in such a way that the quantum state of each particle cannot be described independently of the others, even when separated by large distances.\n- When you measure one particle of an entangled pair, you instantly know something about the other particle, regardless of the distance between them.\n- Einstein famously called it \"spooky action at a distance.\"\n\nKey points I want to convey:\n1. What entanglement is (particles linked in a special way)\n2. The strange part: measuring one instantly tells you about the other\n3. Why it's weird (this seems to defy our classical intuitions)\n4. Maybe clear up a common misconception: you can't use it to send information faster than light\n\nGood analogies to consider:\n- The classic glove analogy: You put a left glove and right glove in separate boxes, send one to a friend. When you open yours and see the left glove, you instantly know your friend has the right one. BUT this analogy is actually misleading because it suggests hidden variables — the gloves were always left and right. Quantum mechanics says the particles don't have definite states until measured (Bell's theorem proved this). I should be careful here. I could use the analogy but then explain why it falls short, which is actually a great pedagogical approach — it highlights what's truly weird about entanglement.\n\n- The coin analogy: two coins that always land on opposite sides when flipped. Similar issue with hidden variables.\n\nActually, the best approach might be:\n1. Start with the intuitive analogy (gloves or coins)\n2. Explain the quantum twist: unlike gloves, the particles don't have definite properties until measured — they're in a \"superposition\" of states\n3. The measurement of one \"collapses\" both into definite states instantly\n4. Mention why this bothered Einstein\n5. Clarify the no-faster-than-light-communication point\n6. Maybe mention practical applications briefly (quantum computing, quantum cryptography)\n\nLet me think about format:\n- \"Simple terms\" request means I should avoid jargon or explain it when used\n- Should be conversational but informative\n- Medium length — not too short that it's unhelpful, not so long it overwhelms\n- Could use a brief structure but probably flowing prose with maybe a couple of natural paragraph breaks works well for an explanation\n- An analogy is essential for \"simple terms\"\n\nLet me draft this:\n\n---\n\nQuantum entanglement is when two particles become linked so that they behave as one system, no matter how far apart they are.\n\n**The basic idea:**\nImagine you have two coins that are \"entangled.\" You shake them up and send one to a friend on the other side of the world. The moment you look at your coin and see heads, you instantly know your friend's coin shows tails — even before they look.\n\n**The quantum twist:**\nHere's where it gets truly strange. With ordinary coins, the outcome was decided the moment you separated them — your coin was \"really\" heads all along. But quantum mechanics tells us something weirder: before you measure them, entangled particles don't have definite properties at all. Each particle exists in a blur of possibilities (called \"superposition\") until the moment of measurement, when it \"chooses\" a state — and its partner instantly matches, no matter the distance.\n\nEinstein hated this, calling it \"spooky action at a distance,\" because it seemed like information was traveling faster than light. Scientists have since confirmed through experiments (winning the 2022 Nobel Prize) that entanglement is real.\n\n**Important caveat:**\nYou can't use entanglement to send messages faster than light. The results you see are random — you only discover the correlation when you compare notes with your friend through ordinary means.\n\n**Why it matters:**\nEntanglement is the engine behind quantum computing, quantum cryptography, and quantum teleportation experiments.\n\n---\n\nThat's pretty good. Let me refine. The coin analogy has the same hidden-variable problem as gloves, but I address it directly, which is the right pedagogical move. Actually I want to make sure the explanation of the twist is clear. \n\nThe key insight: classical correlations (gloves in boxes) are just about our ignorance — the properties existed all along. Quantum entanglement is different because the properties genuinely don't exist until measured, and experiments (Bell tests) have proven this distinction.\n\nShould I mention Bell's theorem explicitly? Maybe briefly — the 2022 Nobel Prize reference (Aspect, Clauser, Zeilinger) is a nice concrete touch that shows this isn't just theory.\n\nLength check: The draft above feels right — comprehensive but not overwhelming. Headers might be helpful here to organize, or I could do flowing prose. For a \"simple terms\" explanation, I think light structure with bold key phrases or minimal headers works well. Actually, maybe I'll keep it more conversational with minimal formatting — a few short paragraphs. Let me think... The request is conversational (\"Explain X in simple terms\"), so a conversational response with maybe one or two bolded phrases for emphasis feels right. Headers might make it feel like a textbook. I'll use flowing paragraphs with clear structure but keep it warm and readable.\n\nLet me finalize:\n\nParagraph 1: What it is — linked particles actin
... response truncated ...
```

## Examples

<details>

<summary>**Reasoning Effort** — Configure reasoning effort for a harder problem (K3's reasoning_effort replaces the K2.x thinking parameter)</summary>



```ts
const response = await env.AI.run(
  'moonshotai/kimi-k3',
  {
    messages: [{ content: 'Prove that the square root of 2 is irrational.', role: 'user' }],
    reasoning_effort: 'max',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "moonshotai/kimi-k3",
  "messages": [
    {
      "content": "Prove that the square root of 2 is irrational.",
      "role": "user"
    }
  ],
  "reasoning_effort": "max"
}'
```

```
# Proof that √2 is irrational

**Theorem.** √2 is irrational.

**Proof.** We proceed by contradiction. Suppose √2 is rational. Then it can be written as a fraction in lowest terms:

$$\sqrt{2} = \frac{a}{b}$$

where $a$ and $b$ are integers, $b \neq 0$, and $\gcd(a, b) = 1$ (meaning $a$ and $b$ share no common factor).

**Step 1: Square both sides.**

$$2 = \frac{a^2}{b^2} \implies a^2 = 2b^2$$

So $a^2$ is even. This forces $a$ itself to be even, because the square of an odd number is odd: if $a = 2k+1$, then $a^2 = 4k^2 + 4k + 1$, which is odd. Hence we can write:

$$a = 2k \quad \text{for some integer } k$$

**Step 2: Substitute back.**

$$(2k)^2 = 2b^2 \implies 4k^2 = 2b^2 \implies b^2 = 2k^2$$

So $b^2$ is even, and by the same reasoning as above, $b$ must be even.

**Step 3: Reach a contradiction.**

We have shown that both $a$ and $b$ are even, so they share a common factor of 2. But this contradicts our assumption that $\gcd(a, b) = 1$.

**Conclusion.** The assumption that √2 is rational leads to a contradiction. Therefore, √2 is irrational. $\blacksquare$

---

**Remark on the key step:** The entire proof hinges on the fact that *every* rational number has a unique fully-reduced form. The equation $a^2 = 2b^2$ is impossible for reduced fractions because the factor 2 appears an even number of times on the left (in the prime factorization of $a^2$) but an odd number of times on the right (in $2b^2$) — this is essentially the contradiction in disguise.
```

```json
{
  "id": "chatcmpl-6a59237a703baa4f421e6187",
  "object": "chat.completion",
  "created": 1784226682,
  "model": "moonshotai/kimi-k3",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "# Proof that √2 is irrational\n\n**Theorem.** √2 is irrational.\n\n**Proof.** We proceed by contradiction. Suppose √2 is rational. Then it can be written as a fraction in lowest terms:\n\n$$\\sqrt{2} = \\frac{a}{b}$$\n\nwhere $a$ and $b$ are integers, $b \\neq 0$, and $\\gcd(a, b) = 1$ (meaning $a$ and $b$ share no common factor).\n\n**Step 1: Square both sides.**\n\n$$2 = \\frac{a^2}{b^2} \\implies a^2 = 2b^2$$\n\nSo $a^2$ is even. This forces $a$ itself to be even, because the square of an odd number is odd: if $a = 2k+1$, then $a^2 = 4k^2 + 4k + 1$, which is odd. Hence we can write:\n\n$$a = 2k \\quad \\text{for some integer } k$$\n\n**Step 2: Substitute back.**\n\n$$(2k)^2 = 2b^2 \\implies 4k^2 = 2b^2 \\implies b^2 = 2k^2$$\n\nSo $b^2$ is even, and by the same reasoning as above, $b$ must be even.\n\n**Step 3: Reach a contradiction.**\n\nWe have shown that both $a$ and $b$ are even, so they share a common factor of 2. But this contradicts our assumption that $\\gcd(a, b) = 1$.\n\n**Conclusion.** The assumption that √2 is rational leads to a contradiction. Therefore, √2 is irrational. $\\blacksquare$\n\n---\n\n**Remark on the key step:** The entire proof hinges on the fact that *every* rational number has a unique fully-reduced form. The equation $a^2 = 2b^2$ is impossible for reduced fractions because the factor 2 appears an even number of times on the left (in the prime factorization of $a^2$) but an odd number of times on the right (in $2b^2$) — this is essentially the contradiction in disguise.",
        "reasoning_content": "The user wants a proof that √2 is irrational. This is a classic proof by contradiction. Let me write it out clearly and rigorously.\n\nThe standard proof:\n\n**Claim:** √2 is irrational.\n\n**Proof (by contradiction):**\n\nSuppose, for the sake of contradiction, that √2 is rational. Then we can write:\n√2 = a/b\n\nwhere a and b are integers with b ≠ 0, and we can assume the fraction is in lowest terms, meaning gcd(a, b) = 1 (a and b share no common factors).\n\nSquaring both sides:\n2 = a²/b²\n2b² = a²\n\nThis means a² is even, which implies a is even (because if a were odd, a² would be odd — the square of an odd number (2k+1)² = 4k² + 4k + 1 = 2(2k² + 2k) + 1 is odd).\n\nSo a = 2k for some integer k.\n\nSubstituting:\n2b² = (2k)² = 4k²\nb² = 2k²\n\nThis means b² is even, which implies b is even (by the same reasoning).\n\nBut now both a and b are even, meaning they share a common factor of 2. This contradicts our assumption that gcd(a, b) = 1 (that the fraction was in lowest terms).\n\nTherefore, our initial assumption that √2 is rational must be false. Hence √2 is irrational. ∎\n\nI should also justify the lemma that if a² is even then a is even. I did that inline above.\n\nLet me format this nicely with clear structure. This is a math proof request, so headers or clear proof structure would be appropriate. I'll use a theorem-proof format. Should be moderately concise but complete and rigorous. I can use some markdown formatting since this appears to be a chat interface where markdown renders.\n\nI'll structure it:\n1. Statement\n2. Proof setup (contradiction)\n3. Key steps\n4. Contradiction\n5. Conclusion\n\nMaybe include the lemma explicitly. Let me write it well."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 96,
    "completion_tokens": 932,
    "total_tokens": 1028,
    "cached_tokens": 96,
    "completion_tokens_details": {
      "reasoning_tokens": 450
    },
    "prompt_tokens_details": {
      "cached_tokens": 96
    }
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Tool Choice Required** — Force a tool call on the first turn with tool_choice</summary>



```ts
const response = await env.AI.run(
  'moonshotai/kimi-k3',
  {
    messages: [{ content: 'What is the weather in San Francisco today?', role: 'user' }],
    tool_choice: 'required',
    tools: [
      {
        function: {
          description: 'Get the weather for a city',
          name: 'get_weather',
          parameters: {
            properties: { city: { type: 'string' } },
            required: ['city'],
            type: 'object',
          },
        },
        type: 'function',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "moonshotai/kimi-k3",
  "messages": [
    {
      "content": "What is the weather in San Francisco today?",
      "role": "user"
    }
  ],
  "tool_choice": "required",
  "tools": [
    {
      "function": {
        "description": "Get the weather for a city",
        "name": "get_weather",
        "parameters": {
          "properties": {
            "city": {
              "type": "string"
            }
          },
          "required": [
            "city"
          ],
          "type": "object"
        }
      },
      "type": "function"
    }
  ]
}'
```

```
I'll check the weather in San Francisco for you.
```

```json
{
  "id": "chatcmpl-6a5923933594b7665d11ae23",
  "object": "chat.completion",
  "created": 1784226696,
  "model": "moonshotai/kimi-k3",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "I'll check the weather in San Francisco for you.",
        "tool_calls": [
          {
            "index": 0,
            "id": "get_weather_0",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\":\"San Francisco\"}"
            }
          }
        ],
        "reasoning_content": "The user is asking about the weather in San Francisco today. I have a `get_weather` tool available. I should call it with the city \"San Francisco\"."
      },
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 208,
    "completion_tokens": 98,
    "total_tokens": 306,
    "cached_tokens": 208,
    "completion_tokens_details": {
      "reasoning_tokens": 35
    },
    "prompt_tokens_details": {
      "cached_tokens": 208
    }
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'moonshotai/kimi-k3',
  { messages: [{ content: 'Explain why the sky is blue.', role: 'user' }], stream: true },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "moonshotai/kimi-k3",
  "messages": [
    {
      "content": "Explain why the sky is blue.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

```
The sky is blue because of a phenomenon called **Rayleigh scattering**, which describes how light interacts with tiny particles—in this case, the gas molecules in Earth's atmosphere.

Here's the process, step by step:

1. **Sunlight contains all colors.** Although it looks white, sunlight is actually a mix of every color of visible light, each with a different wavelength. Red light has long wavelengths (~700 nm), while blue and violet have short ones (~400–450 nm).

2. **Air molecules scatter light.** Nitrogen and oxygen molecules are far smaller than the wavelengths of visible light. When light strikes particles this tiny, it gets scattered in all directions.

3. **Shorter wavelengths scatter much more strongly.** Rayleigh scattering intensity is proportional to 1/λ⁴, meaning blue light is scattered roughly 5–6 times more than red light. As sunlight streams through the atmosphere, blue light gets bounced all over the place—so no matter where you look in the sky, scattered blue light is reaching your eyes.

**Why not violet?** Violet light scatters even more than blue, but the sun emits less of it, and our eyes are less sensitive to it. The combined effect is that we perceive the sky as blue.

**A nice confirmation:** the same physics explains sunsets. When the sun is low on the horizon, its light travels through much more atmosphere to reach you. By the time it arrives, most of the blue has been scattered away, leaving the reds and oranges behind.

As a bonus: on the Moon, which has no atmosphere, the daytime sky is black—there's nothing to scatter the sunlight at all.
```

```json
[
  {
    "id": "chatcmpl-6a59238b8a290065f7c0f652",
    "object": "chat.completion.chunk",
    "created": 1784226700,
    "model": "kimi-k3",
    "choices": [
      {
        "index": 0,
        "delta": {
          "role": "assistant",
          "content": ""
        },
        "finish_reason": null
      }
    ],
    "system_fingerprint": "fpv0_0d4e787e"
  },
  {
    "id": "chatcmpl-6a59238b8a290065f7c0f652",
    "object": "chat.completion.chunk",
    "created": 1784226700,
    "model": "kimi-k3",
    "choices": [
      {
        "index": 0,
        "delta": {
          "reasoning_content": "The"
        },
        "finish_reason": null
      }
    ],
    "system_fingerprint": "fpv0_0d4e787e"
  },
  "... 1315 more chunks omitted ...",
  {
    "id": "chatcmpl-6a59238b8a290065f7c0f652",
    "object": "chat.completion.chunk",
    "created": 1784226700,
    "model": "kimi-k3",
    "choices": [],
    "usage": {
      "prompt_tokens": 92,
      "completion_tokens": 1331,
      "total_tokens": 1423,
      "cached_tokens": 92,
      "completion_tokens_details": {
        "reasoning_tokens": 983
      },
      "prompt_tokens_details": {
        "cached_tokens": 92
      }
    }
  }
]
```

</details>

## Parameters

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/moonshotai/kimi-k3/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/moonshotai/kimi-k3/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/moonshotai/kimi-k3/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/moonshotai/kimi-k3/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/moonshotai/kimi-k3/#page","headline":"Kimi K3","description":"Kimi K3 is Moonshot's flagship 2.8 trillion-parameter model, built on Kimi Delta Attention (a hybrid linear attention mechanism) with Attention Residuals. It offers native visual understanding, always-on reasoning, and a 1M-token context window for long-horizon coding, knowledge work, and deep reasoning tasks.","url":"https://developers.cloudflare.com/ai/models/moonshotai/kimi-k3/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: OpenAI's flagship GPT model for complex tasks with a million-token context window.
title: GPT-4.1
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-4.1

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-4.1/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-4.1`

- Third-party
- Zero data retention

OpenAI's flagship GPT model for complex tasks with a million-token context window.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,047,576 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/index/gpt-4-1/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Output (per 1M tokens)$8.00</li><li>Cached input (per 1M tokens)$0.50</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-4.1',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4.1",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
Certainly! The **three laws of thermodynamics** are fundamental principles describing how energy moves and changes in physical systems:

---

**1. First Law of Thermodynamics (Law of Energy Conservation):**  
*Energy cannot be created or destroyed, only converted from one form to another.*

- In other words, the total energy of an isolated system is constant.
- Mathematically:  
  ΔU = Q − W  
  Where ΔU is the change in internal energy, Q is heat added to the system, and W is work done by the system.

---

**2. Second Law of Thermodynamics (Law of Entropy):**  
*The entropy of an isolated system always increases over time, or remains constant in ideal cases; it never decreases.*

- This law explains why certain processes are irreversible, and why heat flows from hotter to colder bodies naturally.
- It also means that energy transformations are never 100% efficient; some energy is always dispersed as heat.

---

**3. Third Law of Thermodynamics:**  
*As temperature approaches absolute zero (0 K), the entropy of a perfect crystal approaches zero.*

- This suggests it is impossible to reach absolute zero in any finite number of steps.
- At absolute zero, a perfectly ordered crystal would have only one microstate (minimum entropy).

---

**Summary Table:**

| Law        | Main Statement                                             |
|------------|-----------------------------------------------------------|
| First      | Energy is conserved                                       |
| Second     | Entropy increases or remains constant                     |
| Third      | Entropy approaches zero as temperature approaches 0 K     |
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "Certainly! The **three laws of thermodynamics** are fundamental principles describing how energy moves and changes in physical systems:\n\n---\n\n**1. First Law of Thermodynamics (Law of Energy Conservation):**  \n*Energy cannot be created or destroyed, only converted from one form to another.*\n\n- In other words, the total energy of an isolated system is constant.\n- Mathematically:  \n  ΔU = Q − W  \n  Where ΔU is the change in internal energy, Q is heat added to the system, and W is work done by the system.\n\n---\n\n**2. Second Law of Thermodynamics (Law of Entropy):**  \n*The entropy of an isolated system always increases over time, or remains constant in ideal cases; it never decreases.*\n\n- This law explains why certain processes are irreversible, and why heat flows from hotter to colder bodies naturally.\n- It also means that energy transformations are never 100% efficient; some energy is always dispersed as heat.\n\n---\n\n**3. Third Law of Thermodynamics:**  \n*As temperature approaches absolute zero (0 K), the entropy of a perfect crystal approaches zero.*\n\n- This suggests it is impossible to reach absolute zero in any finite number of steps.\n- At absolute zero, a perfectly ordered crystal would have only one microstate (minimum entropy).\n\n---\n\n**Summary Table:**\n\n| Law        | Main Statement                                             |\n|------------|-----------------------------------------------------------|\n| First      | Energy is conserved                                       |\n| Second     | Entropy increases or remains constant                     |\n| Third      | Entropy approaches zero as temperature approaches 0 K     |",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470813,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnUz3cM4bgGfNijU6O2Bjr5zBIE8",
  "model": "gpt-4.1-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_464203d4c6",
  "usage": {
    "completion_tokens": 319,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 16,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 335
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-4.1',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4.1",
  "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"
    }
  ]
}'
```

````
To read a JSON file in Python, you can use the built-in `json` module. Here’s a simple step-by-step example:

### 1. Import the `json` module

```python
import json
```

### 2. Open and read the JSON file

Assuming your JSON file is named `data.json`:

```python
with open('data.json', 'r') as file:
    data = json.load(file)
```

### 3. Now `data` is a Python object (usually a `dict` or `list`)  
You can use `data` just like any other Python dictionary or list.

### Full Example

Assume `data.json` contains:
```json
{
  "name": "Alice",
  "age": 30,
  "city": "Wonderland"
}
```

Python code:
```python
import json

with open('data.json', 'r') as file:
    data = json.load(file)

print(data["name"])  # Output: Alice
print(data["age"])   # Output: 30
```

---

**Recap:**  
- Use `import json`.
- Use `with open(filename) as f: data = json.load(f)`
- Now, `data` contains your JSON data as Python objects!
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "To read a JSON file in Python, you can use the built-in `json` module. Here’s a simple step-by-step example:\n\n### 1. Import the `json` module\n\n```python\nimport json\n```\n\n### 2. Open and read the JSON file\n\nAssuming your JSON file is named `data.json`:\n\n```python\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n```\n\n### 3. Now `data` is a Python object (usually a `dict` or `list`)  \nYou can use `data` just like any other Python dictionary or list.\n\n### Full Example\n\nAssume `data.json` contains:\n```json\n{\n  \"name\": \"Alice\",\n  \"age\": 30,\n  \"city\": \"Wonderland\"\n}\n```\n\nPython code:\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data[\"name\"])  # Output: Alice\nprint(data[\"age\"])   # Output: 30\n```\n\n---\n\n**Recap:**  \n- Use `import json`.\n- Use `with open(filename) as f: data = json.load(f)`\n- Now, `data` contains your JSON data as Python objects!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470814,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnV0JChfu6u4m6dzXKPW2Rb0MofH",
  "model": "gpt-4.1-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_7e40a569fc",
  "usage": {
    "completion_tokens": 268,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 31,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 299
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-4.1',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4.1",
  "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"
    }
  ]
}'
```

```
Great! There are two main routes between San Francisco and Los Angeles:

**1. The Scenic Pacific Coast Highway (Highway 1):**  
This is the most beautiful (and slower) option, hugging the coastline with stunning ocean views. Key stops along this route include:

- **Half Moon Bay:** Charming coastal town, great for beaches and breakfast.
- **Santa Cruz:** Fun boardwalk, surf spots, and natural bridges.
- **Monterey:** Monterey Bay Aquarium, Cannery Row, 17-Mile Drive.
- **Carmel-by-the-Sea:** Picturesque town, great art galleries, boutiques, and beaches.
- **Big Sur:** Breathtaking cliffs, Bixby Creek Bridge, McWay Falls, and several state parks for hiking (like Julia Pfeiffer Burns State Park).
- **Hearst Castle (San Simeon):** Grand historic estate you can tour.
- **Cambria & Morro Bay:** Cute small towns, Morro Rock, great seafood.
- **San Luis Obispo:** Lively downtown, Madonna Inn for quirky photos, Mission San Luis Obispo.
- **Pismo Beach:** Famous for its dunes and clam chowder.
- **Santa Barbara:** Gorgeous beaches, Spanish architecture, great lunch stop, wine tasting.
- **Malibu:** Beautiful beaches and coastal views just before you reach LA.

*Tip: This route is best enjoyed over 2-3 days, but you can do portions if you’re on a tighter schedule.*

---

**2. The Fast Inland Route (Highway 101 or I-5):**  
Quicker, but less scenic. For quick but worthwhile stops:

- **Gilroy:** Garlic capital, outlet shopping.
- **Paso Robles:** Renowned wineries and adorable downtown.
- **Santa Barbara:** As above, worth a detour if you take Hwy 101.

If you’re on **I-5**, main stops are limited—Harris Ranch is a classic spot for a meal (and cattle viewing), but scenery is mostly farmland.

---

**Let me know:**
- Do you have 1 day or several for the drive?
- What are your interests (scenery, food, wine, beaches, hiking)?
- Traveling solo, as a couple, or with family/kids?

With a bit more info, I can tailor a perfect list for you!
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "Great! There are two main routes between San Francisco and Los Angeles:\n\n**1. The Scenic Pacific Coast Highway (Highway 1):**  \nThis is the most beautiful (and slower) option, hugging the coastline with stunning ocean views. Key stops along this route include:\n\n- **Half Moon Bay:** Charming coastal town, great for beaches and breakfast.\n- **Santa Cruz:** Fun boardwalk, surf spots, and natural bridges.\n- **Monterey:** Monterey Bay Aquarium, Cannery Row, 17-Mile Drive.\n- **Carmel-by-the-Sea:** Picturesque town, great art galleries, boutiques, and beaches.\n- **Big Sur:** Breathtaking cliffs, Bixby Creek Bridge, McWay Falls, and several state parks for hiking (like Julia Pfeiffer Burns State Park).\n- **Hearst Castle (San Simeon):** Grand historic estate you can tour.\n- **Cambria & Morro Bay:** Cute small towns, Morro Rock, great seafood.\n- **San Luis Obispo:** Lively downtown, Madonna Inn for quirky photos, Mission San Luis Obispo.\n- **Pismo Beach:** Famous for its dunes and clam chowder.\n- **Santa Barbara:** Gorgeous beaches, Spanish architecture, great lunch stop, wine tasting.\n- **Malibu:** Beautiful beaches and coastal views just before you reach LA.\n\n*Tip: This route is best enjoyed over 2-3 days, but you can do portions if you’re on a tighter schedule.*\n\n---\n\n**2. The Fast Inland Route (Highway 101 or I-5):**  \nQuicker, but less scenic. For quick but worthwhile stops:\n\n- **Gilroy:** Garlic capital, outlet shopping.\n- **Paso Robles:** Renowned wineries and adorable downtown.\n- **Santa Barbara:** As above, worth a detour if you take Hwy 101.\n\nIf you’re on **I-5**, main stops are limited—Harris Ranch is a classic spot for a meal (and cattle viewing), but scenery is mostly farmland.\n\n---\n\n**Let me know:**\n- Do you have 1 day or several for the drive?\n- What are your interests (scenery, food, wine, beaches, hiking)?\n- Traveling solo, as a couple, or with family/kids?\n\nWith a bit more info, I can tailor a perfect list for you!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470817,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnV37uMPRNbZz6wc0f1dEO7gTp17",
  "model": "gpt-4.1-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_3fcf29cddc",
  "usage": {
    "completion_tokens": 481,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 75,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 556
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-4.1',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4.1",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
Detective Lila Maren knelt beside the wrought-iron fence, her breath misting in the pale dawn light. The alley was quiet, save for the distant hum of the city waking. She scanned the scuffed cobblestones, expecting the usual—a cigarette butt, perhaps, or a scrap of torn fabric. Instead, nestled in a shallow puddle, she found a single red chess pawn, oddly pristine amid the grime.

Lila lifted it with gloved fingers, turning it over as she studied its glossy sheen. No markings. No blood. Just a chess piece, out of place and glinting like a secret. She frowned, recalling the message scrawled on the victim’s mirror upstairs: “Checkmate.” The game, it seemed, was just beginning.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "Detective Lila Maren knelt beside the wrought-iron fence, her breath misting in the pale dawn light. The alley was quiet, save for the distant hum of the city waking. She scanned the scuffed cobblestones, expecting the usual—a cigarette butt, perhaps, or a scrap of torn fabric. Instead, nestled in a shallow puddle, she found a single red chess pawn, oddly pristine amid the grime.\n\nLila lifted it with gloved fingers, turning it over as she studied its glossy sheen. No markings. No blood. Just a chess piece, out of place and glinting like a secret. She frowned, recalling the message scrawled on the victim’s mirror upstairs: “Checkmate.” The game, it seemed, was just beginning.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470819,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnV5b5ltpItctts03EY2jcCCWLEe",
  "model": "gpt-4.1-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_7a56a8eabf",
  "usage": {
    "completion_tokens": 159,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 20,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 179
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-4.1',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4.1",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
**Recursion** is a programming technique where a function calls itself to solve a problem. Each time the function calls itself, it breaks the problem down into smaller subproblems. For recursion to stop, a **base case** (or termination condition) is required.

**Simple Example: Calculating Factorial**

The **factorial** of a non-negative integer `n` (written as `n!`) is the product of all positive integers less than or equal to `n`.

**Mathematically:**
- `n! = n × (n-1) × (n-2) × ... × 1`
- By definition, `0! = 1`

**Recursive Definition:**
- If `n == 0`, then `factorial(n) = 1`   (base case)
- If `n > 0`, then `factorial(n) = n × factorial(n-1)`  (recursive case)

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

**How it works:**
To compute `factorial(4)`:
- `factorial(4)` returns `4 * factorial(3)`
- `factorial(3)` returns `3 * factorial(2)`
- `factorial(2)` returns `2 * factorial(1)`
- `factorial(1)` returns `1 * factorial(0)`
- `factorial(0)` returns `1` (base case)

So,
- `factorial(1)` = 1 × 1 = 1
- `factorial(2)` = 2 × 1 = 2
- `factorial(3)` = 3 × 2 = 6
- `factorial(4)` = 4 × 6 = 24

**In summary:**  
Recursion is when a function calls itself, and the problem gets divided into smaller parts until reaching a simple, solvable case (the base case).
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1776470822,
    "id": "chatcmpl-DVnV8rG1ILDUR9r3HsKDVd4dbGH0A",
    "model": "gpt-4.1-2025-04-14",
    "obfuscation": "nqlUcqwR28bhP",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_51f6d1255b",
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "**"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1776470822,
    "id": "chatcmpl-DVnV8rG1ILDUR9r3HsKDVd4dbGH0A",
    "model": "gpt-4.1-2025-04-14",
    "obfuscation": "F8I8qrGpbmKbK",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_51f6d1255b",
    "usage": null
  },
  "... 440 more chunks omitted ...",
  {
    "choices": [],
    "created": 1776470822,
    "id": "chatcmpl-DVnV8rG1ILDUR9r3HsKDVd4dbGH0A",
    "model": "gpt-4.1-2025-04-14",
    "obfuscation": "qHFF5gBP2hPp",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_51f6d1255b",
    "usage": {
      "completion_tokens": 440,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 17,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 457
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-4.1',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4.1",
  "input": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
  "max_output_tokens": 4096,
  "tools": [
    {
      "type": "web_search_preview"
    }
  ]
}'
```

```
Here are the top news stories about Cloudflare this week:

- **Launch of New Partner Initiative for AI and SASE Adoption**: Cloudflare introduced the Cloudflare One Design Partner designation and an AI-powered toolkit to accelerate the adoption of artificial intelligence (AI) and secure access service edge (SASE) architectures. This initiative aims to help organizations modernize legacy security infrastructures and overcome challenges like configuration risks and lengthy deployment times. ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))

- **Completion of Agent Infrastructure Stack with Browser Run Rebuild**: Cloudflare completed its agent infrastructure stack by rebuilding Browser Run on its own Containers platform. This upgrade delivers higher concurrency, faster response times, and support for WebGL and WebMCP, enhancing the performance and scalability of AI agents. ([infoq.com](https://www.infoq.com/news/2026/05/cloudflare-agent-platform-stack/?utm_source=openai))

- **Workforce Reduction Amid AI Adoption**: Cloudflare announced plans to reduce its global workforce by about 20%, cutting more than 1,100 jobs. This restructuring is part of the company's shift towards an AI-first operating model, reflecting the rapid adoption of AI tools and the resulting changes in operational processes. ([business-standard.com](https://www.business-standard.com/technology/tech-news/cloudflare-to-cut-about-20-workforce-as-ai-adoption-reshapes-operations-126050800117_1.html?utm_source=openai))
```

```json
{
  "id": "resp_0fdf05943aa0606d016a398f3d52b48198b359c259da57fcf2",
  "object": "response",
  "created_at": 1782157117,
  "model": "gpt-4.1-2025-04-14",
  "output": [
    {
      "id": "ws_0fdf05943aa0606d016a398f3db07c8198a82f9fb39e0ca765",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare top news stories this week"
        ],
        "query": "Cloudflare top news stories this week"
      }
    },
    {
      "id": "msg_0fdf05943aa0606d016a398f3f38808198be80ca5b78103aaf",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 658,
              "start_index": 494,
              "title": "Cloudflare launches new partner initiative to support AI and SASE adoption",
              "url": "https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 1098,
              "start_index": 998,
              "title": "Cloudflare Completes Its Agent Infrastructure Stack with Browser Run Rebuild and Six-Layer Platform - InfoQ",
              "url": "https://www.infoq.com/news/2026/05/cloudflare-agent-platform-stack/?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 1618,
              "start_index": 1427,
              "title": "Cloudflare to cut about 20% workforce as AI adoption reshapes operations | Tech News - Business Standard",
              "url": "https://www.business-standard.com/technology/tech-news/cloudflare-to-cut-about-20-workforce-as-ai-adoption-reshapes-operations-126050800117_1.html?utm_source=openai"
            }
          ],
          "logprobs": [],
          "text": "Here are the top news stories about Cloudflare this week:\n\n- **Launch of New Partner Initiative for AI and SASE Adoption**: Cloudflare introduced the Cloudflare One Design Partner designation and an AI-powered toolkit to accelerate the adoption of artificial intelligence (AI) and secure access service edge (SASE) architectures. This initiative aims to help organizations modernize legacy security infrastructures and overcome challenges like configuration risks and lengthy deployment times. ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))\n\n- **Completion of Agent Infrastructure Stack with Browser Run Rebuild**: Cloudflare completed its agent infrastructure stack by rebuilding Browser Run on its own Containers platform. This upgrade delivers higher concurrency, faster response times, and support for WebGL and WebMCP, enhancing the performance and scalability of AI agents. ([infoq.com](https://www.infoq.com/news/2026/05/cloudflare-agent-platform-stack/?utm_source=openai))\n\n- **Workforce Reduction Amid AI Adoption**: Cloudflare announced plans to reduce its global workforce by about 20%, cutting more than 1,100 jobs. This restructuring is part of the company's shift towards an AI-first operating model, reflecting the rapid adoption of AI tools and the resulting changes in operational processes. ([business-standard.com](https://www.business-standard.com/technology/tech-news/cloudflare-to-cut-about-20-workforce-as-ai-adoption-reshapes-operations-126050800117_1.html?utm_source=openai)) "
        }
      ],
      "role": "assistant"
    }
  ],
  "status": "completed",
  "usage": {
    "input_tokens": 320,
    "output_tokens": 343,
    "total_tokens": 663,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 0
    }
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1782157123,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 4096,
  "max_tool_calls": null,
  "moderation": null,
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": null,
    "effort": null,
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "web_search_preview",
      "search_content_types": [
        "text"
      ],
      "search_context_size": "medium",
      "user_location": {
        "type": "approximate",
        "city": null,
        "country": "US",
        "region": null,
        "timezone": null
      }
    }
  ],
  "top_logprobs": 0,
  "top_p": 1,
  "truncation": "disabled",
  "user": null,
  "metadata": {},
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4.1/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4.1/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4.1/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4.1/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-4.1/#page","headline":"GPT-4.1","description":"OpenAI's flagship GPT model for complex tasks with a million-token context window.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-4.1/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Fast, affordable version of GPT-4.1 with a million-token context window.
title: GPT-4.1 mini
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-4.1 mini

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-mini/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-4.1-mini`

- Third-party
- Zero data retention

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

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,047,576 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/index/gpt-4-1/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.40</li><li>Output (per 1M tokens)$1.60</li><li>Cached input (per 1M tokens)$0.10</li></ul> |

## Usage

```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4.1-mini",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

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

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "The three laws of thermodynamics are fundamental principles that describe how energy behaves in physical systems:\n\n1. **First Law of Thermodynamics (Law of Energy Conservation):**  \n   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:  \n   \\[\n   \\Delta U = Q - W\n   \\]  \n   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.\n\n2. **Second Law of Thermodynamics:**  \n   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).  \n\n3. **Third Law of Thermodynamics:**  \n   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.\n\nIf you need, I can also explain the Zeroth Law, which is foundational and often included when discussing thermodynamics.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470803,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnUpsMw42Gxv3Iebj1PqAKL5ggSz",
  "model": "gpt-4.1-mini-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_283a574ac4",
  "usage": {
    "completion_tokens": 297,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 16,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 313
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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"
    }
  ]
}'
```

````
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!
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "To read a JSON file in Python, you can use the built-in `json` module. Here's a simple example:\n\n```python\nimport json\n\n# Open the JSON file\nwith open('data.json', 'r') as file:\n    # Load the content of the file into a Python dictionary\n    data = json.load(file)\n\n# Now you can use `data` like a regular Python dictionary\nprint(data)\n```\n\n### Explanation:\n- `open('data.json', 'r')` opens the file in read mode.\n- `json.load(file)` reads the JSON content from the file and converts it into a Python dictionary (or list, depending on the JSON structure).\n\nMake sure your JSON file is properly formatted. If you want to handle errors, you can add a try-except block as well.\n\nLet me know if you need help with that!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470805,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnUrjszaGgaXrIiPHLa9h9MNQaG7",
  "model": "gpt-4.1-mini-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_126f34fc80",
  "usage": {
    "completion_tokens": 175,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 31,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 206
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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"
    }
  ]
}'
```

```
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?
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "Great! Here are some popular and scenic stops along the drive from San Francisco to Los Angeles:\n\n1. **Half Moon Bay** – Just south of San Francisco, it’s a charming coastal town with beautiful beaches and great spots for breakfast or coffee.\n2. **Santa Cruz** – Known for its classic boardwalk, beach vibes, and surfing culture.\n3. **Monterey** – Famous for the Monterey Bay Aquarium, Cannery Row, and stunning coastal views.\n4. **Carmel-by-the-Sea** – A picturesque town with art galleries, boutique shops, and beautiful beaches.\n5. **Big Sur** – One of the most scenic stretches of the California coast with dramatic cliffs, waterfalls (like McWay Falls), and state parks.\n6. **San Simeon** – Home to Hearst Castle, a historic mansion worth touring.\n7. **Pismo Beach** – Great for a beach break, known for its dunes and laid-back atmosphere.\n8. **Santa Barbara** – Often called the “American Riviera” for its Mediterranean climate, with beaches, shopping, and wine tasting.\n\nWould you like recommendations for dining, accommodations, or activities at any of these stops?",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470807,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnUta0ufWlsHWkhAX7ObzcLxe4ys",
  "model": "gpt-4.1-mini-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_babb1d6bc3",
  "usage": {
    "completion_tokens": 241,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 75,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 316
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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"
    }
  ]
}'
```

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

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "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.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470808,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnUuEMVdui5BtdTVUHhhb3cMeSoB",
  "model": "gpt-4.1-mini-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_babb1d6bc3",
  "usage": {
    "completion_tokens": 119,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 20,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 139
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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
  }
}'
```

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

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1776470810,
    "id": "chatcmpl-DVnUwt8ma1xhCsCHYkhjGk6BAkCs1",
    "model": "gpt-4.1-mini-2025-04-14",
    "obfuscation": "lu0xYRXB",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_75f84a798a",
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1776470810,
    "id": "chatcmpl-DVnUwt8ma1xhCsCHYkhjGk6BAkCs1",
    "model": "gpt-4.1-mini-2025-04-14",
    "obfuscation": "hlVju78",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_75f84a798a",
    "usage": null
  },
  "... 322 more chunks omitted ...",
  {
    "choices": [],
    "created": 1776470810,
    "id": "chatcmpl-DVnUwt8ma1xhCsCHYkhjGk6BAkCs1",
    "model": "gpt-4.1-mini-2025-04-14",
    "obfuscation": "F5smuxC",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_75f84a798a",
    "usage": {
      "completion_tokens": 322,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 17,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 339
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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"
    }
  ]
}'
```

```
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))
```

```json
{
  "id": "resp_0cab0a66e314d8de016a398f5f89108199976c9781f9d62782",
  "object": "response",
  "created_at": 1782157151,
  "model": "gpt-4.1-mini-2025-04-14",
  "output": [
    {
      "id": "ws_0cab0a66e314d8de016a398f607314819994386a4692610288",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news April 2024"
        ],
        "query": "Cloudflare news April 2024"
      }
    },
    {
      "id": "msg_0cab0a66e314d8de016a398f6195c08199b60676eda470d4ad",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 862,
              "start_index": 671,
              "title": "Cloudflare launches partner program for SASE and AI security deployment",
              "url": "https://www.streetinsider.com/Corporate%2BNews/Cloudflare%2Blaunches%2Bpartner%2Bprogram%2Bfor%2BSASE%2Band%2BAI%2Bsecurity%2Bdeployment/26657730.html?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 1510,
              "start_index": 1347,
              "title": "Cloudflare (NET) Expands AI Security With Ping Identity Partnership At The Edge - Simply Wall St News",
              "url": "https://simplywall.st/stocks/us/software/nyse-net/cloudflare/news/cloudflare-net-expands-ai-security-with-ping-identity-partne?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 2083,
              "start_index": 1970,
              "title": "Cloudflare Network Disruption Triggers Widespread Internet Outages",
              "url": "https://www.harianbasis.co/en/cloudflare-network-disruption-internet-outage?utm_source=openai"
            }
          ],
          "logprobs": [],
          "text": "Here are the top news stories about Cloudflare from June 15 to June 22, 2026:\n\n- **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))\n\n- **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))\n\n- **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)) "
        }
      ],
      "role": "assistant"
    }
  ],
  "status": "completed",
  "usage": {
    "input_tokens": 320,
    "output_tokens": 477,
    "total_tokens": 797,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 0
    }
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1782157156,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 4096,
  "max_tool_calls": null,
  "moderation": null,
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": null,
    "effort": null,
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "web_search_preview",
      "search_content_types": [
        "text"
      ],
      "search_context_size": "medium",
      "user_location": {
        "type": "approximate",
        "city": null,
        "country": "US",
        "region": null,
        "timezone": null
      }
    }
  ],
  "top_logprobs": 0,
  "top_p": 1,
  "truncation": "disabled",
  "user": null,
  "metadata": {},
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-mini/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-mini/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-mini/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-mini/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-4.1-mini/#page","headline":"GPT-4.1 mini","description":"Fast, affordable version of GPT-4.1 with a million-token context window.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-4.1-mini/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-4.1 Nano is OpenAI’s smallest and cheapest GPT-4.1 variant, optimized for high-throughput, low-latency tasks.
title: GPT-4.1 nano
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-4.1 nano

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-nano/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-4.1-nano`

- Third-party
- Zero data retention

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

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.10</li><li>Output (per 1M tokens)$0.40</li><li>Cached input (per 1M tokens)$0.025</li></ul> |

## Usage

```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4.1-nano",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

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

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "The three laws of thermodynamics are fundamental principles that describe the behavior of energy and temperature in physical systems:\n\n1. **First Law of Thermodynamics (Law of Energy Conservation):**  \n   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.  \n   Mathematically:  \n   \\[\n   \\Delta U = Q - W\n   \\]\n\n2. **Second Law of Thermodynamics:**  \n   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.\n\n3. **Third Law of Thermodynamics:**  \n   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.\n\nThese laws form the foundation of thermodynamics and are essential in understanding energy systems, engines, refrigerators, and many other physical phenomena.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777320190,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMScK7GU5VKq3YMOIJvLRfotOhnW",
  "model": "gpt-4.1-nano-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_8fc5e9a3e3",
  "usage": {
    "completion_tokens": 252,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 16,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 268
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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"
    }
  ]
}'
```

````
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?
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "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:\n\n1. Import the `json` module.\n2. Open the JSON file using `open()`.\n3. Use `json.load()` to parse the data from the file into a Python data structure (usually a dictionary or list).\n\nHere's an example:\n\n```python\nimport json\n\n# Specify the path to your JSON file\nfile_path = 'data.json'\n\n# Open the file and load the JSON data\nwith open(file_path, 'r') as file:\n    data = json.load(file)\n\n# Now you can work with 'data' as a Python dictionary or list\nprint(data)\n```\n\n### Notes:\n- Make sure the JSON file exists at the specified location.\n- If the JSON data is in string format rather than a file, you can use `json.loads()` instead.\n- Always handle potential exceptions (like `FileNotFoundError` or `json.JSONDecodeError`) when working with files and JSON data.\n\nWould you like an example with error handling or working with JSON data in a string?",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777320192,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMSexsEYr8aaW33Xyn2IaPnygnY5",
  "model": "gpt-4.1-nano-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_1bedc25778",
  "usage": {
    "completion_tokens": 238,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 31,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 269
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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"
    }
  ]
}'
```

```
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?
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "Great! Here are some interesting stops along the San Francisco to Los Angeles route, mainly along the iconic Highway 1 and scenic coastal areas:\n\n1. **Santa Cruz**  \n   - Enjoy the beaches, surf culture, and the famous Santa Cruz Beach Boardwalk amusement park.\n\n2. **Monterey & Carmel-by-the-Sea**  \n   - Monterey: Visit the Monterey Bay Aquarium and Cannery Row.  \n   - Carmel: Stroll through charming streets, galleries, and enjoy the stunning coastal views.\n\n3. **Big Sur**  \n   - One of the most breathtaking parts of California's coast.  \n   - Stop at Pfeiffer Beach, Bixby Creek Bridge, McWay Falls, and Julia Pfeiffer Burns State Park.\n\n4. **San Simeon**  \n   - Tour Hearst Castle, a magnificent historic estate with stunning architecture and gardens.\n\n5. **Cambria or Morro Bay**  \n   - Enjoy small-town charm, local shops, and coastal scenery.\n\n6. **Elephant Seal Rookery at Piedras Blancas**  \n   - See seals along the coast (near San Simeon).\n\n7. **Santa Barbara**  \n   - Often called the \"American Riviera,\" it's known for beautiful beaches, Spanish-style architecture, and lively downtown.\n\n8. **Malibu**  \n   - Famous for its beaches and celebrity homes. Consider a quick stop at Zuma Beach or Malibu Pier.\n\nIf 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.\n\nWould you like a suggested itinerary or specific activity recommendations at any of these stops?",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777320194,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMSggejH8U1yMFzW7Ibn1J2xL8xx",
  "model": "gpt-4.1-nano-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_8fc5e9a3e3",
  "usage": {
    "completion_tokens": 341,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 75,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 416
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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"
    }
  ]
}'
```

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

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "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.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777320194,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMSg3VYyqTPmNOmWnu1UqurYsxlI",
  "model": "gpt-4.1-nano-2025-04-14",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_04a6e55762",
  "usage": {
    "completion_tokens": 117,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 20,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 137
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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
  }
}'
```

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

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1777320196,
    "id": "chatcmpl-DZMSi0LW1G5hMlCi690nyLIRbQopZ",
    "model": "gpt-4.1-nano-2025-04-14",
    "obfuscation": "Iw5l2php",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_04a6e55762",
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1777320196,
    "id": "chatcmpl-DZMSi0LW1G5hMlCi690nyLIRbQopZ",
    "model": "gpt-4.1-nano-2025-04-14",
    "obfuscation": "dCJPqHY",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_04a6e55762",
    "usage": null
  },
  "... 337 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777320196,
    "id": "chatcmpl-DZMSi0LW1G5hMlCi690nyLIRbQopZ",
    "model": "gpt-4.1-nano-2025-04-14",
    "obfuscation": "tNgMbOK",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_04a6e55762",
    "usage": {
      "completion_tokens": 337,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 17,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 354
    }
  }
]
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-nano/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-nano/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-nano/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4.1-nano/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-4.1-nano/#page","headline":"GPT-4.1 nano","description":"GPT-4.1 Nano is OpenAI’s smallest and cheapest GPT-4.1 variant, optimized for high-throughput, low-latency tasks.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-4.1-nano/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-4o is OpenAI’s multimodal flagship, accepting text and images and responding quickly across a wide range of tasks.
title: GPT-4o
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-4o

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-4o/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-4o`

- Third-party
- Zero data retention

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

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 128,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$1.25</li><li>Output (per 1M tokens)$5.00</li><li>Cached input (per 1M tokens)$0.625</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-4o',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4o",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

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

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "The three laws of thermodynamics are fundamental principles that describe the behavior of energy and matter in a system. They are:\n\n1. **The First Law of Thermodynamics (Law of Energy Conservation):**\n   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:\n   \\[\n   \\Delta U = Q - W\n   \\]\n   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.\n\n2. **The Second Law of Thermodynamics:**\n   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.\n\n3. **The Third Law of Thermodynamics:**\n   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.\n\nThese three laws describe the fundamental behavior of energy transformations and form the groundwork for understanding thermodynamic processes.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319820,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMegPcIzmJH5Nn9qiWIzdRJqlSB",
  "model": "gpt-4o-2024-08-06",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_b0de34c6fc",
  "usage": {
    "completion_tokens": 360,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 16,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 376
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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"
    }
  ]
}'
```

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

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "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:\n\n1. **Import the `json` module**: To work with JSON data, you need to import this module.\n\n2. **Open the JSON file**: Use the built-in `open()` function to open the file in read mode.\n\n3. **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).\n\nHere is a simple example demonstrating these steps:\n\n```python\nimport json\n\n# Specify the path to your JSON file\nfile_path = 'data.json'\n\n# Open the file and load the JSON data\nwith open(file_path, 'r') as file:\n    data = json.load(file)\n\n# Now `data` is a Python dictionary (or list, depending on the structure of your JSON file)\nprint(data)\n```\n\n### Key Points:\n\n- **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.\n  \n  ```python\n  import json\n\n  file_path = 'data.json'\n\n  try:\n      with open(file_path, 'r') as file:\n          data = json.load(file)\n  except FileNotFoundError:\n      print(f\"Error: The file {file_path} does not exist.\")\n  except json.JSONDecodeError:\n      print(\"Error: The file contains invalid JSON.\")\n  else:\n      print(data)\n  ```\n\n- **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.\n\nUsing this method, you can easily read and work with JSON data in your Python projects.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319825,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMjoI33nq3RWgWVcBbUEFhj8zgI",
  "model": "gpt-4o-2024-08-06",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_025fc0f80f",
  "usage": {
    "completion_tokens": 416,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 31,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 447
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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"
    }
  ]
}'
```

```
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!
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "A road trip from San Francisco to Los Angeles offers many scenic and interesting stops. Here are some popular ones:\n\n1. **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.\n\n2. **Santa Cruz**: Known for its boardwalk and beaches, Santa Cruz also has charming downtown shops and eateries.\n\n3. **Monterey**: Visit the famous Monterey Bay Aquarium or take a scenic drive along the 17-Mile Drive through Pebble Beach.\n\n4. **Carmel-by-the-Sea**: This picturesque town is perfect for a stroll through art galleries, shops, and beautiful beaches.\n\n5. **Big Sur**: Enjoy dramatic coastal views on Highway 1. Stops include Bixby Creek Bridge, McWay Falls, and Pfeiffer Beach.\n\n6. **San Luis Obispo**: Known for its charming downtown and the quirky Bubblegum Alley. You can also visit nearby Pismo Beach or Avila Beach.\n\n7. **Solvang**: A small Danish-style town that offers unique architecture, bakeries, and shops.\n\n8. **Santa Barbara**: Known as the \"American Riviera,\" this city offers beautiful beaches, a bustling downtown, and the iconic Santa Barbara Mission.\n\n9. **Malibu**: Stop by for some of the most famous beaches like Zuma Beach or enjoy oceanfront dining.\n\nThese 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!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319826,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMk2DS6zoHQlMok2F1yWsewGVJc",
  "model": "gpt-4o-2024-08-06",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_6dd86a7be3",
  "usage": {
    "completion_tokens": 331,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 75,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 406
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4o",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

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

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "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.\n\nThe 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.\n\nHer 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.\n\nInside 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.\n\nThis 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.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319830,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMo1EfktQBREr7zAR2RCWKFjLlD",
  "model": "gpt-4o-2024-08-06",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_8637f949d3",
  "usage": {
    "completion_tokens": 399,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 20,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 419
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4o",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

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

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1777319831,
    "id": "chatcmpl-DZMMpD11GwQsD27xo2aEnxkId8PGM",
    "model": "gpt-4o-2024-08-06",
    "obfuscation": "BfwwVsWIvF4uTQ",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_6dd86a7be3",
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1777319831,
    "id": "chatcmpl-DZMMpD11GwQsD27xo2aEnxkId8PGM",
    "model": "gpt-4o-2024-08-06",
    "obfuscation": "CK2cVlJRUSY0t",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_6dd86a7be3",
    "usage": null
  },
  "... 339 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777319831,
    "id": "chatcmpl-DZMMpD11GwQsD27xo2aEnxkId8PGM",
    "model": "gpt-4o-2024-08-06",
    "obfuscation": "zYJbbJ6sJN0JV",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_6dd86a7be3",
    "usage": {
      "completion_tokens": 339,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 17,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 356
    }
  }
]
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4o/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4o/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4o/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4o/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-4o/#page","headline":"GPT-4o","description":"GPT-4o is OpenAI’s multimodal flagship, accepting text and images and responding quickly across a wide range of tasks.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-4o/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-4o Mini is the lightweight, low-cost variant of GPT-4o, well suited to high-volume tasks with multimodal inputs.
title: GPT-4o mini
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-4o mini

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-4o-mini/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-4o-mini`

- Third-party
- Zero data retention

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

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 128,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.075</li><li>Output (per 1M tokens)$0.30</li><li>Cached input (per 1M tokens)$0.0375</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-4o-mini',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4o-mini",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

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

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "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:\n\n1. **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.\n\n2. **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:\n   \\[\n   \\Delta U = Q - W\n   \\]\n   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.\n\n3. **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.\n\n4. **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.\n\nThese laws are foundational to the study of physics and chemistry, affecting various fields, including engineering, biology, and materials science.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319548,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMIGfjLc8l4VDEpWs4s7mSFBSVSy",
  "model": "gpt-4o-mini-2024-07-18",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_3d695acdac",
  "usage": {
    "completion_tokens": 382,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 16,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 398
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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"
    }
  ]
}'
```

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

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "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:\n\n1. **Import the `json` module**: This module allows you to work with JSON data easily.\n2. **Open the JSON file**: Use Python's built-in `open()` function to access the file.\n3. **Load the JSON data**: Use the `json.load()` function to parse the JSON data in the file.\n\nHere is a simple example:\n\n### Example: Reading a JSON file\n\nAssuming you have a JSON file named `data.json` with the following content:\n\n```json\n{\n    \"name\": \"John\",\n    \"age\": 30,\n    \"city\": \"New York\"\n}\n```\n\nHere is how you can read this JSON file in Python:\n\n```python\nimport json\n\n# Open the JSON file for reading\nwith open('data.json', 'r') as file:\n    # Load the JSON data from the file\n    data = json.load(file)\n\n# Now you can access the data\nprint(data)  # This will print the contents of the JSON file as a dictionary\nprint(data['name'])  # Outputs: John\nprint(data['age'])   # Outputs: 30\nprint(data['city'])  # Outputs: New York\n```\n\n### Explanation:\n- 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.\n- The `json.load(file)` function reads the JSON data and converts it into a Python dictionary.\n- You can then access the data using the dictionary syntax.\n\n### Additional Notes:\n- If you have a JSON string instead of a file, you can use `json.loads()` instead.\n- Handle exceptions using `try-except` blocks if you want to manage errors, such as when a file does not exist or contains invalid JSON.\n\nThis method is simple and efficient for reading JSON data in Python.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319552,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMIKpzH6Ql5Lv3sgRPyY48bdKmlB",
  "model": "gpt-4o-mini-2024-07-18",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_e2f9fd5023",
  "usage": {
    "completion_tokens": 432,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 31,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 463
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "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"
    }
  ]
}'
```

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

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "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:\n\n### 1. **Half Moon Bay**\n   - **Distance from San Francisco:** ~30 minutes\n   - **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.\n\n### 2. **Santa Cruz**\n   - **Distance from San Francisco:** ~1.5 hours\n   - **Highlights:** Visit the Santa Cruz Beach Boardwalk, explore the redwood forests in Henry Cowell Redwoods State Park, or take a stroll along the coastline.\n\n### 3. **Monterey**\n   - **Distance from Santa Cruz:** ~45 minutes\n   - **Highlights:** Monterey Bay Aquarium, Cannery Row, and beautiful coastal views. A must-see is the 17-Mile Drive through Pebble Beach.\n\n### 4. **Carmel-by-the-Sea**\n   - **Distance from Monterey:** ~15 minutes\n   - **Highlights:** A picturesque town known for its art galleries, boutique shops, and stunning beach. Don't miss the chance to explore Carmel Mission Basilica.\n\n### 5. **Big Sur**\n   - **Distance from Carmel:** ~30 minutes\n   - **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.\n\n### 6. **San Luis Obispo**\n   - **Distance from Big Sur:** ~2 hours\n   - **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.\n\n### 7. **Pismo Beach**\n   - **Distance from San Luis Obispo:** ~15 minutes\n   - **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.\n\n### 8. **Santa Barbara**\n   - **Distance from Pismo Beach:** ~1 hour\n   - **Highlights:** Gorgeous Mediterranean-style architecture, beautiful beaches, and wine country nearby. Visit State Street, the Santa Barbara Mission, and the Santa Barbara Botanic Garden.\n\n### 9. **Malibu**\n   - **Distance from Santa Barbara:** ~1.5 hours\n   - **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.\n\n### 10. **Los Angeles**\n   - **Distance from Malibu:** ~30 minutes\n   - **Final Destination:** Depending on your interests, explore Hollywood, Santa Monica, or any of the numerous attractions the city has to offer.\n\n### Tips:\n- **Timing:** Start your trip early to maximize your time at each stop.\n- **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.\n- **Food:** There are many great eateries along the coast; don’t hesitate to stop for local seafood and cafés.\n- **Overnight Stay:** If you want to break it into two days, consider staying in Monterey or Santa Barbara for a more relaxed pace.\n\nHope this helps you plan an amazing road trip! Let me know if you need more information or specific recommendations.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319556,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMIOnfc6dUu1qvfnFZgI5SPXv4s1",
  "model": "gpt-4o-mini-2024-07-18",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_a7190374f3",
  "usage": {
    "completion_tokens": 737,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 75,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 812
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4o-mini",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
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?
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "annotations": [],
        "content": "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.\n\nShe 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. \n\nFlipping 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.” \n\nIris 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?",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319560,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMISg6vI8hQtXDR8mDZ4ED3dwWUk",
  "model": "gpt-4o-mini-2024-07-18",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_370ba29939",
  "usage": {
    "completion_tokens": 352,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 20,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 372
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4o-mini",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

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

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1777319565,
    "id": "chatcmpl-DZMIXJtgYyfytjeCEUmk1Yhm8o5XO",
    "model": "gpt-4o-mini-2024-07-18",
    "obfuscation": "a9jF6VOdC",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_6042092f77",
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0,
        "logprobs": null
      }
    ],
    "created": 1777319565,
    "id": "chatcmpl-DZMIXJtgYyfytjeCEUmk1Yhm8o5XO",
    "model": "gpt-4o-mini-2024-07-18",
    "obfuscation": "K0QlI2xz",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_6042092f77",
    "usage": null
  },
  "... 485 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777319565,
    "id": "chatcmpl-DZMIXJtgYyfytjeCEUmk1Yhm8o5XO",
    "model": "gpt-4o-mini-2024-07-18",
    "obfuscation": "8alXGeDK",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_6042092f77",
    "usage": {
      "completion_tokens": 485,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 17,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 502
    }
  }
]
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4o-mini/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4o-mini/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4o-mini/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4o-mini/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-4o-mini/#page","headline":"GPT-4o mini","description":"GPT-4o Mini is the lightweight, low-cost variant of GPT-4o, well suited to high-volume tasks with multimodal inputs.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-4o-mini/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: A speech-to-text model that uses GPT-4o to transcribe audio with improved word error rate and better language recognition compared to original Whisper models.
title: GPT-4o Transcribe
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-4o Transcribe

Automatic Speech Recognition • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-4o-transcribe/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-4o-transcribe`

- Third-party
- Zero data retention

A speech-to-text model that uses GPT-4o to transcribe audio with improved word error rate and better language recognition compared to original Whisper models.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per audio minute$0.006</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-4o-transcribe',
  { file: 'data:audio/wav;base64,<...>' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4o-transcribe",
  "input": {
    "file": "data:audio/wav;base64,<...>"
  }
}'
```

```
Hello
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "text": "Hello"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**With Language Hint** — Transcribe with a language hint for better accuracy</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-4o-transcribe',
  { file: 'data:audio/wav;base64,<...>', language: 'en' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4o-transcribe",
  "input": {
    "file": "data:audio/wav;base64,<...>",
    "language": "en"
  }
}'
```

```
Hello
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "text": "Hello"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Guided Transcription** — Use a prompt to guide transcription style and context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-4o-transcribe',
  {
    file: 'data:audio/wav;base64,<...>',
    prompt: 'This is a technical discussion about Kubernetes and cloud-native architecture.',
    language: 'en',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4o-transcribe",
  "input": {
    "file": "data:audio/wav;base64,<...>",
    "prompt": "This is a technical discussion about Kubernetes and cloud-native architecture.",
    "language": "en"
  }
}'
```

```
This is a technical discussion about Kubernetes and cloud-native architecture.
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "text": "This is a technical discussion about Kubernetes and cloud-native architecture."
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**High Temperature** — Higher temperature for more varied transcription</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-4o-transcribe',
  { file: 'data:audio/wav;base64,<...>', temperature: 0.5 },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-4o-transcribe",
  "input": {
    "file": "data:audio/wav;base64,<...>",
    "temperature": 0.5
  }
}'
```

```
Hello, world!
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "text": "Hello, world!"
  },
  "state": "Completed"
}
```

</details>

## Parameters

file

`string`requiredThe audio file as a data URI (data:audio/...;base64,...) or HTTPS URL. Supported formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm.

language

`string`The language of the input audio. Supplying the input language in ISO-639-1 format will improve accuracy and latency.

prompt

`string`An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language.

temperature

`number`minimum: 0maximum: 1The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. Defaults to 0 if omitted.

text

`string`The transcribed text.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4o-transcribe/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4o-transcribe/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-4o-transcribe/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-4o-transcribe/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-4o-transcribe/#page","headline":"GPT-4o Transcribe","description":"A speech-to-text model that uses GPT-4o to transcribe audio with improved word error rate and better language recognition compared to original Whisper models.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-4o-transcribe/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: OpenAI's model excelling at coding, writing, and reasoning.
title: GPT-5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5`

- Third-party
- Zero data retention

OpenAI's model excelling at coding, writing, and reasoning.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 128,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$1.25</li><li>Output (per 1M tokens)$10.00</li><li>Cached input (per 1M tokens)$0.125</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
- First law (energy conservation): The change in a system’s internal energy equals the heat added to the system minus the work done by the system. In symbols: ΔU = Q − W (with W defined as work done by the system).

- Second law (entropy increase): In any real process, the total entropy of an isolated system never decreases (ΔS ≥ 0). Equivalently, heat flows spontaneously from hot to cold and no heat engine can be 100% efficient.

- Third law (absolute zero/entropy): As temperature approaches 0 K, the entropy of a perfect crystalline substance approaches zero, and absolute zero cannot be reached in a finite number of steps.

Note: There is also a “zeroth law,” which defines temperature via thermal equilibrium.
```

```json
{
  "id": "chatcmpl-DpLAeLKqEscvTBF6Cy8PzvroAyj7Q",
  "object": "chat.completion",
  "created": 1781128480,
  "model": "gpt-5-2025-08-07",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "- First law (energy conservation): The change in a system’s internal energy equals the heat added to the system minus the work done by the system. In symbols: ΔU = Q − W (with W defined as work done by the system).\n\n- Second law (entropy increase): In any real process, the total entropy of an isolated system never decreases (ΔS ≥ 0). Equivalently, heat flows spontaneously from hot to cold and no heat engine can be 100% efficient.\n\n- Third law (absolute zero/entropy): As temperature approaches 0 K, the entropy of a perfect crystalline substance approaches zero, and absolute zero cannot be reached in a finite number of steps.\n\nNote: There is also a “zeroth law,” which defines temperature via thermal equilibrium.",
        "refusal": null,
        "annotations": []
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 15,
    "completion_tokens": 550,
    "total_tokens": 565,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 384,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default",
  "system_fingerprint": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5",
  "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"
    }
  ]
}'
```

```
The built-in json module is the standard way.

Basic: read an entire JSON file into a Python object (dict/list)
import json

with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# Use it
# e.g., if data is a dict:
# print(data['some_key'])

From a JSON string instead of a file
import json

s = '{"a": 1, "b": [1, 2, 3]}'
data = json.loads(s)

Robust version with error handling
import json
from pathlib import Path

path = Path('data.json')
try:
    with path.open('r', encoding='utf-8') as f:
        data = json.load(f)
except FileNotFoundError:
    print(f"File not found: {path}")
except json.JSONDecodeError as e:
    print(f"Bad JSON at line {e.lineno}, col {e.colno}: {e.msg}")

Notes and variants:
- Encoding: JSON is UTF-8 by default; specify encoding='utf-8' to be explicit.
- Large files: json.load reads the whole file into memory. For very large JSON, consider streaming parsers like ijson:
  import ijson
  with open('big.json', 'r', encoding='utf-8') as f:
      for item in ijson.items(f, 'items.item'):  # adjust prefix to your structure
          process(item)
- JSON Lines (NDJSON): one JSON object per line
  import json
  with open('data.jsonl', 'r', encoding='utf-8') as f:
      for line in f:
          line = line.strip()
          if line:
              obj = json.loads(line)
              process(obj)
- With pathlib without json.load (alternative style)
  from pathlib import Path
  import json
  data = json.loads(Path('data.json').read_text(encoding='utf-8'))
- Pandas (tabular data)
  import pandas as pd
  df = pd.read_json('data.json')           # for array-of-objects
  # or for JSON Lines:
  df = pd.read_json('data.jsonl', lines=True)

Common pitfalls:
- Trailing commas or comments are not valid JSON. If you must handle commented JSON, look at json5 or commentjson.
```

```json
{
  "id": "chatcmpl-DpLApEjnJrCwFeYGPMnwKoqO9Xpby",
  "object": "chat.completion",
  "created": 1781128491,
  "model": "gpt-5-2025-08-07",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The built-in json module is the standard way.\n\nBasic: read an entire JSON file into a Python object (dict/list)\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as f:\n    data = json.load(f)\n\n# Use it\n# e.g., if data is a dict:\n# print(data['some_key'])\n\nFrom a JSON string instead of a file\nimport json\n\ns = '{\"a\": 1, \"b\": [1, 2, 3]}'\ndata = json.loads(s)\n\nRobust version with error handling\nimport json\nfrom pathlib import Path\n\npath = Path('data.json')\ntry:\n    with path.open('r', encoding='utf-8') as f:\n        data = json.load(f)\nexcept FileNotFoundError:\n    print(f\"File not found: {path}\")\nexcept json.JSONDecodeError as e:\n    print(f\"Bad JSON at line {e.lineno}, col {e.colno}: {e.msg}\")\n\nNotes and variants:\n- Encoding: JSON is UTF-8 by default; specify encoding='utf-8' to be explicit.\n- Large files: json.load reads the whole file into memory. For very large JSON, consider streaming parsers like ijson:\n  import ijson\n  with open('big.json', 'r', encoding='utf-8') as f:\n      for item in ijson.items(f, 'items.item'):  # adjust prefix to your structure\n          process(item)\n- JSON Lines (NDJSON): one JSON object per line\n  import json\n  with open('data.jsonl', 'r', encoding='utf-8') as f:\n      for line in f:\n          line = line.strip()\n          if line:\n              obj = json.loads(line)\n              process(obj)\n- With pathlib without json.load (alternative style)\n  from pathlib import Path\n  import json\n  data = json.loads(Path('data.json').read_text(encoding='utf-8'))\n- Pandas (tabular data)\n  import pandas as pd\n  df = pd.read_json('data.json')           # for array-of-objects\n  # or for JSON Lines:\n  df = pd.read_json('data.jsonl', lines=True)\n\nCommon pitfalls:\n- Trailing commas or comments are not valid JSON. If you must handle commented JSON, look at json5 or commentjson.",
        "refusal": null,
        "annotations": []
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 30,
    "completion_tokens": 1143,
    "total_tokens": 1173,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 640,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default",
  "system_fingerprint": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5",
  "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"
    }
  ]
}'
```

```
Great question! There are three main ways to go from SF to LA, each with different types of stops. Here are top picks by route, plus a couple sample itineraries.

Fastest (I-5)
- Harris Ranch (Coalinga): Classic steakhouse, big rest stop, EV chargers.
- Kettleman City: Food options (In-N-Out, Bravo Farms), large restrooms, EV superchargers.
- Fort Tejon State Historic Park (near Lebec): Stretch your legs among oak woodlands and historic barracks.
- Pyramid Lake Vista Point (north of Santa Clarita): Quick scenic stop before the final stretch.

Balanced coastal (US-101)
- San Luis Obispo: Charming downtown; Madonna Inn for a quirky snack/photo stop.
- Pismo Beach: Pier, clams, Monarch Butterfly Grove (seasonal: late Oct–Feb).
- Edna Valley or Paso Robles: Easy-access wineries for tastings (designate a driver).
- Solvang: Danish village vibes, pastries, windmills; Pea Soup Andersen’s in nearby Buellton.
- Santa Barbara: Mission, Funk Zone wineries/breweries, waterfront and Stearns Wharf.
- Ventura/Carpinteria: Carpinteria Bluffs and Tar Pits Park; mellow beaches.

Most scenic (Highway 1 / Pacific Coast Highway)
- Half Moon Bay or Santa Cruz: Coffee/beach walk to kick off the coast route.
- Monterey & Pacific Grove: Cannery Row, Monterey Bay Aquarium, 17‑Mile Drive, Lovers Point.
- Point Lobos State Natural Reserve: Short world‑class coastal hikes; arrive early for parking.
- Big Sur highlights: Bixby Creek Bridge overlook; Garrapata State Park pullouts; Pfeiffer Big Sur State Park (valley trails); Pfeiffer Beach (purple sand/keyhole rock, narrow access road); Nepenthe or Big Sur Bakery for views/food.
- Julia Pfeiffer Burns SP: McWay Falls overlook (iconic).
- San Simeon & Cambria: Elephant Seal Vista Point at Piedras Blancas; Hearst Castle (reserve tours); Moonstone Beach boardwalk.
- Morro Bay: Embarcadero and Morro Rock; sea otters often visible.
- Pismo/Oceano: Dunes, beach towns.
- Santa Barbara and Malibu: Finish with beaches like El Matador, Point Dume.

Sample one-day coastal highlight (long day)
- SF → Monterey (breakfast + quick 17‑Mile Drive/Point Lobos) → Big Sur (Bixby, McWay Falls, lunch) → Elephant seals → Santa Barbara (dinner) → LA.

Relaxed two-day coastal trip
- Day 1: SF → Monterey/Carmel → Big Sur hikes/lookouts → Overnight in Cambria, San Simeon, or San Luis Obispo.
- Day 2: Pismo → Solvang pastry stop → Santa Barbara lunch/beach → Malibu sunset → LA.

Tips
- Check Highway 1 conditions (landslides/closures are common in Big Sur): Caltrans QuickMap before you go.
- Start early for parking at Point Lobos/Big Sur stops; cell service is spotty in Big Sur.
- Book Hearst Castle tours and Big Sur/SLO lodging ahead, especially weekends/holidays.
- Bring layers; coastal weather changes fast. Fuel up before Big Sur—few gas stations.

If you tell me:
- Which route you prefer (I-5 speed, 101 balance, or Hwy 1 scenery),
- How many days you have,
- Interests (hikes, food/wine, beaches, kid-friendly, pet-friendly),
I’ll map a tailored stop-by-stop plan with drive times.
```

```json
{
  "id": "chatcmpl-DpLBM7b0Zf6BIFOThPdIAnUziVmcV",
  "object": "chat.completion",
  "created": 1781128524,
  "model": "gpt-5-2025-08-07",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Great question! There are three main ways to go from SF to LA, each with different types of stops. Here are top picks by route, plus a couple sample itineraries.\n\nFastest (I-5)\n- Harris Ranch (Coalinga): Classic steakhouse, big rest stop, EV chargers.\n- Kettleman City: Food options (In-N-Out, Bravo Farms), large restrooms, EV superchargers.\n- Fort Tejon State Historic Park (near Lebec): Stretch your legs among oak woodlands and historic barracks.\n- Pyramid Lake Vista Point (north of Santa Clarita): Quick scenic stop before the final stretch.\n\nBalanced coastal (US-101)\n- San Luis Obispo: Charming downtown; Madonna Inn for a quirky snack/photo stop.\n- Pismo Beach: Pier, clams, Monarch Butterfly Grove (seasonal: late Oct–Feb).\n- Edna Valley or Paso Robles: Easy-access wineries for tastings (designate a driver).\n- Solvang: Danish village vibes, pastries, windmills; Pea Soup Andersen’s in nearby Buellton.\n- Santa Barbara: Mission, Funk Zone wineries/breweries, waterfront and Stearns Wharf.\n- Ventura/Carpinteria: Carpinteria Bluffs and Tar Pits Park; mellow beaches.\n\nMost scenic (Highway 1 / Pacific Coast Highway)\n- Half Moon Bay or Santa Cruz: Coffee/beach walk to kick off the coast route.\n- Monterey & Pacific Grove: Cannery Row, Monterey Bay Aquarium, 17‑Mile Drive, Lovers Point.\n- Point Lobos State Natural Reserve: Short world‑class coastal hikes; arrive early for parking.\n- Big Sur highlights: Bixby Creek Bridge overlook; Garrapata State Park pullouts; Pfeiffer Big Sur State Park (valley trails); Pfeiffer Beach (purple sand/keyhole rock, narrow access road); Nepenthe or Big Sur Bakery for views/food.\n- Julia Pfeiffer Burns SP: McWay Falls overlook (iconic).\n- San Simeon & Cambria: Elephant Seal Vista Point at Piedras Blancas; Hearst Castle (reserve tours); Moonstone Beach boardwalk.\n- Morro Bay: Embarcadero and Morro Rock; sea otters often visible.\n- Pismo/Oceano: Dunes, beach towns.\n- Santa Barbara and Malibu: Finish with beaches like El Matador, Point Dume.\n\nSample one-day coastal highlight (long day)\n- SF → Monterey (breakfast + quick 17‑Mile Drive/Point Lobos) → Big Sur (Bixby, McWay Falls, lunch) → Elephant seals → Santa Barbara (dinner) → LA.\n\nRelaxed two-day coastal trip\n- Day 1: SF → Monterey/Carmel → Big Sur hikes/lookouts → Overnight in Cambria, San Simeon, or San Luis Obispo.\n- Day 2: Pismo → Solvang pastry stop → Santa Barbara lunch/beach → Malibu sunset → LA.\n\nTips\n- Check Highway 1 conditions (landslides/closures are common in Big Sur): Caltrans QuickMap before you go.\n- Start early for parking at Point Lobos/Big Sur stops; cell service is spotty in Big Sur.\n- Book Hearst Castle tours and Big Sur/SLO lodging ahead, especially weekends/holidays.\n- Bring layers; coastal weather changes fast. Fuel up before Big Sur—few gas stations.\n\nIf you tell me:\n- Which route you prefer (I-5 speed, 101 balance, or Hwy 1 scenery),\n- How many days you have,\n- Interests (hikes, food/wine, beaches, kid-friendly, pet-friendly),\nI’ll map a tailored stop-by-stop plan with drive times.",
        "refusal": null,
        "annotations": []
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 76,
    "completion_tokens": 1926,
    "total_tokens": 2002,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 1152,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default",
  "system_fingerprint": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
The diner on Maple had the sort of dawn that came with mop water and an apology. Lemon and old fry oil hung in the air; the neon COFFEE sign in the front window had sputtered itself into a coma sometime before three. Someone had left the door propped with a folded phone book. Someone else had left fingerprints everywhere you could put a hand to steady yourself.

“Mr. Hale?” The manager’s voice came out thin. He was a man who wore his keys like medals, ring clinking against the register as if noise could keep the room from thinking about what had happened in the stockroom. He kept rubbing a clean spot on the Formica with the heel of his palm. “They said not to touch anything. But, uh, someone’s going to have to… You know. She’s back there.”

“I know.” I did not look back there yet. The living are easier to talk to than the dead. The living lie worse, too.

It wasn’t my first crime scene in a place that sold coffee by the gallon, but it was the first time time itself had been sitting on the counter.

Right in the dead center of the service line, between the sugar pourer and a pitcher lipped with milk, stood an hourglass. Not the novelty kind with pink sand and a smiley face, but two clean bulbs pinched at the waist and sealed with a brass cap, the sort of thing you buy for seventeen dollars at a shop that also sells candles that smell like foreign countries.

The stuff pouring through it wasn’t sand.

Dark grit eased from the top bulb to the bottom in a slow, stubborn ribbon. The grounds were too coarse for espresso, too fine for the diner’s clumsy metal basket. I leaned in and the smell of chicory lifted and slid clean into my head. Coffee with teeth. Not something Maple Street Diner served, not in the ten years I’d been stopping in for grilled cheese on Tuesdays. They brewed what came in five-pound bricks with promises on the bag and regrets in the cup.

The hourglass sat in a perfect ring of coffee, the way a drink leaves its mark if you lift it and set it down, lift it and set it down, chasing conversation. Only the ring was too clean, too even. Not slapped there by accident but drawn, like a target.

“Don’t they come with sand?” the manager said, as if I’d stock tips on timepieces. He had the kind of face you wanted to put directions on. He kept glancing toward the hallway where the kitchen started. “Who would bring that here?”

“Somebody who wanted us to see it.” I bent until the glass filled my whole world, the way a thing does when you’re trying not to see a bigger thing behind it. Grounds slid down and hit the bottom with tiny clicks, a sound you feel more than hear. The top bulb was half-empty. The bottom was making a little hill that would slump and start again, brown avalanches inside a winter globe.

There were four notch marks on the counter by the hourglass, burned in with something hot. A cigarette, maybe, or a soldering iron. Not long lines, just ticks where a thumbnail might count. The fugitive smell of something singed lived there. I put a finger near one and felt the edge of the scorch under the polish of a thousand elbows. Not fresh. But made last night, if the way they were crisping under the fluorescent hum meant anything.

I didn’t touch the glass. I touched the ring instead, lightly, because that’s what people notice if you don’t. It was tacky. It left the faint outline of my fingertip when I lifted it away. The coffee in the ring had been thick when it went down, not drip-thin but almost syrup, like someone boiled it down on the stovetop. Old trick for buzzing cheap liquor. Or for drawing with.

“Chicory,” I said, mostly to the hourglass. The manager blinked at me, like I’d just named my favorite constellation.

“Is that… good?”

“If you’re homesick for New Orleans and don’t mind lying to yourself,” I said. It wasn’t a Maple Street thing. It was nowhere-on-this-block thing. There was a place on Luzerne that sold blue crab on Sundays and tobacco under the counter on every day that ended in Y; they stocked cans with a fleur-de-lis on the label behind a curtain you had to ask to see. People who bought it were a certain kind of precise. They liked their mornings with a habit in them.

Someone had clocked her in the stockroom, the call had said, a quick violence that made a long problem. Someone had propped the door so the sirens wouldn’t have to rattle the handle. Someone had time to leave me a prop that wasn’t a prop at all.

“Do me a favor,” I said. “Don’t let anyone touch this. Or sneeze on it. Or breathe enthusiastically.”

The manager nodded as if those were the rules we’d been living by all along. He made himself small, backing away without looking away, like the hourglass might leap off the counter and bite him.

I watched grounds fall through the neck. When they hit the bottom, they rolled a little and settled. The top empties, the bottom fills. After a certain point, if you don’t turn it over, it’s done.

Four notches. A ring drawn too carefully to have happened on accident. Chicory where there shouldn’t be chicory. I counted in my head with the tiny rain of grit, not minutes, because those stretch and snap, but beats. The hourglass bled its coffee heart out with a drummer’s stubbornness—two hundred and forty by the time the hill slumped over and smoothed into itself.

Four flips. Four songs at two minutes each. Four smoke breaks. Four chances to wait and see if someone came through the side door with a soft apology and a reason.

I didn’t know, not yet, what the someone had been timing. Grief. Guts. The moment the street went quiet enough for them to walk. A message for anybody who could read taste and habit like handwriting.

All I knew was that the glass didn’t belong here and neither did its smell. The clue wasn’t unusual because it was clever. It was unusual because it was kind. Somebody, standing in a cheap-lit diner with lemon in their nose and something ruinous at their back, had thought to leave me time that I could tip over with a wrist. Time I could see.

I wish the dead had names like that. I wish they all came with something you could hold up to the light and say, here, this is how long it took. This is where it started; this is where it ran out.

“Mr. Hale?” The manager had drifted back. He’d taken off his keys and set them in a neat circle beside the register, a little hourglass of his own. He had a voice that was trying to be a whisper but kept smarting into sound. “Do you want to—should I—”

“In a minute,” I said. The coffee ring had started to skin over. The grounds made a small mountain inside their bottle. I lowered my head until I could see the thin seam in the brass cap that sealed it, a tiny imperfection in a factory finish. Someone had pried it open once with a butter knife and tamped the top with a thumb. It had a dent in it, a crescent like the side of a bitten moon.

Sometimes the city gives you a map. Sometimes it just gives you a circle and tells you to stand inside it until the world narrows down to what fits. I straightened, and the room got bigger.

“Okay,” I said. “Let’s go look at the thing we’re not looking at.”
```

```json
{
  "id": "chatcmpl-DpLK1cHoQaButs3hdRNv4w58l1y8J",
  "object": "chat.completion",
  "created": 1781129061,
  "model": "gpt-5-2025-08-07",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The diner on Maple had the sort of dawn that came with mop water and an apology. Lemon and old fry oil hung in the air; the neon COFFEE sign in the front window had sputtered itself into a coma sometime before three. Someone had left the door propped with a folded phone book. Someone else had left fingerprints everywhere you could put a hand to steady yourself.\n\n“Mr. Hale?” The manager’s voice came out thin. He was a man who wore his keys like medals, ring clinking against the register as if noise could keep the room from thinking about what had happened in the stockroom. He kept rubbing a clean spot on the Formica with the heel of his palm. “They said not to touch anything. But, uh, someone’s going to have to… You know. She’s back there.”\n\n“I know.” I did not look back there yet. The living are easier to talk to than the dead. The living lie worse, too.\n\nIt wasn’t my first crime scene in a place that sold coffee by the gallon, but it was the first time time itself had been sitting on the counter.\n\nRight in the dead center of the service line, between the sugar pourer and a pitcher lipped with milk, stood an hourglass. Not the novelty kind with pink sand and a smiley face, but two clean bulbs pinched at the waist and sealed with a brass cap, the sort of thing you buy for seventeen dollars at a shop that also sells candles that smell like foreign countries.\n\nThe stuff pouring through it wasn’t sand.\n\nDark grit eased from the top bulb to the bottom in a slow, stubborn ribbon. The grounds were too coarse for espresso, too fine for the diner’s clumsy metal basket. I leaned in and the smell of chicory lifted and slid clean into my head. Coffee with teeth. Not something Maple Street Diner served, not in the ten years I’d been stopping in for grilled cheese on Tuesdays. They brewed what came in five-pound bricks with promises on the bag and regrets in the cup.\n\nThe hourglass sat in a perfect ring of coffee, the way a drink leaves its mark if you lift it and set it down, lift it and set it down, chasing conversation. Only the ring was too clean, too even. Not slapped there by accident but drawn, like a target.\n\n“Don’t they come with sand?” the manager said, as if I’d stock tips on timepieces. He had the kind of face you wanted to put directions on. He kept glancing toward the hallway where the kitchen started. “Who would bring that here?”\n\n“Somebody who wanted us to see it.” I bent until the glass filled my whole world, the way a thing does when you’re trying not to see a bigger thing behind it. Grounds slid down and hit the bottom with tiny clicks, a sound you feel more than hear. The top bulb was half-empty. The bottom was making a little hill that would slump and start again, brown avalanches inside a winter globe.\n\nThere were four notch marks on the counter by the hourglass, burned in with something hot. A cigarette, maybe, or a soldering iron. Not long lines, just ticks where a thumbnail might count. The fugitive smell of something singed lived there. I put a finger near one and felt the edge of the scorch under the polish of a thousand elbows. Not fresh. But made last night, if the way they were crisping under the fluorescent hum meant anything.\n\nI didn’t touch the glass. I touched the ring instead, lightly, because that’s what people notice if you don’t. It was tacky. It left the faint outline of my fingertip when I lifted it away. The coffee in the ring had been thick when it went down, not drip-thin but almost syrup, like someone boiled it down on the stovetop. Old trick for buzzing cheap liquor. Or for drawing with.\n\n“Chicory,” I said, mostly to the hourglass. The manager blinked at me, like I’d just named my favorite constellation.\n\n“Is that… good?”\n\n“If you’re homesick for New Orleans and don’t mind lying to yourself,” I said. It wasn’t a Maple Street thing. It was nowhere-on-this-block thing. There was a place on Luzerne that sold blue crab on Sundays and tobacco under the counter on every day that ended in Y; they stocked cans with a fleur-de-lis on the label behind a curtain you had to ask to see. People who bought it were a certain kind of precise. They liked their mornings with a habit in them.\n\nSomeone had clocked her in the stockroom, the call had said, a quick violence that made a long problem. Someone had propped the door so the sirens wouldn’t have to rattle the handle. Someone had time to leave me a prop that wasn’t a prop at all.\n\n“Do me a favor,” I said. “Don’t let anyone touch this. Or sneeze on it. Or breathe enthusiastically.”\n\nThe manager nodded as if those were the rules we’d been living by all along. He made himself small, backing away without looking away, like the hourglass might leap off the counter and bite him.\n\nI watched grounds fall through the neck. When they hit the bottom, they rolled a little and settled. The top empties, the bottom fills. After a certain point, if you don’t turn it over, it’s done.\n\nFour notches. A ring drawn too carefully to have happened on accident. Chicory where there shouldn’t be chicory. I counted in my head with the tiny rain of grit, not minutes, because those stretch and snap, but beats. The hourglass bled its coffee heart out with a drummer’s stubbornness—two hundred and forty by the time the hill slumped over and smoothed into itself.\n\nFour flips. Four songs at two minutes each. Four smoke breaks. Four chances to wait and see if someone came through the side door with a soft apology and a reason.\n\nI didn’t know, not yet, what the someone had been timing. Grief. Guts. The moment the street went quiet enough for them to walk. A message for anybody who could read taste and habit like handwriting.\n\nAll I knew was that the glass didn’t belong here and neither did its smell. The clue wasn’t unusual because it was clever. It was unusual because it was kind. Somebody, standing in a cheap-lit diner with lemon in their nose and something ruinous at their back, had thought to leave me time that I could tip over with a wrist. Time I could see.\n\nI wish the dead had names like that. I wish they all came with something you could hold up to the light and say, here, this is how long it took. This is where it started; this is where it ran out.\n\n“Mr. Hale?” The manager had drifted back. He’d taken off his keys and set them in a neat circle beside the register, a little hourglass of his own. He had a voice that was trying to be a whisper but kept smarting into sound. “Do you want to—should I—”\n\n“In a minute,” I said. The coffee ring had started to skin over. The grounds made a small mountain inside their bottle. I lowered my head until I could see the thin seam in the brass cap that sealed it, a tiny imperfection in a factory finish. Someone had pried it open once with a butter knife and tamped the top with a thumb. It had a dent in it, a crescent like the side of a bitten moon.\n\nSometimes the city gives you a map. Sometimes it just gives you a circle and tells you to stand inside it until the world narrows down to what fits. I straightened, and the room got bigger.\n\n“Okay,” I said. “Let’s go look at the thing we’re not looking at.”",
        "refusal": null,
        "annotations": []
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 19,
    "completion_tokens": 4961,
    "total_tokens": 4980,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 3328,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default",
  "system_fingerprint": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

```
Recursion is when a function solves a problem by calling itself on a smaller version of the same problem, stopping at a simple “base case.”

Simple example: factorial
- Definition: n! (n factorial) is n × (n−1) × (n−2) × … × 1, and 0! = 1.
- Recursive idea: n! = n × (n−1)! with base case 0! = 1.

How factorial(4) works:
- fact(4) = 4 × fact(3)
- fact(3) = 3 × fact(2)
- fact(2) = 2 × fact(1)
- fact(1) = 1 × fact(0)
- fact(0) = 1  ← base case
- Unwinding: 1 → 1 → 2 → 6 → 24, so fact(4) = 24.

Tiny Python version:
def fact(n):
    if n == 0:          # base case
        return 1
    return n * fact(n-1)  # recursive step

Key points:
- Always have a base case to stop.
- Each call must move toward the base case (smaller/simpler input).
- Missing either leads to infinite recursion (and a crash).
```

```json
[
  {
    "id": "chatcmpl-DpLF5wgUn4piBACWXAMIcVeY5hgvW",
    "object": "chat.completion.chunk",
    "created": 1781128755,
    "model": "gpt-5-2025-08-07",
    "service_tier": "default",
    "system_fingerprint": null,
    "choices": [
      {
        "index": 0,
        "delta": {
          "role": "assistant",
          "content": "",
          "refusal": null
        },
        "finish_reason": null
      }
    ],
    "usage": null,
    "obfuscation": "SbmWVVEKFF"
  },
  {
    "id": "chatcmpl-DpLF5wgUn4piBACWXAMIcVeY5hgvW",
    "object": "chat.completion.chunk",
    "created": 1781128755,
    "model": "gpt-5-2025-08-07",
    "service_tier": "default",
    "system_fingerprint": null,
    "choices": [
      {
        "index": 0,
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null
      }
    ],
    "usage": null,
    "obfuscation": "779H6FdPD"
  },
  "... 276 more chunks omitted ...",
  {
    "id": "chatcmpl-DpLF5wgUn4piBACWXAMIcVeY5hgvW",
    "object": "chat.completion.chunk",
    "created": 1781128755,
    "model": "gpt-5-2025-08-07",
    "service_tier": "default",
    "system_fingerprint": null,
    "choices": [],
    "usage": {
      "prompt_tokens": 16,
      "completion_tokens": 797,
      "total_tokens": 813,
      "prompt_tokens_details": {
        "cached_tokens": 0,
        "audio_tokens": 0
      },
      "completion_tokens_details": {
        "reasoning_tokens": 512,
        "audio_tokens": 0,
        "accepted_prediction_tokens": 0,
        "rejected_prediction_tokens": 0
      }
    },
    "obfuscation": "FQ6Wmta"
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5",
  "input": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
  "max_output_tokens": 4096,
  "tools": [
    {
      "type": "web_search_preview"
    }
  ]
}'
```

```
- June 22, 2026: Cloudflare reported increased error rates and latency tied to a fiber cut in Eastern North America, leading to a partial outage and degraded CDN/Cache performance before traffic engineering mitigations stabilized services later in the day. ([cloudflarestatus.com](https://www.cloudflarestatus.com/))
- June 17–18, 2026: Cloudflare expanded its channel focus—launching a Cloudflare One “Design Partner” designation and AI-powered migration toolkit for SASE/Zero Trust deployments—and signed Westcon‑Comstor as an EMEA‑wide distributor to scale partner-led delivery. ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))
- June 16, 2026: Investor group JLens urged Cloudflare shareholders to withhold votes for two directors at the June 30 annual meeting, citing an ADL report criticizing Cloudflare’s services being used by extremist sites; the campaign was covered across financial wires. ([investing.com](https://www.investing.com/news/company-news/jlens-urges-cloudflare-shareholders-to-withhold-board-votes-93CH-4744895))
```

```json
{
  "id": "resp_02d60b161a01d826016a3990457fa8819b9fc528ec4ea8ad5c",
  "object": "response",
  "created_at": 1782157381,
  "model": "gpt-5-2025-08-07",
  "output": [
    {
      "id": "rs_02d60b161a01d826016a399046a994819b9d25e70abcd3c56c",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_02d60b161a01d826016a3990486108819ba2c466fcb838af82",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news this week June 2026",
          "Cloudflare outage June 2026",
          "Cloudflare announces new product June 2026",
          "Cloudflare earnings June 2026"
        ],
        "query": "Cloudflare news this week June 2026"
      }
    },
    {
      "id": "rs_02d60b161a01d826016a39904d3e18819bb22818e22bb15f3d",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_02d60b161a01d826016a399050a86c819bae0316a4c7791202",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.cloudflarestatus.com/"
      }
    },
    {
      "id": "rs_02d60b161a01d826016a39905240c4819b8bc7c2276ee250d7",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_02d60b161a01d826016a399055207c819bade6df968621d6c8",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "site:cloudflare.com blog June 2026 Cloudflare announcement",
          "Cloudflare announces new AI features June 2026",
          "Cloudflare expands partner program June 2026 news"
        ],
        "query": "site:cloudflare.com blog June 2026 Cloudflare announcement"
      }
    },
    {
      "id": "rs_02d60b161a01d826016a3990593d7c819bb833cdeb40ea0a49",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_02d60b161a01d826016a39905b72e8819b9cd20de4259f2bba",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news June 21 2026",
          "Cloudflare June 20 2026 news",
          "Cloudflare June 19 2026 news",
          "Cloudflare June 16 2026 news"
        ],
        "query": "Cloudflare news June 21 2026"
      }
    },
    {
      "id": "rs_02d60b161a01d826016a3990606f34819baa6fb7267003e879",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_02d60b161a01d826016a3990622f28819bbabde7f244f20734",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "find_in_page",
        "pattern": "Jun 22",
        "url": "https://www.cloudflarestatus.com/"
      }
    },
    {
      "id": "rs_02d60b161a01d826016a399065ff30819b9c45d7c98a8f4e39",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_02d60b161a01d826016a39906963c0819bb0131af6ba3bc7f7",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.investing.com/news/company-news/jlens-urges-cloudflare-shareholders-to-withhold-board-votes-93CH-4744895"
      }
    },
    {
      "id": "rs_02d60b161a01d826016a39906b470c819ba2d18b349dc31613",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_02d60b161a01d826016a39906c101c819ba96f130294f46458",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "JLens urges Cloudflare shareholders to withhold votes Reuters June 16, 2026",
          "ADL report Cloudflare withhold vote JLens June 2026"
        ],
        "query": "JLens urges Cloudflare shareholders to withhold votes Reuters June 16, 2026"
      }
    },
    {
      "id": "rs_02d60b161a01d826016a3990725224819ba7f98ab9f71093ef",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_02d60b161a01d826016a3990757154819b9d9aee09a6c4a2e7",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://simplywall.st/stocks/us/software/nyse-net/cloudflare/news/cloudflare-net-expands-ai-security-with-ping-identity-partne"
      }
    },
    {
      "id": "rs_02d60b161a01d826016a399079c738819b8b884bab3927fe7c",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_02d60b161a01d826016a39907a6720819b8df7a6994610bd54",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare Ping Identity partnership June 2026",
          "Ping Identity Cloudflare partnership 2026"
        ],
        "query": "Cloudflare Ping Identity partnership June 2026"
      }
    },
    {
      "id": "rs_02d60b161a01d826016a3990817980819bab31195c884444a6",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "msg_02d60b161a01d826016a3990922d28819ba309de72951ad102",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 316,
              "start_index": 257,
              "title": "Cloudflare Status",
              "url": "https://www.cloudflarestatus.com/"
            },
            {
              "type": "url_citation",
              "end_index": 746,
              "start_index": 582,
              "title": "Cloudflare launches new partner initiative to support AI and SASE adoption",
              "url": "https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 1152,
              "start_index": 1017,
              "title": "JLens urges Cloudflare shareholders to withhold board votes By Investing.com",
              "url": "https://www.investing.com/news/company-news/jlens-urges-cloudflare-shareholders-to-withhold-board-votes-93CH-4744895"
            }
          ],
          "logprobs": [],
          "text": "- June 22, 2026: Cloudflare reported increased error rates and latency tied to a fiber cut in Eastern North America, leading to a partial outage and degraded CDN/Cache performance before traffic engineering mitigations stabilized services later in the day. ([cloudflarestatus.com](https://www.cloudflarestatus.com/))\n- June 17–18, 2026: Cloudflare expanded its channel focus—launching a Cloudflare One “Design Partner” designation and AI-powered migration toolkit for SASE/Zero Trust deployments—and signed Westcon‑Comstor as an EMEA‑wide distributor to scale partner-led delivery. ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))\n- June 16, 2026: Investor group JLens urged Cloudflare shareholders to withhold votes for two directors at the June 30 annual meeting, citing an ADL report criticizing Cloudflare’s services being used by extremist sites; the campaign was covered across financial wires. ([investing.com](https://www.investing.com/news/company-news/jlens-urges-cloudflare-shareholders-to-withhold-board-votes-93CH-4744895))"
        }
      ],
      "role": "assistant"
    }
  ],
  "status": "completed",
  "usage": {
    "input_tokens": 45264,
    "output_tokens": 2548,
    "total_tokens": 47812,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 1920
    }
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
... response truncated ...
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5/#page","headline":"GPT-5","description":"OpenAI's model excelling at coding, writing, and reasoning.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5 Mini is the lightweight, low-cost variant of GPT-5, well suited to high-volume coding and reasoning tasks.
title: GPT-5 mini
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5 mini

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5-mini/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5-mini`

- Third-party
- Zero data retention

GPT-5 Mini is the lightweight, low-cost variant of GPT-5, well suited to high-volume coding and reasoning tasks.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 128,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.25</li><li>Output (per 1M tokens)$2.00</li><li>Cached input (per 1M tokens)$0.025</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5-mini',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-mini",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
Briefly, the fundamental laws are:

- Zeroth law (often counted separately): If system A is in thermal equilibrium with B, and B is in thermal equilibrium with C, then A is in thermal equilibrium with C. This justifies the concept of temperature and allows the use of thermometers.

- First law (conservation of energy): Energy is conserved. For a closed system,
  ΔU = Q − W,
  where ΔU is the change in internal energy, Q is heat added to the system, and W is work done by the system.

- Second law (direction of processes; entropy): Natural processes increase the total entropy of an isolated system. A standard mathematical statement:
  ΔS ≥ ∫ δQ_rev/T,
  and for an isolated system ΔS ≥ 0. Equivalent formulations: no cyclic engine can convert all heat into work (Kelvin–Planck), and heat cannot spontaneously flow from a colder to a hotter body (Clausius).

- Third law (zero‑temperature limit): As T → 0, the entropy of a perfect crystalline substance approaches a constant (often taken as zero). Consequences include the unattainability principle: absolute zero cannot be reached in a finite number of steps.

(Traditionally textbooks list the First, Second and Third laws; the Zeroth law was named later because it underpins the concept of temperature.)
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Briefly, the fundamental laws are:\n\n- Zeroth law (often counted separately): If system A is in thermal equilibrium with B, and B is in thermal equilibrium with C, then A is in thermal equilibrium with C. This justifies the concept of temperature and allows the use of thermometers.\n\n- First law (conservation of energy): Energy is conserved. For a closed system,\n  ΔU = Q − W,\n  where ΔU is the change in internal energy, Q is heat added to the system, and W is work done by the system.\n\n- Second law (direction of processes; entropy): Natural processes increase the total entropy of an isolated system. A standard mathematical statement:\n  ΔS ≥ ∫ δQ_rev/T,\n  and for an isolated system ΔS ≥ 0. Equivalent formulations: no cyclic engine can convert all heat into work (Kelvin–Planck), and heat cannot spontaneously flow from a colder to a hotter body (Clausius).\n\n- Third law (zero‑temperature limit): As T → 0, the entropy of a perfect crystalline substance approaches a constant (often taken as zero). Consequences include the unattainability principle: absolute zero cannot be reached in a finite number of steps.\n\n(Traditionally textbooks list the First, Second and Third laws; the Zeroth law was named later because it underpins the concept of temperature.)",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777320124,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMRYPDmQAXQ6d6GeOKrgb8jeCPgK",
  "model": "gpt-5-mini-2025-08-07",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 673,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 384,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 15,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 688
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-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"
    }
  ]
}'
```

````
The built‑in json module is the usual way. Use json.load() to parse a file object into Python objects (dicts, lists, strings, numbers, booleans, None).

Basic example:
```python
import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(type(data))  # usually dict or list
print(data)
```

Read from a JSON string:
```python
s = '{"name": "Alice", "age": 30}'
obj = json.loads(s)
```

Common extras

- Error handling:
```python
import json

try:
    with open("data.json", "r", encoding="utf-8") as f:
        data = json.load(f)
except FileNotFoundError:
    print("File not found")
except json.JSONDecodeError as e:
    print("Invalid JSON:", e)
```

- Newline-delimited JSON (NDJSON / JSON Lines):
```python
import json

with open("lines.jsonl", "r", encoding="utf-8") as f:
    for line in f:
        if line.strip():
            obj = json.loads(line)
            # process obj
```

- Large files (streaming): for very large JSON arrays, use a streaming parser like ijson to avoid loading everything into memory:
```python
import ijson

with open("big.json", "rb") as f:
    for item in ijson.items(f, "item"):  # "item" is path for array elements
        # process item
```

- Compressed JSON:
```python
import gzip, json

with gzip.open("data.json.gz", "rt", encoding="utf-8") as f:
    data = json.load(f)
```

- Convert Python back to JSON:
```python
with open("out.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)
```

If your JSON maps naturally to tabular data, pandas.read_json can be convenient:
```python
import pandas as pd
df = pd.read_json("data.json")
```

That covers the usual ways — if you share the structure of your JSON or constraints (huge file, NDJSON, custom types), I can give a more specific example.
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The built‑in json module is the usual way. Use json.load() to parse a file object into Python objects (dicts, lists, strings, numbers, booleans, None).\n\nBasic example:\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n\nprint(type(data))  # usually dict or list\nprint(data)\n```\n\nRead from a JSON string:\n```python\ns = '{\"name\": \"Alice\", \"age\": 30}'\nobj = json.loads(s)\n```\n\nCommon extras\n\n- Error handling:\n```python\nimport json\n\ntry:\n    with open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n        data = json.load(f)\nexcept FileNotFoundError:\n    print(\"File not found\")\nexcept json.JSONDecodeError as e:\n    print(\"Invalid JSON:\", e)\n```\n\n- Newline-delimited JSON (NDJSON / JSON Lines):\n```python\nimport json\n\nwith open(\"lines.jsonl\", \"r\", encoding=\"utf-8\") as f:\n    for line in f:\n        if line.strip():\n            obj = json.loads(line)\n            # process obj\n```\n\n- Large files (streaming): for very large JSON arrays, use a streaming parser like ijson to avoid loading everything into memory:\n```python\nimport ijson\n\nwith open(\"big.json\", \"rb\") as f:\n    for item in ijson.items(f, \"item\"):  # \"item\" is path for array elements\n        # process item\n```\n\n- Compressed JSON:\n```python\nimport gzip, json\n\nwith gzip.open(\"data.json.gz\", \"rt\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n```\n\n- Convert Python back to JSON:\n```python\nwith open(\"out.json\", \"w\", encoding=\"utf-8\") as f:\n    json.dump(data, f, ensure_ascii=False, indent=2)\n```\n\nIf your JSON maps naturally to tabular data, pandas.read_json can be convenient:\n```python\nimport pandas as pd\ndf = pd.read_json(\"data.json\")\n```\n\nThat covers the usual ways — if you share the structure of your JSON or constraints (huge file, NDJSON, custom types), I can give a more specific example.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777320141,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMRprAcSRmcAdqafyZx3VJbKyz1M",
  "model": "gpt-5-mini-2025-08-07",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 754,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 256,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 784
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-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"
    }
  ]
}'
```

```
Great — here are several good stop options and a few sample itineraries depending on how much time you have and which route you take (PCH/Highway 1 for scenery, US‑101 for a balance of speed and towns, I‑5 if you want the fastest drive).

High-level route choices
- Pacific Coast Highway (CA‑1 / PCH): Most scenic — cliffs, beaches, Big Sur. Slow, can be winding and has occasional closures/traffic.
- US‑101: Faster than CA‑1 and still scenic through coastal towns, wine country, and beaches.
- I‑5: Fastest (about 5–6 hours), but mostly inland and not scenic. Good if you want to minimize driving time.

Useful tip: check Caltrans for road conditions and CA‑1/Big Sur closures before you go; plan around LA rush hour (avoid entering LA 3–7 pm) and leaving SF early to beat Bay Area traffic.

Stops (north → south) — highlights by route

Common coastal highlights (CA‑1 & 101 overlap in places)
- Half Moon Bay (30–45 min from SF)
  - Quick beach walk, pastries (Local bakeries), coastal trail views.
- Santa Cruz (1–1.5 hr from SF)
  - Boardwalk, surf spots, downtown restaurants.
- Capitola (near Santa Cruz)
  - Colorful seaside village good for a short stroll and lunch.

Monterey/Carmel area (great for families/couples)
- Monterey Bay Aquarium (Monterey)
  - World-class aquarium, Cannery Row dining.
- 17‑Mile Drive / Pebble Beach (Carmel/Monterey)
  - Scenic loop with coastal viewpoints and Lone Cypress.
- Carmel-by-the-Sea
  - Charming village, galleries, beach.

Big Sur (must-see if you have time)
- Bixby Creek Bridge (iconic photo stop)
- Pfeiffer Big Sur State Park (hiking)
- Pfeiffer Beach (purple sand, limited parking)
- McWay Falls / Julia Pfeiffer Burns State Park (waterfall onto beach)
- Note: limited services and cell coverage — fuel up in Monterey or Carmel.

San Simeon / Cambria / Hearst Castle
- Piedras Blancas elephant seal rookery (near San Simeon)
- Hearst Castle tour (advance tickets recommended)
- Cambria — quaint village for dinner/overnight.

San Luis Obispo / Pismo Beach / Morro Bay
- San Luis Obispo (downtown, bubblegum alley)
- Pismo Beach (cliffs, monarch butterflies seasonally)
- Morro Bay (Morro Rock, kayaking)

Santa Ynez Valley / Solvang (inland detour off PCH/101)
- Danish-style Solvang, wineries in Santa Ynez and Los Olivos — great for wine tasting and a slower afternoon.

Santa Barbara (the “American Riviera”)
- State Street, waterfront, mission, good dining and beaches.

Last stretch into Los Angeles (via US‑101 or PCH)
- Ventura (surf, harbor)
- Malibu (beaches, Zuma, Point Dume)
- Santa Monica / Venice (pier, boardwalk, restaurants) before heading to downtown LA or other neighborhoods.

If you take I‑5 (fastest) — practical stops
- Gilroy (garlic/food if you want a quick break)
- Kettleman City or Harris Ranch (famous steakhouse stop)
- Tejon Ranch outlets near the Grapevine (shopping, quick break)
- Pyramid Lake/ghost-town stops are possible but mostly freeway views

Sample itineraries

1) One-day drive, scenic highlights (long day)
- Early SF departure (6–7 am) → Santa Cruz (coffee, 1 hr) → Monterey (lunch, Aquarium optional, 1.5–2 hr) → Big Sur (Bixby Bridge & viewpoints, 1–1.5 hr) → San Simeon (elephant seals) → Santa Barbara arrival late evening. Expect 10–12+ hours including stops.

2) Two-day relaxed coastal trip (recommended)
Day 1: SF → Half Moon Bay → Santa Cruz → Monterey/Carmel (overnight)
Day 2: Carmel → Big Sur (Pfeiffer Beach, McWay Falls) → San Simeon or Pismo → Santa Barbara → LA
- Overnight options: Carmel, Big Sur (if available), or San Luis Obispo/Santa Barbara to split driving times.

3) Three-day scenic + wine-country
Day 1: SF → Santa Cruz → Monterey/Carmel (explore 17‑Mile Drive)
Day 2: Carmel → Big Sur → San Simeon → Pismo/Morro Bay (overnight)
Day 3: Pismo → Solvang (wine tasting) → Santa Barbara → LA

Practical tips
- Time: Without stops SF→LA on PCH/101 is 8–10 hours; I‑5 ~5–6 hours.
- Fuel and services: Fill up before Big Sur; limited gas and few restaurants in stretches.
- Reservations: Hotels in Big Sur and popular towns fill up fast — book ahead. Hearst Castle requires timed tickets.
- Weather/season: Summer fog near SF; Big Sur can have wind and cooler temps. CA‑1 sometimes closes after storms/landslides.
- Parking: Popular spots (Pfeiffer Beach, Bixby turnout, McWay Falls) can have limited parking — arrive early.
- Safety: Drive carefully on winding sections, keep an eye on fuel, cell coverage is spotty in Big Sur.

If you tell me:
- how many days you have,
- whether you prefer beaches, hiking, wine, food stops, or quick travel,
I’ll draft a detailed day‑by‑day plan with drive times, restaurants and where to stay.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Great — here are several good stop options and a few sample itineraries depending on how much time you have and which route you take (PCH/Highway 1 for scenery, US‑101 for a balance of speed and towns, I‑5 if you want the fastest drive).\n\nHigh-level route choices\n- Pacific Coast Highway (CA‑1 / PCH): Most scenic — cliffs, beaches, Big Sur. Slow, can be winding and has occasional closures/traffic.\n- US‑101: Faster than CA‑1 and still scenic through coastal towns, wine country, and beaches.\n- I‑5: Fastest (about 5–6 hours), but mostly inland and not scenic. Good if you want to minimize driving time.\n\nUseful tip: check Caltrans for road conditions and CA‑1/Big Sur closures before you go; plan around LA rush hour (avoid entering LA 3–7 pm) and leaving SF early to beat Bay Area traffic.\n\nStops (north → south) — highlights by route\n\nCommon coastal highlights (CA‑1 & 101 overlap in places)\n- Half Moon Bay (30–45 min from SF)\n  - Quick beach walk, pastries (Local bakeries), coastal trail views.\n- Santa Cruz (1–1.5 hr from SF)\n  - Boardwalk, surf spots, downtown restaurants.\n- Capitola (near Santa Cruz)\n  - Colorful seaside village good for a short stroll and lunch.\n\nMonterey/Carmel area (great for families/couples)\n- Monterey Bay Aquarium (Monterey)\n  - World-class aquarium, Cannery Row dining.\n- 17‑Mile Drive / Pebble Beach (Carmel/Monterey)\n  - Scenic loop with coastal viewpoints and Lone Cypress.\n- Carmel-by-the-Sea\n  - Charming village, galleries, beach.\n\nBig Sur (must-see if you have time)\n- Bixby Creek Bridge (iconic photo stop)\n- Pfeiffer Big Sur State Park (hiking)\n- Pfeiffer Beach (purple sand, limited parking)\n- McWay Falls / Julia Pfeiffer Burns State Park (waterfall onto beach)\n- Note: limited services and cell coverage — fuel up in Monterey or Carmel.\n\nSan Simeon / Cambria / Hearst Castle\n- Piedras Blancas elephant seal rookery (near San Simeon)\n- Hearst Castle tour (advance tickets recommended)\n- Cambria — quaint village for dinner/overnight.\n\nSan Luis Obispo / Pismo Beach / Morro Bay\n- San Luis Obispo (downtown, bubblegum alley)\n- Pismo Beach (cliffs, monarch butterflies seasonally)\n- Morro Bay (Morro Rock, kayaking)\n\nSanta Ynez Valley / Solvang (inland detour off PCH/101)\n- Danish-style Solvang, wineries in Santa Ynez and Los Olivos — great for wine tasting and a slower afternoon.\n\nSanta Barbara (the “American Riviera”)\n- State Street, waterfront, mission, good dining and beaches.\n\nLast stretch into Los Angeles (via US‑101 or PCH)\n- Ventura (surf, harbor)\n- Malibu (beaches, Zuma, Point Dume)\n- Santa Monica / Venice (pier, boardwalk, restaurants) before heading to downtown LA or other neighborhoods.\n\nIf you take I‑5 (fastest) — practical stops\n- Gilroy (garlic/food if you want a quick break)\n- Kettleman City or Harris Ranch (famous steakhouse stop)\n- Tejon Ranch outlets near the Grapevine (shopping, quick break)\n- Pyramid Lake/ghost-town stops are possible but mostly freeway views\n\nSample itineraries\n\n1) One-day drive, scenic highlights (long day)\n- Early SF departure (6–7 am) → Santa Cruz (coffee, 1 hr) → Monterey (lunch, Aquarium optional, 1.5–2 hr) → Big Sur (Bixby Bridge & viewpoints, 1–1.5 hr) → San Simeon (elephant seals) → Santa Barbara arrival late evening. Expect 10–12+ hours including stops.\n\n2) Two-day relaxed coastal trip (recommended)\nDay 1: SF → Half Moon Bay → Santa Cruz → Monterey/Carmel (overnight)\nDay 2: Carmel → Big Sur (Pfeiffer Beach, McWay Falls) → San Simeon or Pismo → Santa Barbara → LA\n- Overnight options: Carmel, Big Sur (if available), or San Luis Obispo/Santa Barbara to split driving times.\n\n3) Three-day scenic + wine-country\nDay 1: SF → Santa Cruz → Monterey/Carmel (explore 17‑Mile Drive)\nDay 2: Carmel → Big Sur → San Simeon → Pismo/Morro Bay (overnight)\nDay 3: Pismo → Solvang (wine tasting) → Santa Barbara → LA\n\nPractical tips\n- Time: Without stops SF→LA on PCH/101 is 8–10 hours; I‑5 ~5–6 hours.\n- Fuel and services: Fill up before Big Sur; limited gas and few restaurants in stretches.\n- Reservations: Hotels in Big Sur and popular towns fill up fast — book ahead. Hearst Castle requires timed tickets.\n- Weather/season: Summer fog near SF; Big Sur can have wind and cooler temps. CA‑1 sometimes closes after storms/landslides.\n- Parking: Popular spots (Pfeiffer Beach, Bixby turnout, McWay Falls) can have limited parking — arrive early.\n- Safety: Drive carefully on winding sections, keep an eye on fuel, cell coverage is spotty in Big Sur.\n\nIf you tell me:\n- how many days you have,\n- whether you prefer beaches, hiking, wine, food stops, or quick travel,\nI’ll draft a detailed day‑by‑day plan with drive times, restaurants and where to stay.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777420669,
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "chatcmpl-DZmbFd2Ooyi5zmVdbSPxGyjtrwUUO",
  "model": "gpt-5-mini-2025-08-07",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 1926,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 704,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 76,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 2002
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5-mini',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-mini",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
The stairwell smelled like old coffee and lemon oil; the landlord kept the cleaner’s bottle on the second landing like a totem. I’d been up and down those stairs enough to know the rhythm of the building—how the pipes sang at night, which door stuck in winter—but the little hallway outside 3B hit a chord I hadn’t heard before: silence so neat it felt deliberate.

Her coat was still on the back of a chair, collar up like a small, pale stack of waves. No sign of forced entry, no overturned furniture, just the slow, inevitable disorder of someone who left thinking she’d be right back. I moved to the chair because detectives move where other people don’t: to pockets. Fingers downed in fabric, searching for lint and receipts and the kind of trash that forgets its own story.

Folded twice, tucked in the inner pocket, was a drawing on cheap paper—crayon blue and stubborn as truth. A stick figure, two dots for eyes, and across the forehead a jagged line of darker crayon. At the bottom, in a child’s hurried script, the name: Jonah. My Jonah. The line across the forehead was the scar I got when I was eight and dared a chain-link fence like a daredevil out of hindsight. A scar nobody I worked with would know about; a scar I had never told anyone about.

The paper smelled faintly of rain and something waxy. I held it up to the single strip of window light and the crayon wax glowed like it had a pulse. The building hummed. Downstairs, someone laughed at nothing. In my chest, something rearranged—an old drawer opened, and a key I’d misplaced years ago slid into my hand. Not a clue so much as an accusation: someone had been in her pockets and had known the exact shape of my face.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The stairwell smelled like old coffee and lemon oil; the landlord kept the cleaner’s bottle on the second landing like a totem. I’d been up and down those stairs enough to know the rhythm of the building—how the pipes sang at night, which door stuck in winter—but the little hallway outside 3B hit a chord I hadn’t heard before: silence so neat it felt deliberate.\n\nHer coat was still on the back of a chair, collar up like a small, pale stack of waves. No sign of forced entry, no overturned furniture, just the slow, inevitable disorder of someone who left thinking she’d be right back. I moved to the chair because detectives move where other people don’t: to pockets. Fingers downed in fabric, searching for lint and receipts and the kind of trash that forgets its own story.\n\nFolded twice, tucked in the inner pocket, was a drawing on cheap paper—crayon blue and stubborn as truth. A stick figure, two dots for eyes, and across the forehead a jagged line of darker crayon. At the bottom, in a child’s hurried script, the name: Jonah. My Jonah. The line across the forehead was the scar I got when I was eight and dared a chain-link fence like a daredevil out of hindsight. A scar nobody I worked with would know about; a scar I had never told anyone about.\n\nThe paper smelled faintly of rain and something waxy. I held it up to the single strip of window light and the crayon wax glowed like it had a pulse. The building hummed. Downstairs, someone laughed at nothing. In my chest, something rearranged—an old drawer opened, and a key I’d misplaced years ago slid into my hand. Not a clue so much as an accusation: someone had been in her pockets and had known the exact shape of my face.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777320157,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMS5kOjcgUQY5W2AZnL6aYVk6pbG",
  "model": "gpt-5-mini-2025-08-07",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 1416,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 1024,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 1435
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5-mini',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-mini",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

```
Recursion is when a function calls itself to solve a smaller instance of the same problem. Two parts are essential:
- Base case: a simple instance that can be answered directly (stops recursion).
- Recursive case: reduces the problem toward the base case by calling the function again.

Simple example — factorial (n! = n × (n−1) × ... × 1)

Python:
def factorial(n):
    if n == 0:           # base case
        return 1
    else:                # recursive case
        return n * factorial(n - 1)

Trace for factorial(4):
factorial(4)
→ 4 * factorial(3)
→ 4 * (3 * factorial(2))
→ 4 * (3 * (2 * factorial(1)))
→ 4 * (3 * (2 * (1 * factorial(0))))
→ 4 * 3 * 2 * 1 * 1 = 24

Another simple example — sum of a list:
def sum_list(lst):
    if not lst:          # base case: empty list
        return 0
    return lst[0] + sum_list(lst[1:])  # recursive case

Notes:
- Always ensure the base case will be reached (otherwise you get infinite recursion and eventually a stack overflow).
- Recursion can make code clearer for problems that naturally break into smaller subproblems (tree traversal, divide-and-conquer). For very deep recursion, consider iterative solutions or tail recursion (if the language optimizes it).
```

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777320181,
    "id": "chatcmpl-DZMSTkAwp2vWq2CMKZi2k62kKUAsk",
    "model": "gpt-5-mini-2025-08-07",
    "obfuscation": "R7nTj",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777320181,
    "id": "chatcmpl-DZMSTkAwp2vWq2CMKZi2k62kKUAsk",
    "model": "gpt-5-mini-2025-08-07",
    "obfuscation": "tvLc",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  "... 318 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777320181,
    "id": "chatcmpl-DZMSTkAwp2vWq2CMKZi2k62kKUAsk",
    "model": "gpt-5-mini-2025-08-07",
    "obfuscation": "mJ",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 711,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 384,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 16,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 727
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-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"
    }
  ]
}'
```

```
Do you mean this calendar week (June 16–22, 2026)? Assuming yes — here are the three top Cloudflare stories from June 16–22, 2026:

- Jun 22, 2026 — Eastern North America fiber cut caused increased error rates/latency and a partial degradation across Cloudflare services; engineers re‑routed traffic and mitigated most impact. ([cloudflarestatus.com](https://www.cloudflarestatus.com/))  
- Jun 16, 2026 — Cloudflare reported degraded availability for some Workers AI models (affecting specific @cf/moonshotai models), which Cloudflare investigated and partially mitigated. ([cloudflarestatus.com](https://www.cloudflarestatus.com/))  
- Jun 17–18, 2026 — Cloudflare launched a Cloudflare One “Design Partner” designation and an AI‑powered toolkit (Cloudflare One Stack) to speed SASE/Zero‑Trust and AI security migrations via select channel partners. ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))

Want me to expand any item (impacts, affected customers, timelines) or fetch more sources?
```

```json
{
  "id": "resp_0353bf77a6c21bf8016a3990db5a388199857704943aa2bb92",
  "object": "response",
  "created_at": 1782157531,
  "model": "gpt-5-mini-2025-08-07",
  "output": [
    {
      "id": "rs_0353bf77a6c21bf8016a3990dbc7748199b7d16f5b4f7e77ca",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0353bf77a6c21bf8016a3990ddd1c4819998796587f7fb4927",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news June 2026",
          "Cloudflare this week June 2026 news Cloudflare breach outage June 2026",
          "Cloudflare IPO news 2026 June 'Cloudflare' 'June 2026' 'announcement'"
        ],
        "query": "Cloudflare news June 2026"
      }
    },
    {
      "id": "rs_0353bf77a6c21bf8016a3990df53dc81999d07483ac94d8c85",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0353bf77a6c21bf8016a3990e126588199944c35eb4b3ce827",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news June 2026",
          "Cloudflare outage June 2026",
          "Cloudflare security incident June 2026"
        ],
        "query": "Cloudflare news June 2026"
      }
    },
    {
      "id": "rs_0353bf77a6c21bf8016a3990e34d508199a4144abcd991086c",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0353bf77a6c21bf8016a3990e43d8c8199bc26696b72289725",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.cloudflarestatus.com/"
      }
    },
    {
      "id": "rs_0353bf77a6c21bf8016a3990e59ae48199b6ba9d1f7337f25c",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0353bf77a6c21bf8016a3990e9b440819998ba8376759a1a54",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare One Design Partner AI toolkit announcement June 2026 Cloudflare press release",
          "Cloudflare 'Design Partner' 'Cloudflare One' June 17 2026 press release"
        ],
        "query": "Cloudflare One Design Partner AI toolkit announcement June 2026 Cloudflare press release"
      }
    },
    {
      "id": "rs_0353bf77a6c21bf8016a3990ec1a1481998070b84eb2a654a0",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "msg_0353bf77a6c21bf8016a3990f499108199bd7021505470de8c",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 386,
              "start_index": 327,
              "title": "Cloudflare Status",
              "url": "https://www.cloudflarestatus.com/"
            },
            {
              "type": "url_citation",
              "end_index": 633,
              "start_index": 574,
              "title": "Cloudflare Status",
              "url": "https://www.cloudflarestatus.com/"
            },
            {
              "type": "url_citation",
              "end_index": 1016,
              "start_index": 852,
              "title": "Cloudflare launches new partner initiative to support AI and SASE adoption",
              "url": "https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai"
            }
          ],
          "logprobs": [],
          "text": "Do you mean this calendar week (June 16–22, 2026)? Assuming yes — here are the three top Cloudflare stories from June 16–22, 2026:\n\n- Jun 22, 2026 — Eastern North America fiber cut caused increased error rates/latency and a partial degradation across Cloudflare services; engineers re‑routed traffic and mitigated most impact. ([cloudflarestatus.com](https://www.cloudflarestatus.com/))  \n- Jun 16, 2026 — Cloudflare reported degraded availability for some Workers AI models (affecting specific @cf/moonshotai models), which Cloudflare investigated and partially mitigated. ([cloudflarestatus.com](https://www.cloudflarestatus.com/))  \n- Jun 17–18, 2026 — Cloudflare launched a Cloudflare One “Design Partner” designation and an AI‑powered toolkit (Cloudflare One Stack) to speed SASE/Zero‑Trust and AI security migrations via select channel partners. ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))\n\nWant me to expand any item (impacts, affected customers, timelines) or fetch more sources?"
        }
      ],
      "role": "assistant"
    }
  ],
  "status": "completed",
  "usage": {
    "input_tokens": 19586,
    "output_tokens": 1796,
    "total_tokens": 21382,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 1344
    }
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1782157560,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 4096,
  "max_tool_calls": null,
  "moderation": null,
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "current_turn",
    "effort": "medium",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "web_search_preview",
      "search_content_types": [
        "text"
      ],
      "search_context_size": "medium",
      "user_location": {
        "type": "approximate",
        "city": null,
        "country": "US",
        "region": null,
        "timezone": null
      }
    }
  ],
  "top_logprobs": 0,
  "top_p": 1,
  "truncation": "disabled",
  "user": null,
  "metadata": {},
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5-mini/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5-mini/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5-mini/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5-mini/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5-mini/#page","headline":"GPT-5 mini","description":"GPT-5 Mini is the lightweight, low-cost variant of GPT-5, well suited to high-volume coding and reasoning tasks.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5-mini/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5 Nano is OpenAI’s smallest GPT-5 variant, optimized for low latency and cheap, high-throughput tasks.
title: GPT-5 nano
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5 nano

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5-nano/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5-nano`

- Third-party
- Zero data retention

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

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 128,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.05</li><li>Output (per 1M tokens)$0.40</li><li>Cached input (per 1M tokens)$0.005</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5-nano',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-nano",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
There are four laws in the standard formulation, but many introductions refer to the three fundamental ones (the Zeroth law is often treated separately). Here are the three most commonly cited (plus a note about the fourth):

Three fundamental laws (often taught as the main ones)
- First Law (Energy conservation): For a closed system, the change in internal energy equals heat added minus work done by the system.
  ΔU = Q − W
  (Q is heat in, W is work done by the system on the surroundings.)

- Second Law (Entropy and direction of processes): In any spontaneous process, the total entropy of an isolated system increases (or stays the same for reversible processes).
  ΔS ≥ 0
  Equivalently, you can state that you cannot convert all heat into work in a cyclic process (Kelvin–Planck) and that heat cannot spontaneously flow from cold to hot (Clausius).

- Third Law (Asymptotic behavior at low temperature): As temperature approaches absolute zero, the entropy of a perfect crystal approaches a constant minimum (often taken as zero). Practically, absolute zero cannot be reached in a finite number of steps (unattainability).

Note on Zeroth Law
- Zeroth Law: If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This provides the definition of temperature: if A and C are in equilibrium, and B and C are in equilibrium, then A and B are in equilibrium. It underpins the concept of temperature as a property that can be compared.

If you want, I can also give a few simple examples illustrating each law.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "There are four laws in the standard formulation, but many introductions refer to the three fundamental ones (the Zeroth law is often treated separately). Here are the three most commonly cited (plus a note about the fourth):\n\nThree fundamental laws (often taught as the main ones)\n- First Law (Energy conservation): For a closed system, the change in internal energy equals heat added minus work done by the system.\n  ΔU = Q − W\n  (Q is heat in, W is work done by the system on the surroundings.)\n\n- Second Law (Entropy and direction of processes): In any spontaneous process, the total entropy of an isolated system increases (or stays the same for reversible processes).\n  ΔS ≥ 0\n  Equivalently, you can state that you cannot convert all heat into work in a cyclic process (Kelvin–Planck) and that heat cannot spontaneously flow from cold to hot (Clausius).\n\n- Third Law (Asymptotic behavior at low temperature): As temperature approaches absolute zero, the entropy of a perfect crystal approaches a constant minimum (often taken as zero). Practically, absolute zero cannot be reached in a finite number of steps (unattainability).\n\nNote on Zeroth Law\n- Zeroth Law: If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This provides the definition of temperature: if A and C are in equilibrium, and B and C are in equilibrium, then A and B are in equilibrium. It underpins the concept of temperature as a property that can be compared.\n\nIf you want, I can also give a few simple examples illustrating each law.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319975,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMP9juESnbcNqeQyt9DdJmF9QM0t",
  "model": "gpt-5-nano-2025-08-07",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 1307,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 960,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 15,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 1322
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-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"
    }
  ]
}'
```

````
You can read a JSON file in Python using the built-in json module. Open the file and use json.load to parse it into Python objects (usually dictionaries or lists).

A simple example:
- read a JSON object from a file into a Python dict

```python
import json

with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

print(type(data))  # dict or list
print(data)
```

Notes and variations:
- If you have a JSON string (not a file), use json.loads:
```python
import json

s = '{"name": "Alice", "age": 30}'
data = json.loads(s)
```

- Handle errors:
```python
import json

try:
    with open('data.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
except json.JSONDecodeError as e:
    print("Invalid JSON:", e)
```

- Use pathlib for nicer path handling:
```python
from pathlib import Path
import json

p = Path('data.json')
with p.open('r', encoding='utf-8') as f:
    data = json.load(f)
```

- Large files: json.load reads the whole file into memory. If the file is huge, consider:
  - processing a newline-delimited JSON (NDJSON) file line by line
  - or using a streaming parser like ijson

Example for NDJSON:
```python
import json

with open('data.ndjson', 'r', encoding='utf-8') as f:
    for line in f:
        obj = json.loads(line)
        # process obj
```

- Optional customization: you can use object_hook to customize how dicts are turned into objects:
```python
import json
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

def decode_person(d):
    if 'name' in d and 'age' in d:
        return Person(d['name'], d['age'])
    return d

with open('people.json', 'r', encoding='utf-8') as f:
    data = json.load(f, object_hook=decode_person)
```

If you tell me the shape of your JSON (dict vs list, any large size concerns), I can tailor the example.
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "You can read a JSON file in Python using the built-in json module. Open the file and use json.load to parse it into Python objects (usually dictionaries or lists).\n\nA simple example:\n- read a JSON object from a file into a Python dict\n\n```python\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as f:\n    data = json.load(f)\n\nprint(type(data))  # dict or list\nprint(data)\n```\n\nNotes and variations:\n- If you have a JSON string (not a file), use json.loads:\n```python\nimport json\n\ns = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(s)\n```\n\n- Handle errors:\n```python\nimport json\n\ntry:\n    with open('data.json', 'r', encoding='utf-8') as f:\n        data = json.load(f)\nexcept json.JSONDecodeError as e:\n    print(\"Invalid JSON:\", e)\n```\n\n- Use pathlib for nicer path handling:\n```python\nfrom pathlib import Path\nimport json\n\np = Path('data.json')\nwith p.open('r', encoding='utf-8') as f:\n    data = json.load(f)\n```\n\n- Large files: json.load reads the whole file into memory. If the file is huge, consider:\n  - processing a newline-delimited JSON (NDJSON) file line by line\n  - or using a streaming parser like ijson\n\nExample for NDJSON:\n```python\nimport json\n\nwith open('data.ndjson', 'r', encoding='utf-8') as f:\n    for line in f:\n        obj = json.loads(line)\n        # process obj\n```\n\n- Optional customization: you can use object_hook to customize how dicts are turned into objects:\n```python\nimport json\nfrom dataclasses import dataclass\n\n@dataclass\nclass Person:\n    name: str\n    age: int\n\ndef decode_person(d):\n    if 'name' in d and 'age' in d:\n        return Person(d['name'], d['age'])\n    return d\n\nwith open('people.json', 'r', encoding='utf-8') as f:\n    data = json.load(f, object_hook=decode_person)\n```\n\nIf you tell me the shape of your JSON (dict vs list, any large size concerns), I can tailor the example.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319979,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMPDVD85J31ue22YYuw6KL8rE5q5",
  "model": "gpt-5-nano-2025-08-07",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 2035,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 1536,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 2065
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-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"
    }
  ]
}'
```

```
Great question. Here are some standout stops for two popular SF-to-LA routes. Pick the vibe you want and I can tailor a day-by-day plan.

Option 1 — Scenic Pacific Coast Highway (CA-1 / US-101)
- Santa Cruz: Beach boardwalk, Wharf, redwood forests nearby (Henry Cowell Redwoods State Park).
- Monterey: Monterey Bay Aquarium, Cannery Row, Old Fisherman’s Wharf; consider the 17-Mile Drive for spectacular coastal scenery.
- Carmel-by-the-Sea: Charming village, art galleries, white-sand beaches; great for a stroll and lunch.
- Big Sur: Breathtaking coastline. Must-see spots include Bixby Creek Bridge, Pfeiffer Beach, and McWay Falls (Julia Pfeiffer Burns State Park).
- San Simeon: Hearst Castle tours (book in advance); possible elephant seal viewing at Piedras Blancas Beach.
- Morro Bay / San Luis Obispo: Morro Rock views, water activities in Morro Bay; stroll SLO’s downtown and Bubblegum Alley.
- Pismo Beach or Santa Barbara: Long beaches, pier, and laid-back coastal vibes; Santa Barbara adds Mission, Stearns Wharf, and the Funk Zone wine area (or detour to Solvang, a Danish-style village).
- Santa Barbara to Malibu/Ventura: Beautiful coastal towns and beaches; good for a lunch stop.
- Malibu to Santa Monica / Venice Beach: Classic Southern California coast with great seafood spots and iconic piers.
- Los Angeles area: If you’re ending in LA, you’ll have countless options for museums, beaches, and dining.

Option 2 — Inland I-5 Corridor (fastest, more practical for a quick trip)
- Gilroy: Garlic farms and a solid stop for a quick bite or a stroll through the outlets.
- Harris Ranch (Coalinga area): Famous steakhouse lunch stop; a handy fuel/thematic break.
- Kettleman City / Buttonwillow: Quick rest stops with gas, snacks, and bathrooms.
- Bakersfield: A larger stop with a few cultural options (Buck Owens Crystal Palace, Kern County Museum, downtown stroll).
- (Optional detour if you want a wine break) Paso Robles or Santa Ynez wine country a short detour off the main I-5 route.
- Santa Clarita / Valencia (near LA): If you want a theme-park or city-break break before hitting the LA basin.
- Then onward to the Los Angeles area (Malibu, Santa Monica, Venice, or downtown LA depending on your end point).

A few ready-made itinerary ideas
- 3-day coastal loop (full coast life, slower pace):
  Day 1: SF → Santa Cruz → Monterey/Carmel (overnight in Monterey or Carmel)
  Day 2: Big Sur coast → San Simeon (Hearst Castle) → Morro Bay (overnight)
  Day 3: Morro Bay → Santa Barbara → Malibu/Santa Monica (overnight or continue to LA)
- 4–5 days for a relaxed coastal trip:
  Add: Pismo Beach, Santa Barbara wine country detour (Solvang nearby), a longer stay in Santa Monica or Malibu, plus time in LA’s beach areas or neighborhoods.

Tips to make it smooth
- Book ahead for popular spots (Hearst Castle tours, 17-Mile Drive if you plan to stop there).
- Check CA-1 conditions in winter and after storms; some sections can close or have slower speeds due to rockfalls.
- If you’re doing the coast, allow extra time for scenic stops and viewpoints.
- Bring layers, especially along the coast where it can be cool and windy, even on sunny days.
- For meals, Harris Ranch is a classic inland lunch stop on I-5; along the coast you’ll find many casual to upscale options in each town.

Would you like me to tailor a day-by-day plan based on:
- How many days you have
- Whether you prefer the coastal route or the inland route
- Your interests (wine, hiking, beaches, food, photography)
- Any must-see stops or budget/overnight constraints?
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Great question. Here are some standout stops for two popular SF-to-LA routes. Pick the vibe you want and I can tailor a day-by-day plan.\n\nOption 1 — Scenic Pacific Coast Highway (CA-1 / US-101)\n- Santa Cruz: Beach boardwalk, Wharf, redwood forests nearby (Henry Cowell Redwoods State Park).\n- Monterey: Monterey Bay Aquarium, Cannery Row, Old Fisherman’s Wharf; consider the 17-Mile Drive for spectacular coastal scenery.\n- Carmel-by-the-Sea: Charming village, art galleries, white-sand beaches; great for a stroll and lunch.\n- Big Sur: Breathtaking coastline. Must-see spots include Bixby Creek Bridge, Pfeiffer Beach, and McWay Falls (Julia Pfeiffer Burns State Park).\n- San Simeon: Hearst Castle tours (book in advance); possible elephant seal viewing at Piedras Blancas Beach.\n- Morro Bay / San Luis Obispo: Morro Rock views, water activities in Morro Bay; stroll SLO’s downtown and Bubblegum Alley.\n- Pismo Beach or Santa Barbara: Long beaches, pier, and laid-back coastal vibes; Santa Barbara adds Mission, Stearns Wharf, and the Funk Zone wine area (or detour to Solvang, a Danish-style village).\n- Santa Barbara to Malibu/Ventura: Beautiful coastal towns and beaches; good for a lunch stop.\n- Malibu to Santa Monica / Venice Beach: Classic Southern California coast with great seafood spots and iconic piers.\n- Los Angeles area: If you’re ending in LA, you’ll have countless options for museums, beaches, and dining.\n\nOption 2 — Inland I-5 Corridor (fastest, more practical for a quick trip)\n- Gilroy: Garlic farms and a solid stop for a quick bite or a stroll through the outlets.\n- Harris Ranch (Coalinga area): Famous steakhouse lunch stop; a handy fuel/thematic break.\n- Kettleman City / Buttonwillow: Quick rest stops with gas, snacks, and bathrooms.\n- Bakersfield: A larger stop with a few cultural options (Buck Owens Crystal Palace, Kern County Museum, downtown stroll).\n- (Optional detour if you want a wine break) Paso Robles or Santa Ynez wine country a short detour off the main I-5 route.\n- Santa Clarita / Valencia (near LA): If you want a theme-park or city-break break before hitting the LA basin.\n- Then onward to the Los Angeles area (Malibu, Santa Monica, Venice, or downtown LA depending on your end point).\n\nA few ready-made itinerary ideas\n- 3-day coastal loop (full coast life, slower pace):\n  Day 1: SF → Santa Cruz → Monterey/Carmel (overnight in Monterey or Carmel)\n  Day 2: Big Sur coast → San Simeon (Hearst Castle) → Morro Bay (overnight)\n  Day 3: Morro Bay → Santa Barbara → Malibu/Santa Monica (overnight or continue to LA)\n- 4–5 days for a relaxed coastal trip:\n  Add: Pismo Beach, Santa Barbara wine country detour (Solvang nearby), a longer stay in Santa Monica or Malibu, plus time in LA’s beach areas or neighborhoods.\n\nTips to make it smooth\n- Book ahead for popular spots (Hearst Castle tours, 17-Mile Drive if you plan to stop there).\n- Check CA-1 conditions in winter and after storms; some sections can close or have slower speeds due to rockfalls.\n- If you’re doing the coast, allow extra time for scenic stops and viewpoints.\n- Bring layers, especially along the coast where it can be cool and windy, even on sunny days.\n- For meals, Harris Ranch is a classic inland lunch stop on I-5; along the coast you’ll find many casual to upscale options in each town.\n\nWould you like me to tailor a day-by-day plan based on:\n- How many days you have\n- Whether you prefer the coastal route or the inland route\n- Your interests (wine, hiking, beaches, food, photography)\n- Any must-see stops or budget/overnight constraints?",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777421265,
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "chatcmpl-DZmkrO6ReFPBgbE0saPZqQIRxy3pu",
  "model": "gpt-5-nano-2025-08-07",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 5919,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 5056,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 76,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 5995
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5-nano',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-nano",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
The rain turned the city into a bleary watercolor, every streetlight smeared into halos that bled down the sidewalks. Detective Isla Voss slipped into the alley behind the Glasswright Gallery, where the security guard stood under a lone lamp, shaking out a soggy notebook. The building loomed quiet and serene, the way a locked box does after a storm. Inside, something had happened, but nothing obvious remained.

“Not a thing missing,” the guard said, eyes wary. “Doors were closed, windows intact. Nothing broken, nothing stolen. Just… not right.”

Isla nodded, stepping under the gallery’s arched doorway where the vestibule held a stale room-temperature hush. The air smelled faintly of varnish and rain—less a crime scene and more a paused painting. The security alarm blinked from red to green as she moved past the lobby into the main hall, where the telltale tremor of a disturbance usually left a visible trace. Here, though, the room wore its normalities as if nothing at all had happened.

In the center of the hall, where the monumental skylight draped the floor in pale glass, lay the oddity: a perfect ring of soot on the white marble, as if someone had circled the space with a tiny, patient brush of charcoal. No dent in the glass, no broken frame, no shard of glass anywhere to indicate a break-in. Just that ring. And inside the ring, the soot had arranged itself into a meticulous, minuscule map—an urban silhouette, a cityscape drawn in black granules and negative space.

Isla crouched, pulled out her ultraviolet flashlight, and leaned close. The soot glowed faintly blue under the peculiar light, the color of a firefly trapped in dusk. The ring itself wasn’t random; the pattern suggested streets, rooftops, a river that ran like a blue thread through the middle of the composition. It wasn’t a doodle, not a mere prank. It was a clue, and a strange one at that.

The gallery’s curator, a thin man with a voice like a piano wire, appeared at Isla’s shoulder. “You see?” he whispered. “We deal with paintings here, not disguises. But this—this feels like a message.”

Isla stood, letting the light wash over the ring again. A city map drawn in soot—how could that be? She’d seen fingerprints that spelled out names, footprints that traced a route, but a map formed by ash and pigment and gravity’s small mercy was something else entirely. It demanded a different kind of attention, the sort she reserved for echoes and memory rather than objects.

“Who had access to this room after hours?” she asked the curator, keeping her tone light, as if discussing a curious trick rather than a possible crime.

The curator scanned the room, as if the answer might be hiding in the corners, the way a receipt might hide between two books on a shelf. “We lock up at six. The security feed is clean. The assistant, Mina, is the only other person who might have wandered in—she cleans up after close. But Mina’s never late, never stops to sketch.” He hesitated. “And she’s… unreliable to strangers’ eyes, if you’ll forgive the honesty.”

Isla offered a small, almost-smile. “People aren’t always what they seem. We’ll talk to Mina. And the feed will tell us whether someone else tried to tamper with the room. But tell me, why a map? Why this room?”

The curator shrugged, his lips thinning. “We publish nothing here that could draw a map of the city exactly. It’s too precise. The only thing that’s ever aligned as neatly as this is a plan for a private tour—one that never happened, not officially.”

Her eyes drifted to the ring again. The map was too precise to be a prank, too delicate to be a mere coincidence. That was good. Clues should be precise enough to be trusted, but not so obvious they screamed.

Isla stood slowly, letting another breath of rain-salted air slip past her lips. She looked up at the skylight, where the rain pattered on the glass in a pattern that made the room feel almost musical. The glow from the map deepened when she traced a line with her finger, right along the imagined avenue that would pass beneath the museum’s floor if the city’s hidden corridors existed.

“Tell me about the last event here,” she said, her voice deliberately casual. “The last exhibit, the last guest, the last thing anyone talked about.”

The curator drew in a sharp breath. “A storm of artists. A show that never quite ended. The last thing—the piece that the thief would want: a single painting—a landscape of a street in a city that isn’t ours, a city made of shadows and rumor. The piece was insured for a fortune, yet nobody claimed it as theirs.”

A city map in soot, a password of sorts etched without anyone realizing. Isla turned the ring of ashes, watching the map shift as the light moved, the river’s blue thread glimmering more clearly at one angle than another. The clue wasn’t merely a map; it was a sign that someone who knew the city intimately had walked into this room and left a message that only a person with that same intimacy could decipher.

Her instincts nudged her toward the back corridor, where the staff’s break room met the service stairs. The door had a thin smear of dust along its edge, the kind that builds up when a space isn’t used often enough by more than two or three people. She pressed her gloved finger to the dust, then to her lips, a quick, almost subconscious ritual. The dust retained a faint metallic tang—not obvious, but clear to someone who paid attention to such traces.

Back in the main hall, the guard spoke up again. “Mina, you’re thinking Mina, right? She’s the one who cleans the room and who night shifts some weeks. If anyone could conjure a map out of ash, it would be her.”

Isla considered Mina’s possible motives with the cool precision of a clockmaker adjusting a gear. A map drawn in soot could be a confession, a direction, or a trap. An invitation to follow a path that only someone who knows the city’s more intimate lies would recognize.

She walked toward the break room doorway, every step measured, listening for the smallest sound—a floorboard sigh, a shifted chair, the whisper of a lung trying not to betray fear. In the quiet, she heard not a noise but a breath—someone’s subtle exhale, a sign of life where there shouldn’t be life in the dead of night.

Inside, Mina stood with her back to the door, cleaning a coffee mug with a rag that had seen better days. The mug’s handle rattled faintly as she moved, the sound crisp in the hushed room.

“Good evening,” Isla said, still almost polite, though the room’s air felt charged, like a string about to snap.

Mina turned slowly, eyes widening at the sight of the glow from the map still faintly visible on the marble floor. She swallowed, the tremor in her throat betraying her attempt at calm. “I didn’t mean to—” she began, but trailed off when Isla raised a hand.

“Tell me about the map,” Isla said softly. “Why draw a city here, in a place that doesn’t even belong to this room?”

Mina’s lips pressed together. She looked at the map, then at Isla, as if weighing whether honesty would survive in the space between them. When she spoke, her voice was little more than a whisper, but it carried the weight of a confession long rehearsed in the quiet corners of the city.

And then the room’s lights flickered, briefly bathing them in a cold, blue glare. The map’s glow intensified on the marble floor, suggesting a route, a password, a path through the city’s hidden veins. It wasn’t a trap, not yet. It was an invitation.

Isla realized then what the clue was truly asking: not who would steal or why, but where to begin. The map wasn’t just a message; it was a map of the city’s memory, drawn by someone who knew where every shadow slept and which doors remained unlocked after hours.

In that moment, she understood that the unusual clue wasn’t merely the soot, or the glow of the map, or even Mina’s whispered confession. It was the promise of a trail that stretched beyond the gallery walls and into the heart of a city that spoke in smoke, light, and memory. And she intended to follow it, one precise step at a time.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The rain turned the city into a bleary watercolor, every streetlight smeared into halos that bled down the sidewalks. Detective Isla Voss slipped into the alley behind the Glasswright Gallery, where the security guard stood under a lone lamp, shaking out a soggy notebook. The building loomed quiet and serene, the way a locked box does after a storm. Inside, something had happened, but nothing obvious remained.\n\n“Not a thing missing,” the guard said, eyes wary. “Doors were closed, windows intact. Nothing broken, nothing stolen. Just… not right.”\n\nIsla nodded, stepping under the gallery’s arched doorway where the vestibule held a stale room-temperature hush. The air smelled faintly of varnish and rain—less a crime scene and more a paused painting. The security alarm blinked from red to green as she moved past the lobby into the main hall, where the telltale tremor of a disturbance usually left a visible trace. Here, though, the room wore its normalities as if nothing at all had happened.\n\nIn the center of the hall, where the monumental skylight draped the floor in pale glass, lay the oddity: a perfect ring of soot on the white marble, as if someone had circled the space with a tiny, patient brush of charcoal. No dent in the glass, no broken frame, no shard of glass anywhere to indicate a break-in. Just that ring. And inside the ring, the soot had arranged itself into a meticulous, minuscule map—an urban silhouette, a cityscape drawn in black granules and negative space.\n\nIsla crouched, pulled out her ultraviolet flashlight, and leaned close. The soot glowed faintly blue under the peculiar light, the color of a firefly trapped in dusk. The ring itself wasn’t random; the pattern suggested streets, rooftops, a river that ran like a blue thread through the middle of the composition. It wasn’t a doodle, not a mere prank. It was a clue, and a strange one at that.\n\nThe gallery’s curator, a thin man with a voice like a piano wire, appeared at Isla’s shoulder. “You see?” he whispered. “We deal with paintings here, not disguises. But this—this feels like a message.”\n\nIsla stood, letting the light wash over the ring again. A city map drawn in soot—how could that be? She’d seen fingerprints that spelled out names, footprints that traced a route, but a map formed by ash and pigment and gravity’s small mercy was something else entirely. It demanded a different kind of attention, the sort she reserved for echoes and memory rather than objects.\n\n“Who had access to this room after hours?” she asked the curator, keeping her tone light, as if discussing a curious trick rather than a possible crime.\n\nThe curator scanned the room, as if the answer might be hiding in the corners, the way a receipt might hide between two books on a shelf. “We lock up at six. The security feed is clean. The assistant, Mina, is the only other person who might have wandered in—she cleans up after close. But Mina’s never late, never stops to sketch.” He hesitated. “And she’s… unreliable to strangers’ eyes, if you’ll forgive the honesty.”\n\nIsla offered a small, almost-smile. “People aren’t always what they seem. We’ll talk to Mina. And the feed will tell us whether someone else tried to tamper with the room. But tell me, why a map? Why this room?”\n\nThe curator shrugged, his lips thinning. “We publish nothing here that could draw a map of the city exactly. It’s too precise. The only thing that’s ever aligned as neatly as this is a plan for a private tour—one that never happened, not officially.”\n\nHer eyes drifted to the ring again. The map was too precise to be a prank, too delicate to be a mere coincidence. That was good. Clues should be precise enough to be trusted, but not so obvious they screamed.\n\nIsla stood slowly, letting another breath of rain-salted air slip past her lips. She looked up at the skylight, where the rain pattered on the glass in a pattern that made the room feel almost musical. The glow from the map deepened when she traced a line with her finger, right along the imagined avenue that would pass beneath the museum’s floor if the city’s hidden corridors existed.\n\n“Tell me about the last event here,” she said, her voice deliberately casual. “The last exhibit, the last guest, the last thing anyone talked about.”\n\nThe curator drew in a sharp breath. “A storm of artists. A show that never quite ended. The last thing—the piece that the thief would want: a single painting—a landscape of a street in a city that isn’t ours, a city made of shadows and rumor. The piece was insured for a fortune, yet nobody claimed it as theirs.”\n\nA city map in soot, a password of sorts etched without anyone realizing. Isla turned the ring of ashes, watching the map shift as the light moved, the river’s blue thread glimmering more clearly at one angle than another. The clue wasn’t merely a map; it was a sign that someone who knew the city intimately had walked into this room and left a message that only a person with that same intimacy could decipher.\n\nHer instincts nudged her toward the back corridor, where the staff’s break room met the service stairs. The door had a thin smear of dust along its edge, the kind that builds up when a space isn’t used often enough by more than two or three people. She pressed her gloved finger to the dust, then to her lips, a quick, almost subconscious ritual. The dust retained a faint metallic tang—not obvious, but clear to someone who paid attention to such traces.\n\nBack in the main hall, the guard spoke up again. “Mina, you’re thinking Mina, right? She’s the one who cleans the room and who night shifts some weeks. If anyone could conjure a map out of ash, it would be her.”\n\nIsla considered Mina’s possible motives with the cool precision of a clockmaker adjusting a gear. A map drawn in soot could be a confession, a direction, or a trap. An invitation to follow a path that only someone who knows the city’s more intimate lies would recognize.\n\nShe walked toward the break room doorway, every step measured, listening for the smallest sound—a floorboard sigh, a shifted chair, the whisper of a lung trying not to betray fear. In the quiet, she heard not a noise but a breath—someone’s subtle exhale, a sign of life where there shouldn’t be life in the dead of night.\n\nInside, Mina stood with her back to the door, cleaning a coffee mug with a rag that had seen better days. The mug’s handle rattled faintly as she moved, the sound crisp in the hushed room.\n\n“Good evening,” Isla said, still almost polite, though the room’s air felt charged, like a string about to snap.\n\nMina turned slowly, eyes widening at the sight of the glow from the map still faintly visible on the marble floor. She swallowed, the tremor in her throat betraying her attempt at calm. “I didn’t mean to—” she began, but trailed off when Isla raised a hand.\n\n“Tell me about the map,” Isla said softly. “Why draw a city here, in a place that doesn’t even belong to this room?”\n\nMina’s lips pressed together. She looked at the map, then at Isla, as if weighing whether honesty would survive in the space between them. When she spoke, her voice was little more than a whisper, but it carried the weight of a confession long rehearsed in the quiet corners of the city.\n\nAnd then the room’s lights flickered, briefly bathing them in a cold, blue glare. The map’s glow intensified on the marble floor, suggesting a route, a password, a path through the city’s hidden veins. It wasn’t a trap, not yet. It was an invitation.\n\nIsla realized then what the clue was truly asking: not who would steal or why, but where to begin. The map wasn’t just a message; it was a map of the city’s memory, drawn by someone who knew where every shadow slept and which doors remained unlocked after hours.\n\nIn that moment, she understood that the unusual clue wasn’t merel
... response truncated ...
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5-nano',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-nano",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

```
Recursion is when a function solves a problem by calling itself to solve a smaller version of the same problem, and it uses a simple base case to stop.

Key ideas:
- Base case: a simple, known result that ends the recursion.
- Recursive step: the function calls itself with a smaller problem.
- Each call adds a new frame to the call stack, and results are returned back up once the base case is reached.
- Recursion eventually terminates when the base case is reached.

Simple example: factorial
- The factorial of n (written n!) is defined as:
  - n! = n × (n-1)! for n > 0
  - 0! = 1 (base case)

Example trace for n = 4:
- 4! = 4 × 3!
- 3! = 3 × 2!
- 2! = 2 × 1!
- 1! = 1 × 0!
- 0! = 1
Now compute back up:
- 1! = 1
- 2! = 2 × 1 = 2
- 3! = 3 × 2 = 6
- 4! = 4 × 6 = 24

Python code:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))  # 120

Notes:
- Recursion is elegant and easy to express for problems like factorial, tree traversals, or divide-and-conquer tasks.
- It can use more memory due to the call stack and can hit a recursion depth limit for large inputs.
- An iterative version (loop) can be more memory-efficient if needed. Example:

def factorial_iter(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

If you’d like, I can tailor a recursion example to a different problem.
```

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777320010,
    "id": "chatcmpl-DZMPiZzou66Tn3iPi5undITqdrV1R",
    "model": "gpt-5-nano-2025-08-07",
    "obfuscation": "QaiOK",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777320010,
    "id": "chatcmpl-DZMPiZzou66Tn3iPi5undITqdrV1R",
    "model": "gpt-5-nano-2025-08-07",
    "obfuscation": "3fFP",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  "... 422 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777320010,
    "id": "chatcmpl-DZMPiZzou66Tn3iPi5undITqdrV1R",
    "model": "gpt-5-nano-2025-08-07",
    "obfuscation": "mfrEA02JD9ew9sU",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 2031,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 1600,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 16,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 2047
    }
  }
]
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5-nano/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5-nano/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5-nano/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5-nano/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5-nano/#page","headline":"GPT-5 nano","description":"GPT-5 Nano is OpenAI’s smallest GPT-5 variant, optimized for low latency and cheap, high-throughput tasks.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5-nano/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5.1 is OpenAI’s incremental improvement over GPT-5, with stronger coding, reasoning, and writing.
title: GPT-5.1
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5.1

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5.1/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5.1`

- Third-party
- Zero data retention

GPT-5.1 is OpenAI’s incremental improvement over GPT-5, with stronger coding, reasoning, and writing.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 128,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$1.25</li><li>Output (per 1M tokens)$10.00</li><li>Cached input (per 1M tokens)$0.125</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5.1',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.1",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The three classical laws of thermodynamics (often listed as 0th–3rd, but you asked for three) are:

**First Law (Conservation of Energy)**  
Energy cannot be created or destroyed, only transformed from one form to another.  
Mathematically for a system:  
\[
\Delta U = Q - W
\]  
where ΔU is change in internal energy, Q is heat added to the system, and W is work done by the system.

**Second Law (Direction of Processes / Entropy)**  
The total entropy of an isolated system never decreases; it either increases or, in an ideal reversible process, stays constant.  
This implies:
- Heat flows spontaneously from hot to cold, not the reverse.
- No heat engine can be 100% efficient.

**Third Law (Absolute Zero and Entropy)**  
As the temperature of a perfect crystalline substance approaches absolute zero (0 K), its entropy approaches a minimum value (often taken as zero).  
Consequence: It is impossible, by any finite number of steps, to cool a system all the way to absolute zero.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The three classical laws of thermodynamics (often listed as 0th–3rd, but you asked for three) are:\n\n**First Law (Conservation of Energy)**  \nEnergy cannot be created or destroyed, only transformed from one form to another.  \nMathematically for a system:  \n\\[\n\\Delta U = Q - W\n\\]  \nwhere ΔU is change in internal energy, Q is heat added to the system, and W is work done by the system.\n\n**Second Law (Direction of Processes / Entropy)**  \nThe total entropy of an isolated system never decreases; it either increases or, in an ideal reversible process, stays constant.  \nThis implies:\n- Heat flows spontaneously from hot to cold, not the reverse.\n- No heat engine can be 100% efficient.\n\n**Third Law (Absolute Zero and Entropy)**  \nAs the temperature of a perfect crystalline substance approaches absolute zero (0 K), its entropy approaches a minimum value (often taken as zero).  \nConsequence: It is impossible, by any finite number of steps, to cool a system all the way to absolute zero.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319793,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMDjkjm2G9LOk72IMGhbyvdpRFX",
  "model": "gpt-5.1-2025-11-13",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 236,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 15,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 251
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.1',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.1",
  "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"
    }
  ]
}'
```

````
To read a JSON file in Python, use the built-in `json` module.

### Basic example

```python
import json

# Path to your JSON file
file_path = "data.json"

with open(file_path, "r", encoding="utf-8") as f:
    data = json.load(f)

print(data)
print(type(data))  # usually dict or list
```

- `json.load(f)` reads JSON from an open file object.
- The result is usually a Python `dict` (for JSON objects) or `list` (for JSON arrays).

### If you have JSON as a string

```python
import json

json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)  # note the "s" at the end
```

If you show me a sample of your JSON file, I can suggest the exact code to access its fields.
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "To read a JSON file in Python, use the built-in `json` module.\n\n### Basic example\n\n```python\nimport json\n\n# Path to your JSON file\nfile_path = \"data.json\"\n\nwith open(file_path, \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n\nprint(data)\nprint(type(data))  # usually dict or list\n```\n\n- `json.load(f)` reads JSON from an open file object.\n- The result is usually a Python `dict` (for JSON objects) or `list` (for JSON arrays).\n\n### If you have JSON as a string\n\n```python\nimport json\n\njson_str = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_str)  # note the \"s\" at the end\n```\n\nIf you show me a sample of your JSON file, I can suggest the exact code to access its fields.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319793,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMDAa1J4qoS42vzFJjxeGGOfqiW",
  "model": "gpt-5.1-2025-11-13",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 200,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 230
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.1',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.1",
  "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"
    }
  ]
}'
```

```
Here are two main route options with good stops between San Francisco and Los Angeles. You can mix and match depending on your time.

---

## 1. Scenic Coastal Route (Highway 1 / Pacific Coast Highway)

Best if you have at least 1.5–2 days and want views and small towns.

### Between SF and Monterey / Carmel
- **Half Moon Bay**  
  - Quick stop: Harbor, coastal bluffs, coffee on Main St.
- **Pescadero**  
  - Tiny town, great sandwiches and baked goods at Arcangeli Grocery.
  - Pigeon Point Lighthouse viewpoint nearby.

### Monterey & Carmel-by-the-Sea
- **Monterey**  
  - Cannery Row & Old Fisherman’s Wharf (touristy but atmospheric).  
  - Monterey Bay Aquarium (needs 2–3 hours minimum).
- **17-Mile Drive** (between Pacific Grove & Carmel)  
  - Paid scenic drive with coastal lookouts, Lone Cypress, golf course views.
- **Carmel-by-the-Sea**  
  - Walkable village, art galleries, Carmel Beach at sunset.

### Big Sur Area (spectacular coastline)
Plan extra time between Carmel and Ragged Point.

- **Bixby Creek Bridge**  
  - Iconic photo stop; small turnouts on either side.
- **Pfeiffer Beach**  
  - Known for purple-ish sand and rock arch (watch for narrow access road).
- **Julia Pfeiffer Burns State Park / McWay Falls**  
  - Short walk to a viewpoint of a waterfall onto the beach.
- **Nepenthe**  
  - Restaurant with incredible views; good for a snack or drink.
- **Ragged Point**  
  - Scenic overlook, café, restrooms; last dramatic cliff views heading south.

### San Simeon to Pismo Beach
- **Hearst Castle (San Simeon)**  
  - Mansion tours on a hill with ocean views (reserve ahead if possible).
- **Elephant Seal Vista Point (Piedras Blancas)**  
  - Large colony of elephant seals right off the road.
- **Cambria**  
  - Cute town, Moonstone Beach boardwalk, wine tasting.
- **Morro Bay**  
  - Harbor town with Morro Rock; good lunch spot on the water.
- **Pismo Beach**  
  - Classic beach town; pier, dunes, clam chowder (e.g., Splash Café).

### Central Coast to LA
- **San Luis Obispo (SLO)**  
  - Lively college town; great for dinner or an overnight.
- **Solvang**  
  - Danish-style village with bakeries and windmills.
- **Santa Barbara**  
  - Beachfront, Stearns Wharf, State Street shops and restaurants.
- **Malibu**  
  - Coastal pullouts, Zuma Beach, Malibu Pier (cafés, views).
- Continue along PCH into **Santa Monica** and **LA**.

---

## 2. Faster Inland Route (US-101 or I-5)

Best if you want to get there quicker but still have a couple of interesting stops.

### Via US-101 (balanced speed + scenery)
- **Gilroy** – Outlet shopping; garlic-themed everything.  
- **Paso Robles** – Wine country; nice downtown square and tasting rooms.  
- Then connect back to the coast near **San Luis Obispo** and follow the SLO → Santa Barbara → Malibu stops above.

### Via I-5 (fastest, most direct)
More utilitarian, but:

- **Harris Ranch (Coalinga)** – Big steakhouse, hotel, and rest stop.  
- **Tejon Pass / Fort Tejon** – Mountain views as you cross into SoCal.

---

## Quick Templates Depending on Time

- **1 long day, some scenery:**  
  SF → Monterey lunch → Bixby Bridge / McWay Falls stops → San Simeon seals → SLO dinner → LA.

- **2 days, overnight on Central Coast:**  
  Day 1: SF → Half Moon Bay → Monterey → Big Sur sights → overnight in Cambria or SLO.  
  Day 2: SLO → Pismo → Santa Barbara (lunch / explore) → Malibu → LA.

If you tell me:
- which month you’re going,
- how many days you have,
- whether you care more about food, hikes, beaches, or towns,

I can turn this into a specific, timed itinerary with suggested departure times and where to stay.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Here are two main route options with good stops between San Francisco and Los Angeles. You can mix and match depending on your time.\n\n---\n\n## 1. Scenic Coastal Route (Highway 1 / Pacific Coast Highway)\n\nBest if you have at least 1.5–2 days and want views and small towns.\n\n### Between SF and Monterey / Carmel\n- **Half Moon Bay**  \n  - Quick stop: Harbor, coastal bluffs, coffee on Main St.\n- **Pescadero**  \n  - Tiny town, great sandwiches and baked goods at Arcangeli Grocery.\n  - Pigeon Point Lighthouse viewpoint nearby.\n\n### Monterey & Carmel-by-the-Sea\n- **Monterey**  \n  - Cannery Row & Old Fisherman’s Wharf (touristy but atmospheric).  \n  - Monterey Bay Aquarium (needs 2–3 hours minimum).\n- **17-Mile Drive** (between Pacific Grove & Carmel)  \n  - Paid scenic drive with coastal lookouts, Lone Cypress, golf course views.\n- **Carmel-by-the-Sea**  \n  - Walkable village, art galleries, Carmel Beach at sunset.\n\n### Big Sur Area (spectacular coastline)\nPlan extra time between Carmel and Ragged Point.\n\n- **Bixby Creek Bridge**  \n  - Iconic photo stop; small turnouts on either side.\n- **Pfeiffer Beach**  \n  - Known for purple-ish sand and rock arch (watch for narrow access road).\n- **Julia Pfeiffer Burns State Park / McWay Falls**  \n  - Short walk to a viewpoint of a waterfall onto the beach.\n- **Nepenthe**  \n  - Restaurant with incredible views; good for a snack or drink.\n- **Ragged Point**  \n  - Scenic overlook, café, restrooms; last dramatic cliff views heading south.\n\n### San Simeon to Pismo Beach\n- **Hearst Castle (San Simeon)**  \n  - Mansion tours on a hill with ocean views (reserve ahead if possible).\n- **Elephant Seal Vista Point (Piedras Blancas)**  \n  - Large colony of elephant seals right off the road.\n- **Cambria**  \n  - Cute town, Moonstone Beach boardwalk, wine tasting.\n- **Morro Bay**  \n  - Harbor town with Morro Rock; good lunch spot on the water.\n- **Pismo Beach**  \n  - Classic beach town; pier, dunes, clam chowder (e.g., Splash Café).\n\n### Central Coast to LA\n- **San Luis Obispo (SLO)**  \n  - Lively college town; great for dinner or an overnight.\n- **Solvang**  \n  - Danish-style village with bakeries and windmills.\n- **Santa Barbara**  \n  - Beachfront, Stearns Wharf, State Street shops and restaurants.\n- **Malibu**  \n  - Coastal pullouts, Zuma Beach, Malibu Pier (cafés, views).\n- Continue along PCH into **Santa Monica** and **LA**.\n\n---\n\n## 2. Faster Inland Route (US-101 or I-5)\n\nBest if you want to get there quicker but still have a couple of interesting stops.\n\n### Via US-101 (balanced speed + scenery)\n- **Gilroy** – Outlet shopping; garlic-themed everything.  \n- **Paso Robles** – Wine country; nice downtown square and tasting rooms.  \n- Then connect back to the coast near **San Luis Obispo** and follow the SLO → Santa Barbara → Malibu stops above.\n\n### Via I-5 (fastest, most direct)\nMore utilitarian, but:\n\n- **Harris Ranch (Coalinga)** – Big steakhouse, hotel, and rest stop.  \n- **Tejon Pass / Fort Tejon** – Mountain views as you cross into SoCal.\n\n---\n\n## Quick Templates Depending on Time\n\n- **1 long day, some scenery:**  \n  SF → Monterey lunch → Bixby Bridge / McWay Falls stops → San Simeon seals → SLO dinner → LA.\n\n- **2 days, overnight on Central Coast:**  \n  Day 1: SF → Half Moon Bay → Monterey → Big Sur sights → overnight in Cambria or SLO.  \n  Day 2: SLO → Pismo → Santa Barbara (lunch / explore) → Malibu → LA.\n\nIf you tell me:\n- which month you’re going,\n- how many days you have,\n- whether you care more about food, hikes, beaches, or towns,\n\nI can turn this into a specific, timed itinerary with suggested departure times and where to stay.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319796,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMGeXlDsasqazbxN8E8725SP8Co",
  "model": "gpt-5.1-2025-11-13",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 945,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 76,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 1021
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.1',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.1",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
The rain had turned Ashford Lane into a smear of reflections—red tail-lights, yellow windows, blue police strobes bleeding into the black river of asphalt. Detective Mara Leland hunched her shoulders against the weather and ducked under the sagging strip of crime-scene tape, the plastic snapping against her coat like impatient fingers.

The alley smelled of wet cardboard and old grease. Uniforms stood around in the practiced way of people trying not to look curious: hands tucked, mouths tight, eyes everywhere. The body lay where it had dropped beside the overflowing dumpster, face turned toward the brick wall as if listening to it.

“Male, mid-thirties,” the medical examiner said, barely glancing up as Mara approached. “Blunt force trauma, back of the head. Wallet’s missing. So is his phone.” He nodded toward the glistening puddles. “If there was anything else on him, the rain’s not doing us favors.”

Mara crouched, the cold water seeping through the knees of her slacks. The victim’s suit was inexpensive but clean, his tie knotted with deliberate care. No wedding ring. The bruise at the base of his skull was already swelling beneath the wet shine of his hair.

Robbery gone bad, the scene wanted her to think. It almost worked.

Then she saw his hand.

His right fist was clenched tight, the knuckles scraped, as if he’d hit something before he went down—or tried to hold on to it. Mara waited for the tech to finish with his photos, then slid on a fresh pair of gloves.

“Let’s see what you didn’t want to give up,” she murmured.

She pried his fingers open, one by stiffening one. It took effort; the chill had already started to set the muscles. Inside his palm, slick with rainwater and blood, lay a small paper rectangle, folded twice, the edges softened but the center still stiff.

Not a photograph. Not cash. Not a receipt.

A library card.

The laminate was cracked down one side, the blue logo of the Ashford Public Library almost worn away. The name typed beneath it, though, was unmistakable.

“Is that his?” one of the uniforms asked.

Mara shook her head slowly. “No.”

The card was ten years expired.

And it had her own name on it.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The rain had turned Ashford Lane into a smear of reflections—red tail-lights, yellow windows, blue police strobes bleeding into the black river of asphalt. Detective Mara Leland hunched her shoulders against the weather and ducked under the sagging strip of crime-scene tape, the plastic snapping against her coat like impatient fingers.\n\nThe alley smelled of wet cardboard and old grease. Uniforms stood around in the practiced way of people trying not to look curious: hands tucked, mouths tight, eyes everywhere. The body lay where it had dropped beside the overflowing dumpster, face turned toward the brick wall as if listening to it.\n\n“Male, mid-thirties,” the medical examiner said, barely glancing up as Mara approached. “Blunt force trauma, back of the head. Wallet’s missing. So is his phone.” He nodded toward the glistening puddles. “If there was anything else on him, the rain’s not doing us favors.”\n\nMara crouched, the cold water seeping through the knees of her slacks. The victim’s suit was inexpensive but clean, his tie knotted with deliberate care. No wedding ring. The bruise at the base of his skull was already swelling beneath the wet shine of his hair.\n\nRobbery gone bad, the scene wanted her to think. It almost worked.\n\nThen she saw his hand.\n\nHis right fist was clenched tight, the knuckles scraped, as if he’d hit something before he went down—or tried to hold on to it. Mara waited for the tech to finish with his photos, then slid on a fresh pair of gloves.\n\n“Let’s see what you didn’t want to give up,” she murmured.\n\nShe pried his fingers open, one by stiffening one. It took effort; the chill had already started to set the muscles. Inside his palm, slick with rainwater and blood, lay a small paper rectangle, folded twice, the edges softened but the center still stiff.\n\nNot a photograph. Not cash. Not a receipt.\n\nA library card.\n\nThe laminate was cracked down one side, the blue logo of the Ashford Public Library almost worn away. The name typed beneath it, though, was unmistakable.\n\n“Is that his?” one of the uniforms asked.\n\nMara shook her head slowly. “No.”\n\nThe card was ten years expired.\n\nAnd it had her own name on it.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319796,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMG1m127ZSVVIdInH24b5KfjU9n",
  "model": "gpt-5.1-2025-11-13",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 493,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 512
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.1',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.1",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
Recursion is when a function solves a problem by calling **itself**, each time working on a **smaller or simpler** version of the original problem, until it reaches a **base case** where it stops.

Two key ideas:
1. **Base case** – when to stop.
2. **Recursive step** – how the function calls itself with a simpler input.

### Simple example: Factorial

The factorial of a number `n` (written `n!`) is:
- `5! = 5 × 4 × 3 × 2 × 1 = 120`
- `1! = 1`
- By definition, `0! = 1`

We can define factorial recursively:
- Base case:  
  If `n = 0`, return `1`.
- Recursive step:  
  If `n > 0`, return `n × factorial(n - 1)`.

In (pseudo)code:

```python
def factorial(n):
    if n == 0:          # base case
        return 1
    else:               # recursive step
        return n * factorial(n - 1)
```

How `factorial(3)` works:
- `factorial(3)`  
  = `3 * factorial(2)`
- `factorial(2)`  
  = `2 * factorial(1)`
- `factorial(1)`  
  = `1 * factorial(0)`
- `factorial(0)`  
  = `1`  (base case)

Now substitute back:
- `factorial(1) = 1 * 1 = 1`
- `factorial(2) = 2 * 1 = 2`
- `factorial(3) = 3 * 2 = 6`

That chain of a function calling itself with smaller inputs is recursion.
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777319805,
    "id": "chatcmpl-DZMMPsL6Uzmm6d7HUyXvVCrMVjr9E",
    "model": "gpt-5.1-2025-11-13",
    "obfuscation": "NplkcVf5",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777319805,
    "id": "chatcmpl-DZMMPsL6Uzmm6d7HUyXvVCrMVjr9E",
    "model": "gpt-5.1-2025-11-13",
    "obfuscation": "QL5wyvK",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  "... 384 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777319805,
    "id": "chatcmpl-DZMMPsL6Uzmm6d7HUyXvVCrMVjr9E",
    "model": "gpt-5.1-2025-11-13",
    "obfuscation": "PuXlssc",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 393,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 16,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 409
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.1',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.1",
  "input": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
  "max_output_tokens": 4096,
  "tools": [
    {
      "type": "web_search_preview"
    }
  ]
}'
```

```
Here are the three main Cloudflare storylines that dominated coverage over roughly the past week (June 16–22, 2026):

- **Ongoing reaction to the VoidZero acquisition (June 4):** Analysts and developers are still digesting Cloudflare’s purchase of AI security startup VoidZero, with coverage focusing on how the deal strengthens Cloudflare’s AI-native security and edge platform strategy and its competition with hyperscalers in AI infrastructure. ([cloudflare.com](https://www.cloudflare.com/press/?utm_source=openai))  

- **Cloudflare’s role in recent/ongoing Internet reliability discussions:** In light of major Cloudflare outages over the last year, technical blogs and communities continue to scrutinize Cloudflare’s status communications and resilience; a fresh Reddit discussion this week debated timestamp handling and transparency on Cloudflare’s status page during a recent network-impacting incident linked to a major US fiber cut. ([reddit.com](https://www.reddit.com/r/sysadmin/comments/1ucmhpy/cloudflares_outage_and_the_ethics_of_fudging/?utm_source=openai))  

- **Continued build‑out of Cloudflare’s AI/agent platform stack:** Coverage from developer press highlights Cloudflare’s recent completion of a six‑layer “agent infrastructure” stack—especially the rebuilt Browser Run service on its Containers platform—framing Cloudflare as a key infrastructure provider for AI agents and automation workloads. ([infoq.com](https://www.infoq.com/news/2026/05/cloudflare-agent-platform-stack/?utm_source=openai))
```

```json
{
  "id": "resp_0f23d628b8934486016a3995086314819bbe0601a8ca62d55b",
  "object": "response",
  "created_at": 1782158600,
  "model": "gpt-5.1-2025-11-13",
  "output": [
    {
      "id": "ws_0f23d628b8934486016a399508e1ac819ba2a6f8c5c5eafc3e",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news past 7 days"
        ],
        "query": "Cloudflare news past 7 days"
      }
    },
    {
      "id": "msg_0f23d628b8934486016a39950a3540819b9680a2736261c217",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 519,
              "start_index": 448,
              "title": "Press Overview | Cloudflare",
              "url": "https://www.cloudflare.com/press/?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 1075,
              "start_index": 945,
              "title": "Cloudflare's outage and the ethics of fudging status page timestamps",
              "url": "https://www.reddit.com/r/sysadmin/comments/1ucmhpy/cloudflares_outage_and_the_ethics_of_fudging/?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 1524,
              "start_index": 1424,
              "title": "Cloudflare Completes Its Agent Infrastructure Stack with Browser Run Rebuild and Six-Layer Platform - InfoQ",
              "url": "https://www.infoq.com/news/2026/05/cloudflare-agent-platform-stack/?utm_source=openai"
            }
          ],
          "logprobs": [],
          "text": "Here are the three main Cloudflare storylines that dominated coverage over roughly the past week (June 16–22, 2026):\n\n- **Ongoing reaction to the VoidZero acquisition (June 4):** Analysts and developers are still digesting Cloudflare’s purchase of AI security startup VoidZero, with coverage focusing on how the deal strengthens Cloudflare’s AI-native security and edge platform strategy and its competition with hyperscalers in AI infrastructure. ([cloudflare.com](https://www.cloudflare.com/press/?utm_source=openai))  \n\n- **Cloudflare’s role in recent/ongoing Internet reliability discussions:** In light of major Cloudflare outages over the last year, technical blogs and communities continue to scrutinize Cloudflare’s status communications and resilience; a fresh Reddit discussion this week debated timestamp handling and transparency on Cloudflare’s status page during a recent network-impacting incident linked to a major US fiber cut. ([reddit.com](https://www.reddit.com/r/sysadmin/comments/1ucmhpy/cloudflares_outage_and_the_ethics_of_fudging/?utm_source=openai))  \n\n- **Continued build‑out of Cloudflare’s AI/agent platform stack:** Coverage from developer press highlights Cloudflare’s recent completion of a six‑layer “agent infrastructure” stack—especially the rebuilt Browser Run service on its Containers platform—framing Cloudflare as a key infrastructure provider for AI agents and automation workloads. ([infoq.com](https://www.infoq.com/news/2026/05/cloudflare-agent-platform-stack/?utm_source=openai))"
        }
      ],
      "role": "assistant"
    }
  ],
  "status": "completed",
  "usage": {
    "input_tokens": 10740,
    "output_tokens": 336,
    "total_tokens": 11076,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 32
    }
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1782158605,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 4096,
  "max_tool_calls": null,
  "moderation": null,
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "current_turn",
    "effort": "none",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "web_search_preview",
      "search_content_types": [
        "text"
      ],
      "search_context_size": "medium",
      "user_location": {
        "type": "approximate",
        "city": null,
        "country": "US",
        "region": null,
        "timezone": null
      }
    }
  ],
  "top_logprobs": 0,
  "top_p": 1,
  "truncation": "disabled",
  "user": null,
  "metadata": {},
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.1/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.1/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.1/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.1/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5.1/#page","headline":"GPT-5.1","description":"GPT-5.1 is OpenAI’s incremental improvement over GPT-5, with stronger coding, reasoning, and writing.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5.1/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5.4 is OpenAI's flagship model with strong coding, reasoning, and multimodal capabilities.
title: GPT-5.4
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5.4

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5.4/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5.4`

- Third-party
- Zero data retention

GPT-5.4 is OpenAI's flagship model with strong coding, reasoning, and multimodal capabilities.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$2.50</li><li>Output (per 1M tokens)$15.00</li><li>Cached input (per 1M tokens)$0.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5.4',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The **three laws of thermodynamics** are:

1. **First Law of Thermodynamics** — **Energy is conserved**  
   Energy cannot be created or destroyed, only transferred or transformed.  
   In thermodynamic systems, this is often written as:  
   **ΔU = Q - W**  
   where:
   - **ΔU** = change in internal energy  
   - **Q** = heat added to the system  
   - **W** = work done by the system  

2. **Second Law of Thermodynamics** — **Entropy tends to increase**  
   In any natural process, the total entropy of an isolated system never decreases.  
   This means energy tends to spread out, and no heat engine can be 100% efficient.

3. **Third Law of Thermodynamics** — **Entropy approaches a minimum at absolute zero**  
   As the temperature of a perfect crystal approaches **0 Kelvin**, its entropy approaches **zero**.  
   This also implies that absolute zero cannot be reached in a finite number of steps.

There is also a **Zeroth Law of Thermodynamics**, which is often listed before the first three:

- If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.  
- This is the basis for the concept of **temperature**.

If you want, I can also give a simple everyday explanation of each law.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The **three laws of thermodynamics** are:\n\n1. **First Law of Thermodynamics** — **Energy is conserved**  \n   Energy cannot be created or destroyed, only transferred or transformed.  \n   In thermodynamic systems, this is often written as:  \n   **ΔU = Q - W**  \n   where:\n   - **ΔU** = change in internal energy  \n   - **Q** = heat added to the system  \n   - **W** = work done by the system  \n\n2. **Second Law of Thermodynamics** — **Entropy tends to increase**  \n   In any natural process, the total entropy of an isolated system never decreases.  \n   This means energy tends to spread out, and no heat engine can be 100% efficient.\n\n3. **Third Law of Thermodynamics** — **Entropy approaches a minimum at absolute zero**  \n   As the temperature of a perfect crystal approaches **0 Kelvin**, its entropy approaches **zero**.  \n   This also implies that absolute zero cannot be reached in a finite number of steps.\n\nThere is also a **Zeroth Law of Thermodynamics**, which is often listed before the first three:\n\n- If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.  \n- This is the basis for the concept of **temperature**.\n\nIf you want, I can also give a simple everyday explanation of each law.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470832,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnVIkT2U7hYs4iNW9G9MXRoaNGmZ",
  "model": "gpt-5.4-2026-03-05",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 292,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 15,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 307
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4",
  "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"
    }
  ]
}'
```

````
Use Python’s built-in `json` module.

### Read a JSON file
```python
import json

with open("data.json", "r") as file:
    data = json.load(file)

print(data)
```

### If the file contains:
```json
{
  "name": "Alice",
  "age": 25
}
```

### Then `data` becomes:
```python
{'name': 'Alice', 'age': 25}
```

### Notes
- `json.load(file)` reads JSON from a file and converts it to Python objects.
- JSON objects become Python dictionaries.
- JSON arrays become Python lists.

### Read with UTF-8 encoding
```python
import json

with open("data.json", "r", encoding="utf-8") as file:
    data = json.load(file)
```

### Handle invalid JSON safely
```python
import json

try:
    with open("data.json", "r", encoding="utf-8") as file:
        data = json.load(file)
    print(data)
except FileNotFoundError:
    print("File not found.")
except json.JSONDecodeError:
    print("Invalid JSON.")
```

If you want, I can also show:
- how to read a JSON string
- how to write JSON to a file
- how to pretty-print JSON
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Use Python’s built-in `json` module.\n\n### Read a JSON file\n```python\nimport json\n\nwith open(\"data.json\", \"r\") as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n### If the file contains:\n```json\n{\n  \"name\": \"Alice\",\n  \"age\": 25\n}\n```\n\n### Then `data` becomes:\n```python\n{'name': 'Alice', 'age': 25}\n```\n\n### Notes\n- `json.load(file)` reads JSON from a file and converts it to Python objects.\n- JSON objects become Python dictionaries.\n- JSON arrays become Python lists.\n\n### Read with UTF-8 encoding\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as file:\n    data = json.load(file)\n```\n\n### Handle invalid JSON safely\n```python\nimport json\n\ntry:\n    with open(\"data.json\", \"r\", encoding=\"utf-8\") as file:\n        data = json.load(file)\n    print(data)\nexcept FileNotFoundError:\n    print(\"File not found.\")\nexcept json.JSONDecodeError:\n    print(\"Invalid JSON.\")\n```\n\nIf you want, I can also show:\n- how to read a JSON string\n- how to write JSON to a file\n- how to pretty-print JSON",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470834,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnVKhkW5dNkb7BVCtXpsT0KQSQPA",
  "model": "gpt-5.4-2026-03-05",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 279,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 309
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4",
  "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"
    }
  ]
}'
```

```
Here are some popular stops if you take the scenic coastal route (Highway 1 / Pacific Coast Highway), which is much slower than I-5 but far more beautiful:

### Great stops from San Francisco to Los Angeles
- **Half Moon Bay** – Nice beaches, coastal views, and a good first stop.
- **Santa Cruz** – Classic beach town with a boardwalk, pier, and cafes.
- **Monterey** – Famous for Cannery Row and the Monterey Bay Aquarium.
- **Carmel-by-the-Sea** – Charming small town with shops, galleries, and a beautiful beach.
- **Big Sur** – One of the most scenic stretches of the drive, with cliffs, ocean views, and hiking spots.
- **San Simeon** – Known for Hearst Castle and elephant seals nearby.
- **Morro Bay** – Relaxed coastal town with the iconic Morro Rock.
- **San Luis Obispo** – Cute downtown, restaurants, and a good overnight stop.
- **Pismo Beach** – Good for a beach walk or seafood stop.
- **Santa Barbara** – Beautiful Spanish-style architecture, beaches, and wine tasting.
- **Malibu** – Scenic coastline before arriving in Los Angeles.

### If you want the faster inland route (I-5)
Stops are less scenic, but you could consider:
- **Gilroy** – Known for garlic-themed food.
- **Harris Ranch** – Popular food/rest stop on I-5.
- **Kettleman City** – Convenient midpoint break.
- **Grapevine area** – Good place to pause before descending into LA.

If you want, I can also suggest:
1. a **1-day fast itinerary**,  
2. a **2-3 day scenic itinerary**, or  
3. **food-focused stops**.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Here are some popular stops if you take the scenic coastal route (Highway 1 / Pacific Coast Highway), which is much slower than I-5 but far more beautiful:\n\n### Great stops from San Francisco to Los Angeles\n- **Half Moon Bay** – Nice beaches, coastal views, and a good first stop.\n- **Santa Cruz** – Classic beach town with a boardwalk, pier, and cafes.\n- **Monterey** – Famous for Cannery Row and the Monterey Bay Aquarium.\n- **Carmel-by-the-Sea** – Charming small town with shops, galleries, and a beautiful beach.\n- **Big Sur** – One of the most scenic stretches of the drive, with cliffs, ocean views, and hiking spots.\n- **San Simeon** – Known for Hearst Castle and elephant seals nearby.\n- **Morro Bay** – Relaxed coastal town with the iconic Morro Rock.\n- **San Luis Obispo** – Cute downtown, restaurants, and a good overnight stop.\n- **Pismo Beach** – Good for a beach walk or seafood stop.\n- **Santa Barbara** – Beautiful Spanish-style architecture, beaches, and wine tasting.\n- **Malibu** – Scenic coastline before arriving in Los Angeles.\n\n### If you want the faster inland route (I-5)\nStops are less scenic, but you could consider:\n- **Gilroy** – Known for garlic-themed food.\n- **Harris Ranch** – Popular food/rest stop on I-5.\n- **Kettleman City** – Convenient midpoint break.\n- **Grapevine area** – Good place to pause before descending into LA.\n\nIf you want, I can also suggest:\n1. a **1-day fast itinerary**,  \n2. a **2-3 day scenic itinerary**, or  \n3. **food-focused stops**.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470837,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnVNwByCFYOwLiCFfkIf3ghWHlTf",
  "model": "gpt-5.4-2026-03-05",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 376,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 76,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 452
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
Detective Mara Voss found the first clue where no clue had any business being.

It was tucked inside the mouth of a stone lion that guarded the steps of Blackwell Hall, a place better known for charity galas than murder. The victim lay inside, under a chandelier bright enough to make everyone look innocent. Guests whispered behind silk gloves. Police boots clicked across marble. But Mara stood outside in the rain, staring at the lion’s weather-dark teeth.

Someone had placed a single peach pit on its tongue.

Not dropped. Placed.

She lifted it carefully with her handkerchief. The pit had been polished until it shone, and carved into its surface was the tiniest image of a key.

Mara looked up at the mansion windows. On the third floor, one curtain moved, though the glass behind it was black.

A dead banker in the ballroom was ordinary, as far as her city was concerned. A carved peach pit hidden in a stone lion’s mouth was not.

That was when she began to suspect the murder had started long before the body hit the floor.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Detective Mara Voss found the first clue where no clue had any business being.\n\nIt was tucked inside the mouth of a stone lion that guarded the steps of Blackwell Hall, a place better known for charity galas than murder. The victim lay inside, under a chandelier bright enough to make everyone look innocent. Guests whispered behind silk gloves. Police boots clicked across marble. But Mara stood outside in the rain, staring at the lion’s weather-dark teeth.\n\nSomeone had placed a single peach pit on its tongue.\n\nNot dropped. Placed.\n\nShe lifted it carefully with her handkerchief. The pit had been polished until it shone, and carved into its surface was the tiniest image of a key.\n\nMara looked up at the mansion windows. On the third floor, one curtain moved, though the glass behind it was black.\n\nA dead banker in the ballroom was ordinary, as far as her city was concerned. A carved peach pit hidden in a stone lion’s mouth was not.\n\nThat was when she began to suspect the murder had started long before the body hit the floor.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470838,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnVORnUmWsqkuSUZDpx0HiNsT3n6",
  "model": "gpt-5.4-2026-03-05",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 222,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 241
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
Recursion is when a function solves a problem by calling itself on a smaller version of the same problem.

It usually has 2 parts:

1. **Base case** — the condition where the function stops calling itself.
2. **Recursive case** — the part where the function calls itself with a smaller input.

### Simple example: factorial

The factorial of a number means:

- `5! = 5 × 4 × 3 × 2 × 1`
- `1! = 1`

A recursive version looks like this in Python:

```python
def factorial(n):
    if n == 1:          # base case
        return 1
    return n * factorial(n - 1)   # recursive case

print(factorial(5))
```

### How it works for `factorial(5)`

- `factorial(5)` → `5 * factorial(4)`
- `factorial(4)` → `4 * factorial(3)`
- `factorial(3)` → `3 * factorial(2)`
- `factorial(2)` → `2 * factorial(1)`
- `factorial(1)` → `1` ← base case

Then it returns back up:

- `factorial(2)` = `2 * 1 = 2`
- `factorial(3)` = `3 * 2 = 6`
- `factorial(4)` = `4 * 6 = 24`
- `factorial(5)` = `5 * 24 = 120`

### Key idea

Recursion works by breaking a big problem into smaller, similar problems until it reaches a simple stopping point.

If you want, I can also show a **real-life analogy** or a **non-math recursion example**.
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1776470844,
    "id": "chatcmpl-DVnVUroKWQ9mKa7IP7mbN9LFrUecN",
    "model": "gpt-5.4-2026-03-05",
    "obfuscation": "Wo9naBca",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1776470844,
    "id": "chatcmpl-DVnVUroKWQ9mKa7IP7mbN9LFrUecN",
    "model": "gpt-5.4-2026-03-05",
    "obfuscation": "Eu4D5Wg",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  "... 371 more chunks omitted ...",
  {
    "choices": [],
    "created": 1776470844,
    "id": "chatcmpl-DVnVUroKWQ9mKa7IP7mbN9LFrUecN",
    "model": "gpt-5.4-2026-03-05",
    "obfuscation": "quuZy0B",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 374,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 16,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 390
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4",
  "input": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
  "max_output_tokens": 4096,
  "tools": [
    {
      "type": "web_search_preview"
    }
  ]
}'
```

```
Here are the top Cloudflare stories I found for **this week of June 16–22, 2026**:

- **Cloudflare unveiled a new browser-backed web standard effort on June 22.** It said it is working with **Mozilla, Google, Microsoft, and Shopify** on **Private Access Control Tokens (PACT)**, a privacy-first protocol meant to help websites distinguish legitimate humans and authorized bots from malicious automation without relying as heavily on CAPTCHAs or invasive tracking. ([cloudflare.com](https://www.cloudflare.com/press/press-releases/2026/cloudflare-collaborates-with-leading-browsers-to-develop-a-privacy-first-protocol-for-the-global-internet/))

- **Cloudflare launched a new partner program push around AI and SASE on June 17–18.** The company introduced a **Cloudflare One Design Partner** designation and an **AI-powered deployment toolkit / Cloudflare One Stack** aimed at helping partners migrate customers from legacy security setups to Cloudflare’s SASE platform more quickly. ([cloudflare.com](https://www.cloudflare.com/press/press-releases/))

- **Cloudflare was also in the spotlight for a major outage discussion on June 22.** Community and operator reports pointed to a widespread incident affecting North America, with users debating Cloudflare’s status-page timing and some commenters attributing the disruption to a large **fiber cut in the eastern U.S.** That attribution appears to be community reporting rather than an official Cloudflare statement, so treat it as provisional. ([reddit.com](https://www.reddit.com/r/sysadmin/comments/1ucmhpy/cloudflares_outage_and_the_ethics_of_fudging/))

If you want, I can also turn this into a **more polished “executive brief” version** or include **links to the original articles/press releases**.
```

```json
{
  "id": "resp_07308ed5e73a1a07016a399654b808819bbe73b7cacddeb144",
  "object": "response",
  "created_at": 1782158932,
  "model": "gpt-5.4-2026-03-05",
  "output": [
    {
      "id": "ws_07308ed5e73a1a07016a3996555478819ba0dc680619d5b577",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare latest news this week June 2026",
          "Cloudflare news June 2026 site:cloudflare.com OR site:reuters.com OR site:theverge.com OR site:techcrunch.com",
          "Cloudflare press release June 2026",
          "Cloudflare Reuters June 2026"
        ],
        "query": "Cloudflare latest news this week June 2026"
      }
    },
    {
      "id": "ws_07308ed5e73a1a07016a399657b250819b993ed21cd98de1b0",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.cloudflare.com/press/press-releases/"
      }
    },
    {
      "id": "ws_07308ed5e73a1a07016a39965a0d04819b8c2ed37555f60460",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.cloudflare.com/press/press-releases/"
      }
    },
    {
      "id": "msg_07308ed5e73a1a07016a39965b2a44819bb530eea4c274d30e",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 643,
              "start_index": 464,
              "title": "www.cloudflare.com",
              "url": "https://www.cloudflare.com/press/press-releases/2026/cloudflare-collaborates-with-leading-browsers-to-develop-a-privacy-first-protocol-for-the-global-internet/"
            },
            {
              "type": "url_citation",
              "end_index": 1051,
              "start_index": 983,
              "title": "Press Overview | Cloudflare",
              "url": "https://www.cloudflare.com/press/press-releases/"
            },
            {
              "type": "url_citation",
              "end_index": 1608,
              "start_index": 1496,
              "title": "Cloudflare's outage and the ethics of fudging status page timestamps : r/sysadmin",
              "url": "https://www.reddit.com/r/sysadmin/comments/1ucmhpy/cloudflares_outage_and_the_ethics_of_fudging/"
            }
          ],
          "logprobs": [],
          "text": "Here are the top Cloudflare stories I found for **this week of June 16–22, 2026**:\n\n- **Cloudflare unveiled a new browser-backed web standard effort on June 22.** It said it is working with **Mozilla, Google, Microsoft, and Shopify** on **Private Access Control Tokens (PACT)**, a privacy-first protocol meant to help websites distinguish legitimate humans and authorized bots from malicious automation without relying as heavily on CAPTCHAs or invasive tracking. ([cloudflare.com](https://www.cloudflare.com/press/press-releases/2026/cloudflare-collaborates-with-leading-browsers-to-develop-a-privacy-first-protocol-for-the-global-internet/))\n\n- **Cloudflare launched a new partner program push around AI and SASE on June 17–18.** The company introduced a **Cloudflare One Design Partner** designation and an **AI-powered deployment toolkit / Cloudflare One Stack** aimed at helping partners migrate customers from legacy security setups to Cloudflare’s SASE platform more quickly. ([cloudflare.com](https://www.cloudflare.com/press/press-releases/))\n\n- **Cloudflare was also in the spotlight for a major outage discussion on June 22.** Community and operator reports pointed to a widespread incident affecting North America, with users debating Cloudflare’s status-page timing and some commenters attributing the disruption to a large **fiber cut in the eastern U.S.** That attribution appears to be community reporting rather than an official Cloudflare statement, so treat it as provisional. ([reddit.com](https://www.reddit.com/r/sysadmin/comments/1ucmhpy/cloudflares_outage_and_the_ethics_of_fudging/))\n\nIf you want, I can also turn this into a **more polished “executive brief” version** or include **links to the original articles/press releases**."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "status": "completed",
  "usage": {
    "input_tokens": 19126,
    "output_tokens": 522,
    "total_tokens": 19648,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 175
    }
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1782158944,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 4096,
  "max_tool_calls": null,
  "moderation": null,
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "current_turn",
    "effort": "none",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "web_search_preview",
      "search_content_types": [
        "text"
      ],
      "search_context_size": "medium",
      "user_location": {
        "type": "approximate",
        "city": null,
        "country": "US",
        "region": null,
        "timezone": null
      }
    }
  ],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "user": null,
  "metadata": {},
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.4/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.4/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.4/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.4/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5.4/#page","headline":"GPT-5.4","description":"GPT-5.4 is OpenAI's flagship model with strong coding, reasoning, and multimodal capabilities.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5.4/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5.4 mini is a smaller, faster, and more cost-efficient version of GPT-5.4 for lightweight tasks.
title: GPT-5.4 mini
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5.4 mini

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-mini/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5.4-mini`

- Third-party
- Zero data retention

GPT-5.4 mini is a smaller, faster, and more cost-efficient version of GPT-5.4 for lightweight tasks.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 128,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.75</li><li>Output (per 1M tokens)$4.50</li><li>Cached input (per 1M tokens)$0.075</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5.4-mini',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-mini",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The three laws of thermodynamics are:

1. **First Law: Conservation of energy**  
   Energy cannot be created or destroyed, only transferred or transformed.  
   In simple form:  
   **ΔU = Q − W**  
   where ΔU is the change in internal energy, Q is heat added to the system, and W is work done by the system.

2. **Second Law: Entropy increases**  
   In an isolated system, entropy tends to increase over time. This means natural processes are irreversible and energy tends to spread out.  
   A common implication: no heat engine can be 100% efficient.

3. **Third Law: Absolute zero is unattainable**  
   As temperature approaches absolute zero, the entropy of a perfect crystal approaches a minimum value, usually taken as zero.  
   In practice, it’s impossible to reach exactly 0 K in a finite number of steps.

If you want, I can also give you a **very simple everyday analogy** for each law.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The three laws of thermodynamics are:\n\n1. **First Law: Conservation of energy**  \n   Energy cannot be created or destroyed, only transferred or transformed.  \n   In simple form:  \n   **ΔU = Q − W**  \n   where ΔU is the change in internal energy, Q is heat added to the system, and W is work done by the system.\n\n2. **Second Law: Entropy increases**  \n   In an isolated system, entropy tends to increase over time. This means natural processes are irreversible and energy tends to spread out.  \n   A common implication: no heat engine can be 100% efficient.\n\n3. **Third Law: Absolute zero is unattainable**  \n   As temperature approaches absolute zero, the entropy of a perfect crystal approaches a minimum value, usually taken as zero.  \n   In practice, it’s impossible to reach exactly 0 K in a finite number of steps.\n\nIf you want, I can also give you a **very simple everyday analogy** for each law.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470825,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnVB12AdRglT0QAUKVZ2kfSuzFOP",
  "model": "gpt-5.4-mini-2026-03-17",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 211,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 15,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 226
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-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"
    }
  ]
}'
```

````
Use Python’s built-in `json` module.

```python
import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(data)
```

### Notes
- `json.load(f)` reads JSON from a file object.
- `json.loads(s)` reads JSON from a string.
- The result is usually a Python `dict` or `list`, depending on the JSON structure.

### Example JSON
```json
{
  "name": "Alice",
  "age": 30
}
```

### Python result
```python
{'name': 'Alice', 'age': 30}
```

If you want, I can also show how to:
- read JSON into a pandas DataFrame
- handle invalid JSON errors
- write JSON back to a file
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Use Python’s built-in `json` module.\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n\nprint(data)\n```\n\n### Notes\n- `json.load(f)` reads JSON from a file object.\n- `json.loads(s)` reads JSON from a string.\n- The result is usually a Python `dict` or `list`, depending on the JSON structure.\n\n### Example JSON\n```json\n{\n  \"name\": \"Alice\",\n  \"age\": 30\n}\n```\n\n### Python result\n```python\n{'name': 'Alice', 'age': 30}\n```\n\nIf you want, I can also show how to:\n- read JSON into a pandas DataFrame\n- handle invalid JSON errors\n- write JSON back to a file",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470827,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnVDQEDXijlKMCbGNVtJzuMx2D8F",
  "model": "gpt-5.4-mini-2026-03-17",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 176,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 206
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-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"
    }
  ]
}'
```

```
Absolutely — the San Francisco to Los Angeles drive has a lot of great stop options depending on whether you want the **fastest route** or the **most scenic one**.

## Best stops if you take Highway 1 / Pacific Coast Highway
This is the most scenic route, but it can add a lot of time.

### 1. Monterey / Carmel-by-the-Sea
- Great for a first major stop south of SF
- **Monterey Bay Aquarium** is a top attraction
- Carmel has a charming village feel, beaches, and galleries

### 2. Big Sur
- One of the most famous scenic stretches in California
- Must-see viewpoints:
  - **Bixby Creek Bridge**
  - **Pfeiffer Beach**
  - **Julia Pfeiffer Burns State Park** / McWay Falls
- Ideal if you want dramatic coastline and photo stops

### 3. San Simeon / Hearst Castle
- Good place to break up the drive
- **Hearst Castle** is the big attraction here
- Also possible to see elephant seals at **Piedras Blancas**

### 4. San Luis Obispo
- Nice overnight or lunch stop
- Relaxed downtown, good food, and easy access to nearby wine country

### 5. Santa Barbara
- Beautiful coastal city, great for a meal or longer stop
- **Stearns Wharf**, the mission, and the harbor are popular
- Good “last major stop” before LA

## Best stops if you take the faster inland route (US-101 / I-5)
This is quicker and still has good options.

### 1. San Luis Obispo
- Great midway break
- Walkable downtown and lots of restaurants

### 2. Solvang
- A fun Danish-style town near Santa Barbara
- Good for pastries, coffee, and a quick stretch

### 3. Santa Barbara
- Still worth stopping even on the faster route
- Beautiful and easy to enjoy without a huge detour

### 4. Ventura / Oxnard
- Good coastal stop before reaching LA
- Less crowded than Santa Barbara

## If you want a balanced one-day route
A practical plan is:
- **SF → Monterey / Carmel**
- **Monterey → Big Sur**
- **Big Sur → San Luis Obispo**
- **San Luis Obispo → Santa Barbara**
- **Santa Barbara → LA**

That’s a lot for one day, so many people do it as a **2-day or 3-day road trip**.

## Quick recommendation
If you only want a few stops, I’d pick:
1. **Monterey**
2. **Big Sur**
3. **Santa Barbara**

If you want, I can also make you:
- a **1-day itinerary**
- a **2-day scenic itinerary**
- or a route with **food, beaches, and hiking stops**.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Absolutely — the San Francisco to Los Angeles drive has a lot of great stop options depending on whether you want the **fastest route** or the **most scenic one**.\n\n## Best stops if you take Highway 1 / Pacific Coast Highway\nThis is the most scenic route, but it can add a lot of time.\n\n### 1. Monterey / Carmel-by-the-Sea\n- Great for a first major stop south of SF\n- **Monterey Bay Aquarium** is a top attraction\n- Carmel has a charming village feel, beaches, and galleries\n\n### 2. Big Sur\n- One of the most famous scenic stretches in California\n- Must-see viewpoints:\n  - **Bixby Creek Bridge**\n  - **Pfeiffer Beach**\n  - **Julia Pfeiffer Burns State Park** / McWay Falls\n- Ideal if you want dramatic coastline and photo stops\n\n### 3. San Simeon / Hearst Castle\n- Good place to break up the drive\n- **Hearst Castle** is the big attraction here\n- Also possible to see elephant seals at **Piedras Blancas**\n\n### 4. San Luis Obispo\n- Nice overnight or lunch stop\n- Relaxed downtown, good food, and easy access to nearby wine country\n\n### 5. Santa Barbara\n- Beautiful coastal city, great for a meal or longer stop\n- **Stearns Wharf**, the mission, and the harbor are popular\n- Good “last major stop” before LA\n\n## Best stops if you take the faster inland route (US-101 / I-5)\nThis is quicker and still has good options.\n\n### 1. San Luis Obispo\n- Great midway break\n- Walkable downtown and lots of restaurants\n\n### 2. Solvang\n- A fun Danish-style town near Santa Barbara\n- Good for pastries, coffee, and a quick stretch\n\n### 3. Santa Barbara\n- Still worth stopping even on the faster route\n- Beautiful and easy to enjoy without a huge detour\n\n### 4. Ventura / Oxnard\n- Good coastal stop before reaching LA\n- Less crowded than Santa Barbara\n\n## If you want a balanced one-day route\nA practical plan is:\n- **SF → Monterey / Carmel**\n- **Monterey → Big Sur**\n- **Big Sur → San Luis Obispo**\n- **San Luis Obispo → Santa Barbara**\n- **Santa Barbara → LA**\n\nThat’s a lot for one day, so many people do it as a **2-day or 3-day road trip**.\n\n## Quick recommendation\nIf you only want a few stops, I’d pick:\n1. **Monterey**\n2. **Big Sur**\n3. **Santa Barbara**\n\nIf you want, I can also make you:\n- a **1-day itinerary**\n- a **2-day scenic itinerary**\n- or a route with **food, beaches, and hiking stops**.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470827,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnVDSqb2DaSLNqKCpSBwk0puM04a",
  "model": "gpt-5.4-mini-2026-03-17",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 601,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 76,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 677
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-mini',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-mini",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
The rain had been falling since midnight, soft and persistent, turning the city into a blur of sodium light and reflected secrets. Detective Mara Venn stood in the doorway of apartment 4B, one gloved hand resting against the frame, and looked down at the object gleaming on the floorboards.

It wasn’t a weapon. It wasn’t jewelry, either.

At first glance, it looked like a child’s toy: a tiny brass bird with one wing folded and the other raised as if caught mid-flight. But when Mara knelt and picked it up, she felt the weight of it—too heavy for its size—and noticed the fine engraved line along its belly. A seam.

She turned the figurine over. Hidden beneath the bird’s feet was a row of numbers, stamped so neatly they might have been part of the design. Not a serial number, exactly. Too deliberate for that. Too precise.

Behind her, the apartment hummed with the low buzz of the refrigerator and the distant wail of a siren moving somewhere farther downtown. Inside the room, the dead man sat slumped in his chair as if he’d merely nodded off. His hands were folded on the desk. His face was calm.

Mara looked again at the brass bird.

The numbers weren’t random. She knew that before she even compared them to the note pinned under the victim’s pen, written in a hand so steady it seemed almost smug:

**You’re late. Look under the third stone.**

She slipped the bird into an evidence bag and stared at the cold line of the victim’s mouth.

Someone had planned this very carefully.

And somehow, they had expected her to come.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The rain had been falling since midnight, soft and persistent, turning the city into a blur of sodium light and reflected secrets. Detective Mara Venn stood in the doorway of apartment 4B, one gloved hand resting against the frame, and looked down at the object gleaming on the floorboards.\n\nIt wasn’t a weapon. It wasn’t jewelry, either.\n\nAt first glance, it looked like a child’s toy: a tiny brass bird with one wing folded and the other raised as if caught mid-flight. But when Mara knelt and picked it up, she felt the weight of it—too heavy for its size—and noticed the fine engraved line along its belly. A seam.\n\nShe turned the figurine over. Hidden beneath the bird’s feet was a row of numbers, stamped so neatly they might have been part of the design. Not a serial number, exactly. Too deliberate for that. Too precise.\n\nBehind her, the apartment hummed with the low buzz of the refrigerator and the distant wail of a siren moving somewhere farther downtown. Inside the room, the dead man sat slumped in his chair as if he’d merely nodded off. His hands were folded on the desk. His face was calm.\n\nMara looked again at the brass bird.\n\nThe numbers weren’t random. She knew that before she even compared them to the note pinned under the victim’s pen, written in a hand so steady it seemed almost smug:\n\n**You’re late. Look under the third stone.**\n\nShe slipped the bird into an evidence bag and stared at the cold line of the victim’s mouth.\n\nSomeone had planned this very carefully.\n\nAnd somehow, they had expected her to come.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470828,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnVEh2k96IQnpAZXEH5eHHSILLHq",
  "model": "gpt-5.4-mini-2026-03-17",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 343,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 362
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-mini',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-mini",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
Recursion is when a function solves a problem by calling itself on a smaller version of the same problem.

### Simple idea
A recursive function usually has:
1. **A base case** — when to stop calling itself
2. **A recursive case** — when it calls itself with a smaller input

### Example: counting down
```python
def countdown(n):
    if n == 0:          # base case
        print("Done!")
    else:
        print(n)
        countdown(n - 1)  # recursive call
```

If you run:
```python
countdown(3)
```

It prints:
```python
3
2
1
Done!
```

### How it works
- `countdown(3)` prints `3`, then calls `countdown(2)`
- `countdown(2)` prints `2`, then calls `countdown(1)`
- `countdown(1)` prints `1`, then calls `countdown(0)`
- `countdown(0)` reaches the base case and stops

### In short
Recursion is like solving a big problem by breaking it into smaller versions of the same problem until you reach a stopping point.
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1776470832,
    "id": "chatcmpl-DVnVIJWPzCL8OTA38vb3b0IM2eEca",
    "model": "gpt-5.4-mini-2026-03-17",
    "obfuscation": "9pV",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1776470832,
    "id": "chatcmpl-DVnVIJWPzCL8OTA38vb3b0IM2eEca",
    "model": "gpt-5.4-mini-2026-03-17",
    "obfuscation": "2K",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  "... 248 more chunks omitted ...",
  {
    "choices": [],
    "created": 1776470832,
    "id": "chatcmpl-DVnVIJWPzCL8OTA38vb3b0IM2eEca",
    "model": "gpt-5.4-mini-2026-03-17",
    "obfuscation": "Ic",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 251,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 16,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 267
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-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"
    }
  ]
}'
```

```
Here are the top Cloudflare stories from **this week** I found, in three bullets:

- **Cloudflare had a service degradation/outage today, June 22, 2026**, with widespread user reports of 500 errors and impacted services; discussion online suggests it affected a broad set of Cloudflare-dependent sites. ([reddit.com](https://www.reddit.com/r/sysadmin/comments/1ucm4f2/cloudflare_na_service_degraded_6222026/?utm_source=openai))

- **Cloudflare announced a new partner initiative for AI and SASE adoption** on **June 18, 2026**, adding a Cloudflare One Design Partner designation and AI tooling to help customers migrate away from fragmented security setups. ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))

- **Cloudflare’s June product/news cycle was dominated by AI and platform expansion**, including the launch of “Application Services for Private Origins” on **June 10**, the company’s acquisition of **VoidZero** on **June 4**, and new AI security/budgeting features on **June 5**. ([blog.cloudflare.com](https://blog.cloudflare.com/?utm_source=openai))

If you want, I can turn this into a **more newsroom-style summary** or a **“most important + why it matters”** version.
```

```json
{
  "id": "resp_0f020ddf70098206016a399675cf94819bbe9b7eee768256c3",
  "object": "response",
  "created_at": 1782158965,
  "model": "gpt-5.4-mini-2026-03-17",
  "output": [
    {
      "id": "ws_0f020ddf70098206016a3996763370819b932817a9ee0bacdc",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news this week June 2026 Cloudflare",
          "Cloudflare this week news June 2026",
          "Cloudflare latest news June 2026 site:reuters.com OR site:bloomberg.com OR site:techcrunch.com OR site:theverge.com"
        ],
        "query": "Cloudflare news this week June 2026 Cloudflare"
      }
    },
    {
      "id": "ws_0f020ddf70098206016a399678a478819ba4f867a7c11a5136",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "site:reuters.com Cloudflare June 2026 outage June 22 2026",
          "site:cloudflare.com blog June 2026 Cloudflare outage June 22 2026",
          "site:techcrunch.com Cloudflare June 2026 outage"
        ],
        "query": "site:reuters.com Cloudflare June 2026 outage June 22 2026"
      }
    },
    {
      "id": "msg_0f020ddf70098206016a39967aa8f0819bb32294764e0878d9",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 427,
              "start_index": 303,
              "title": "Cloudflare NA service degraded 6-22-2026",
              "url": "https://www.reddit.com/r/sysadmin/comments/1ucm4f2/cloudflare_na_service_degraded_6222026/?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 822,
              "start_index": 658,
              "title": "Cloudflare launches new partner initiative to support AI and SASE adoption",
              "url": "https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 1176,
              "start_index": 1105,
              "title": "The Cloudflare Blog",
              "url": "https://blog.cloudflare.com/?utm_source=openai"
            }
          ],
          "logprobs": [],
          "text": "Here are the top Cloudflare stories from **this week** I found, in three bullets:\n\n- **Cloudflare had a service degradation/outage today, June 22, 2026**, with widespread user reports of 500 errors and impacted services; discussion online suggests it affected a broad set of Cloudflare-dependent sites. ([reddit.com](https://www.reddit.com/r/sysadmin/comments/1ucm4f2/cloudflare_na_service_degraded_6222026/?utm_source=openai))\n\n- **Cloudflare announced a new partner initiative for AI and SASE adoption** on **June 18, 2026**, adding a Cloudflare One Design Partner designation and AI tooling to help customers migrate away from fragmented security setups. ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))\n\n- **Cloudflare’s June product/news cycle was dominated by AI and platform expansion**, including the launch of “Application Services for Private Origins” on **June 10**, the company’s acquisition of **VoidZero** on **June 4**, and new AI security/budgeting features on **June 5**. ([blog.cloudflare.com](https://blog.cloudflare.com/?utm_source=openai))\n\nIf you want, I can turn this into a **more newsroom-style summary** or a **“most important + why it matters”** version."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "status": "completed",
  "usage": {
    "input_tokens": 17121,
    "output_tokens": 485,
    "total_tokens": 17606,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 196
    }
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1782158971,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 4096,
  "max_tool_calls": null,
  "moderation": null,
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "current_turn",
    "effort": "none",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "web_search_preview",
      "search_content_types": [
        "text"
      ],
      "search_context_size": "medium",
      "user_location": {
        "type": "approximate",
        "city": null,
        "country": "US",
        "region": null,
        "timezone": null
      }
    }
  ],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "user": null,
  "metadata": {},
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-mini/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-mini/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-mini/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-mini/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5.4-mini/#page","headline":"GPT-5.4 mini","description":"GPT-5.4 mini is a smaller, faster, and more cost-efficient version of GPT-5.4 for lightweight tasks.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5.4-mini/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5.4 nano is OpenAI's smallest and fastest model, optimized for edge and low-latency use cases.
title: GPT-5.4 nano
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5.4 nano

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-nano/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5.4-nano`

- Third-party
- Zero data retention

GPT-5.4 nano is OpenAI's smallest and fastest model, optimized for edge and low-latency use cases.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 128,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$0.20</li><li>Output (per 1M tokens)$1.25</li><li>Cached input (per 1M tokens)$0.02</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5.4-nano',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-nano",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The three laws of thermodynamics are:

1. **Zeroth Law (thermal equilibrium):**  
   If system A is in thermal equilibrium with system B, and system B is in thermal equilibrium with system C, then A is in thermal equilibrium with C.  
   *This law justifies the concept of temperature.*

2. **First Law (conservation of energy):**  
   Energy cannot be created or destroyed. It can only be transferred or transformed.  
   *In thermodynamics:* the change in internal energy of a system equals heat added to the system minus work done by the system.

3. **Second Law (entropy and direction of processes):**  
   Natural processes occur in a direction that increases the **total entropy** of the universe (or, equivalently, they tend to go from more ordered to less ordered forms).  
   It also implies that **not all heat can be converted into work** in a cyclical process.

*(There is also a “Third Law,” often presented alongside these as the third in the series.)*

4. **Third Law (absolute zero):**  
   As temperature approaches absolute zero (0 K), the entropy of a perfect crystal approaches a constant minimum value (typically zero).  
   It is impossible to reach absolute zero in a finite number of steps.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The three laws of thermodynamics are:\n\n1. **Zeroth Law (thermal equilibrium):**  \n   If system A is in thermal equilibrium with system B, and system B is in thermal equilibrium with system C, then A is in thermal equilibrium with C.  \n   *This law justifies the concept of temperature.*\n\n2. **First Law (conservation of energy):**  \n   Energy cannot be created or destroyed. It can only be transferred or transformed.  \n   *In thermodynamics:* the change in internal energy of a system equals heat added to the system minus work done by the system.\n\n3. **Second Law (entropy and direction of processes):**  \n   Natural processes occur in a direction that increases the **total entropy** of the universe (or, equivalently, they tend to go from more ordered to less ordered forms).  \n   It also implies that **not all heat can be converted into work** in a cyclical process.\n\n*(There is also a “Third Law,” often presented alongside these as the third in the series.)*\n\n4. **Third Law (absolute zero):**  \n   As temperature approaches absolute zero (0 K), the entropy of a perfect crystal approaches a constant minimum value (typically zero).  \n   It is impossible to reach absolute zero in a finite number of steps.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470688,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnSyLOilRNmNr3S4HVuxEV3o73CA",
  "model": "gpt-5.4-nano-2026-03-17",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 269,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 15,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 284
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-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"
    }
  ]
}'
```

````
You can read a JSON file in Python using the built-in `json` module.

```python
import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(data)  # data is now a Python dict/list depending on the JSON
```

**Notes:**
- Use `json.load(f)` to read from a file object.
- If your JSON file is an array at the top level, `data` will be a `list`; if it’s an object, it’ll be a `dict`.

If you want to read a JSON string instead (not a file), use `json.loads(s)`.
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "You can read a JSON file in Python using the built-in `json` module.\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n\nprint(data)  # data is now a Python dict/list depending on the JSON\n```\n\n**Notes:**\n- Use `json.load(f)` to read from a file object.\n- If your JSON file is an array at the top level, `data` will be a `list`; if it’s an object, it’ll be a `dict`.\n\nIf you want to read a JSON string instead (not a file), use `json.loads(s)`.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470689,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnSzJVB6hEuloVcaDknzODqh082f",
  "model": "gpt-5.4-nano-2026-03-17",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 144,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 174
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-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"
    }
  ]
}'
```

```
Absolutely—here are some great stop ideas on a typical San Francisco → Los Angeles road trip (assuming you’ll mostly take **I‑5 or US‑101**). I’ll list them by region so you can mix and match based on time and interests.

## Best quick stops (easy to add)
### Along/near the coast (great views)
- **Half Moon Bay** – beaches, scenic overlooks, quick coffee/food stops.
- **Santa Cruz (if you take/near US‑101)** – boardwalk area, viewpoints; fun even for a short stop.
- **Monterey Bay / Cannery Row** – aquarium area and coastal scenery.
- **Big Sur viewpoints (if you do the coastal route)**  
  - Common highlights: **Bixby Bridge**, **McWay Falls (if open)**, scenic pullouts along Highway 1.

> Note: Big Sur can be slower and is weather-dependent (and Highway 1 sections can close occasionally), so plan with current conditions if you choose this.

### Classic “Hollywood-adjacent” vibes
- **Santa Barbara** – charming downtown, good food, beach walk.
- **Solvang** – Danish-style village theme; silly/fun stop for snacks and photos.

## Major “worth it” detours (more time, bigger payoff)
### Wine country (if you like food + views)
- **Santa Rosa / Healdsburg (Sonoma County)** – wineries, farm stands, tastings.
- **Napa Valley (if you want a big wine day)** – mostly if you’re okay with a longer detour.

### Redwood / nature stops
- **Henry Cowell Redwoods State Park (near Santa Cruz)** – redwood trails without a huge detour.
- **Giant redwoods near Monterey area / Big Basin (depending on route)** – more forest time.

### Route/landscape highlights on inland routes
If you go more inland (often faster, less coastline):
- **Gilroy** – quick stop for garlic-themed food or outlets.
- **Central Valley roadside stops** – quick lunch breaks, but fewer “must-see” landmarks.

## A few “choose based on your route” suggestions
- **If you take US‑101 (often prettier / more towns):** Half Moon Bay → Santa Cruz → Monterey → Santa Barbara → LA.
- **If you take I‑5 (usually faster):** San Jose area → Paso Robles (good mid-way option) → Santa Barbara → LA.
- **If you want the iconic scenery:** prioritize **Highway 1 / Big Sur** (best views, slower, more planning).

---

### Quick questions so I can tailor a perfect stop list + itinerary
1. What month (or approximate dates) are you going?
2. Do you prefer **coastal views (slower, scenic)** or **faster/inland (more driving, fewer views)**?
3. How many days do you want (e.g., 1 long day vs 2–3 days)?
4. Any interests: beaches, hiking, wine, kitschy towns, food stops, museums?

Answer those and I’ll propose a specific route with 6–12 stops, estimated timing, and backup options.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Absolutely—here are some great stop ideas on a typical San Francisco → Los Angeles road trip (assuming you’ll mostly take **I‑5 or US‑101**). I’ll list them by region so you can mix and match based on time and interests.\n\n## Best quick stops (easy to add)\n### Along/near the coast (great views)\n- **Half Moon Bay** – beaches, scenic overlooks, quick coffee/food stops.\n- **Santa Cruz (if you take/near US‑101)** – boardwalk area, viewpoints; fun even for a short stop.\n- **Monterey Bay / Cannery Row** – aquarium area and coastal scenery.\n- **Big Sur viewpoints (if you do the coastal route)**  \n  - Common highlights: **Bixby Bridge**, **McWay Falls (if open)**, scenic pullouts along Highway 1.\n\n> Note: Big Sur can be slower and is weather-dependent (and Highway 1 sections can close occasionally), so plan with current conditions if you choose this.\n\n### Classic “Hollywood-adjacent” vibes\n- **Santa Barbara** – charming downtown, good food, beach walk.\n- **Solvang** – Danish-style village theme; silly/fun stop for snacks and photos.\n\n## Major “worth it” detours (more time, bigger payoff)\n### Wine country (if you like food + views)\n- **Santa Rosa / Healdsburg (Sonoma County)** – wineries, farm stands, tastings.\n- **Napa Valley (if you want a big wine day)** – mostly if you’re okay with a longer detour.\n\n### Redwood / nature stops\n- **Henry Cowell Redwoods State Park (near Santa Cruz)** – redwood trails without a huge detour.\n- **Giant redwoods near Monterey area / Big Basin (depending on route)** – more forest time.\n\n### Route/landscape highlights on inland routes\nIf you go more inland (often faster, less coastline):\n- **Gilroy** – quick stop for garlic-themed food or outlets.\n- **Central Valley roadside stops** – quick lunch breaks, but fewer “must-see” landmarks.\n\n## A few “choose based on your route” suggestions\n- **If you take US‑101 (often prettier / more towns):** Half Moon Bay → Santa Cruz → Monterey → Santa Barbara → LA.\n- **If you take I‑5 (usually faster):** San Jose area → Paso Robles (good mid-way option) → Santa Barbara → LA.\n- **If you want the iconic scenery:** prioritize **Highway 1 / Big Sur** (best views, slower, more planning).\n\n---\n\n### Quick questions so I can tailor a perfect stop list + itinerary\n1. What month (or approximate dates) are you going?\n2. Do you prefer **coastal views (slower, scenic)** or **faster/inland (more driving, fewer views)**?\n3. How many days do you want (e.g., 1 long day vs 2–3 days)?\n4. Any interests: beaches, hiking, wine, kitschy towns, food stops, museums?\n\nAnswer those and I’ll propose a specific route with 6–12 stops, estimated timing, and backup options.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470691,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnT1xz56ah5Px0VXmp40Yxy793fo",
  "model": "gpt-5.4-nano-2026-03-17",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 665,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 76,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 741
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-nano',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-nano",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
The rain had been falling long enough to turn the city’s neon into smeared watercolor, but it hadn’t softened the edges of the crime scene.

Detective Mara Kincaid stood just inside the taped perimeter, her coat dark with moisture and her mind sharper than the puddles gathering at her feet. The victim’s apartment sat above a shuttered bakery, its windows fogged from the inside, its hallway smelling faintly of citrus cleaner and burnt copper.

A uniform officer hovered nearby, eager to be useful. “No signs of forced entry, Detective. The husband—” He stopped, corrected himself. “The occupant. He found them like this.”

Mara didn’t look up. She was kneeling by the threshold, letting her flashlight sweep the floorboards the way some people read scripture—slow, patient, searching for the lines that didn’t belong.

Something glittered against the worn grain of wood.

It wasn’t glass. It wasn’t glitter from a spilled drink. It didn’t catch the light like coins or broken jewelry. It caught it like… breath.

A thin, translucent flake—no bigger than a fingernail clipping—lay half-buried in the seam between two planks. When Mara tilted her beam, the flake didn’t reflect so much as *remember*. The light seemed to sink into it and come back altered, as if the material were holding a picture just out of reach.

“Don’t touch it,” she said automatically, though she hadn’t realized she’d spoken until the officer flinched.

Mara held her breath. The flake had a faint curve, like the edge of a leaf, and a delicate pattern of lines that didn’t resemble any natural vein. Under the flashlight, the pattern looked almost… intentional.

She lifted her gloved hand, stopped millimeters above it, and felt a temperature difference. The wood around it was cold with night air. The flake was warmer, as though it had just been pressed there.

On instinct, she slid a small evidence marker beside it without moving the flake itself. Then she leaned closer and listened—because in her line of work, some things weren’t just seen.

At first there was only the rain and the distant rumble of traffic.

Then—barely audible beneath it—a soft, rhythmic *tick… tick… tick*, like a clock inside something too small to be a clock.

Mara straightened slowly, her stomach tightening. The unusual clue wasn’t just out of place.

It was *alive* in a way she couldn’t explain.

Behind her, the officer cleared his throat. “Detective? Should we—uh—call for your tech?”

Mara didn’t answer right away. She stared at the flake until her eyes began to ache, watching the light tremble within it like it was trying to form a message.

Finally, she said, “Yeah. And bring two sets of gloves.”

She stood, turning toward the apartment interior where the air felt heavy with everything that had already happened.

Whatever left this behind didn’t want to be caught.

But it had made sure she’d look—down at the seam between boards—at the moment her flashlight found it.

As if it knew exactly where her curiosity would go next.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The rain had been falling long enough to turn the city’s neon into smeared watercolor, but it hadn’t softened the edges of the crime scene.\n\nDetective Mara Kincaid stood just inside the taped perimeter, her coat dark with moisture and her mind sharper than the puddles gathering at her feet. The victim’s apartment sat above a shuttered bakery, its windows fogged from the inside, its hallway smelling faintly of citrus cleaner and burnt copper.\n\nA uniform officer hovered nearby, eager to be useful. “No signs of forced entry, Detective. The husband—” He stopped, corrected himself. “The occupant. He found them like this.”\n\nMara didn’t look up. She was kneeling by the threshold, letting her flashlight sweep the floorboards the way some people read scripture—slow, patient, searching for the lines that didn’t belong.\n\nSomething glittered against the worn grain of wood.\n\nIt wasn’t glass. It wasn’t glitter from a spilled drink. It didn’t catch the light like coins or broken jewelry. It caught it like… breath.\n\nA thin, translucent flake—no bigger than a fingernail clipping—lay half-buried in the seam between two planks. When Mara tilted her beam, the flake didn’t reflect so much as *remember*. The light seemed to sink into it and come back altered, as if the material were holding a picture just out of reach.\n\n“Don’t touch it,” she said automatically, though she hadn’t realized she’d spoken until the officer flinched.\n\nMara held her breath. The flake had a faint curve, like the edge of a leaf, and a delicate pattern of lines that didn’t resemble any natural vein. Under the flashlight, the pattern looked almost… intentional.\n\nShe lifted her gloved hand, stopped millimeters above it, and felt a temperature difference. The wood around it was cold with night air. The flake was warmer, as though it had just been pressed there.\n\nOn instinct, she slid a small evidence marker beside it without moving the flake itself. Then she leaned closer and listened—because in her line of work, some things weren’t just seen.\n\nAt first there was only the rain and the distant rumble of traffic.\n\nThen—barely audible beneath it—a soft, rhythmic *tick… tick… tick*, like a clock inside something too small to be a clock.\n\nMara straightened slowly, her stomach tightening. The unusual clue wasn’t just out of place.\n\nIt was *alive* in a way she couldn’t explain.\n\nBehind her, the officer cleared his throat. “Detective? Should we—uh—call for your tech?”\n\nMara didn’t answer right away. She stared at the flake until her eyes began to ache, watching the light tremble within it like it was trying to form a message.\n\nFinally, she said, “Yeah. And bring two sets of gloves.”\n\nShe stood, turning toward the apartment interior where the air felt heavy with everything that had already happened.\n\nWhatever left this behind didn’t want to be caught.\n\nBut it had made sure she’d look—down at the seam between boards—at the moment her flashlight found it.\n\nAs if it knew exactly where her curiosity would go next.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470691,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnT1SUtcOln0seA0LbQDeFgl1Mdf",
  "model": "gpt-5.4-nano-2026-03-17",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 666,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 685
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-nano',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-nano",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
Recursion is a programming technique where a function solves a problem by calling itself on smaller versions of the same problem.

A key idea is that recursion usually needs:
1. **A base case** (when to stop).
2. **A recursive case** (the problem broken into a smaller subproblem).

### Simple Example: Factorial
The factorial of a number *n* (written `n!`) is:
- `n! = n × (n-1)!`
- with the base case `0! = 1`

#### Code (Python-like pseudocode)
```python
def factorial(n):
    if n == 0:          # base case
        return 1
    return n * factorial(n - 1)  # recursive case
```

#### What happens for `factorial(4)`?
- `factorial(4) = 4 * factorial(3)`
- `factorial(3) = 3 * factorial(2)`
- `factorial(2) = 2 * factorial(1)`
- `factorial(1) = 1 * factorial(0)`
- `factorial(0) = 1`

So: `4 * 3 * 2 * 1 = 24`

If you want, I can also show a recursion example like summing a list or traversing a tree.
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1776470696,
    "id": "chatcmpl-DVnT6eFAFifz1GeXTi6RbmQUsrFn2",
    "model": "gpt-5.4-nano-2026-03-17",
    "obfuscation": "Vug",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1776470696,
    "id": "chatcmpl-DVnT6eFAFifz1GeXTi6RbmQUsrFn2",
    "model": "gpt-5.4-nano-2026-03-17",
    "obfuscation": "l1",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  "... 279 more chunks omitted ...",
  {
    "choices": [],
    "created": 1776470696,
    "id": "chatcmpl-DVnT6eFAFifz1GeXTi6RbmQUsrFn2",
    "model": "gpt-5.4-nano-2026-03-17",
    "obfuscation": "1Z",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 282,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 16,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 298
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-nano',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-nano",
  "input": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
  "max_output_tokens": 4096,
  "tools": [
    {
      "type": "web_search_preview"
    }
  ]
}'
```

```
- **New Cloudflare One partner initiative for AI + SASE migrations:** Cloudflare announced a new “Cloudflare One Design Partner” designation (via its PowerUP program) and an AI-powered toolkit aimed at helping organizations modernize security/networking to SASE-style architectures. ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))  
- **Acquisition to expand Cloudflare’s AI-native dev tooling:** Cloudflare said it’s buying **VoidZero** (behind the Vite ecosystem and related tools like Vitest), with plans to integrate those assets into **Cloudflare Workers** and keep key parts open source. ([itpro.com](https://www.itpro.com/business/acquisition/cloudflare-snaps-up-voidzero-to-expand-ai-native-developer-tools?utm_source=openai))  
- **Operational / reliability chatter around recent Cloudflare issues:** Multiple outlets and community reports during the last week pointed to **service problems affecting customer traffic** (including discussions referencing Cloudflare’s status/incident activity). ([cloudflarestatus.com](https://www.cloudflarestatus.com/uptime?utm_source=openai))
```

```json
{
  "id": "resp_0e2e9c834e7f91cc016a39969473f0819a9f7395881d0a2709",
  "object": "response",
  "created_at": 1782158996,
  "model": "gpt-5.4-nano-2026-03-17",
  "output": [
    {
      "id": "ws_0e2e9c834e7f91cc016a399694e4e4819aae4e34fc9fbc5091",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news this week",
          "Cloudflare announcement June 2026",
          "Cloudflare funding acquisition partnership June 2026",
          "Cloudflare incident outage news"
        ],
        "query": "Cloudflare news this week"
      }
    },
    {
      "id": "ws_0e2e9c834e7f91cc016a3996967398819aa1ca74f93b3d30b0",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "site:blog.cloudflare.com 2026 Cloudflare June 2026",
          "Cloudflare June 2026 acquisition partnership June 2026 Reuters",
          "Cloudflare June 2026 earnings analyst news",
          "Cloudflare outage June 2026"
        ],
        "query": "site:blog.cloudflare.com 2026 Cloudflare June 2026"
      }
    },
    {
      "id": "msg_0e2e9c834e7f91cc016a399698556c819aaeac57e1b9b1c6e0",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 447,
              "start_index": 283,
              "title": "Cloudflare launches new partner initiative to support AI and SASE adoption",
              "url": "https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 851,
              "start_index": 711,
              "title": "Cloudflare snaps up VoidZero to expand AI-native developer tools",
              "url": "https://www.itpro.com/business/acquisition/cloudflare-snaps-up-voidzero-to-expand-ai-native-developer-tools?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 1204,
              "start_index": 1121,
              "title": "Cloudflare Status - Incident History",
              "url": "https://www.cloudflarestatus.com/uptime?utm_source=openai"
            }
          ],
          "logprobs": [],
          "text": "- **New Cloudflare One partner initiative for AI + SASE migrations:** Cloudflare announced a new “Cloudflare One Design Partner” designation (via its PowerUP program) and an AI-powered toolkit aimed at helping organizations modernize security/networking to SASE-style architectures. ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))  \n- **Acquisition to expand Cloudflare’s AI-native dev tooling:** Cloudflare said it’s buying **VoidZero** (behind the Vite ecosystem and related tools like Vitest), with plans to integrate those assets into **Cloudflare Workers** and keep key parts open source. ([itpro.com](https://www.itpro.com/business/acquisition/cloudflare-snaps-up-voidzero-to-expand-ai-native-developer-tools?utm_source=openai))  \n- **Operational / reliability chatter around recent Cloudflare issues:** Multiple outlets and community reports during the last week pointed to **service problems affecting customer traffic** (including discussions referencing Cloudflare’s status/incident activity). ([cloudflarestatus.com](https://www.cloudflarestatus.com/uptime?utm_source=openai))"
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "status": "completed",
  "usage": {
    "input_tokens": 12884,
    "output_tokens": 388,
    "total_tokens": 13272,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 173
    }
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1782159001,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 4096,
  "max_tool_calls": null,
  "moderation": null,
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "current_turn",
    "effort": "none",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "web_search_preview",
      "search_content_types": [
        "text"
      ],
      "search_context_size": "medium",
      "user_location": {
        "type": "approximate",
        "city": null,
        "country": "US",
        "region": null,
        "timezone": null
      }
    }
  ],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "user": null,
  "metadata": {},
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-nano/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-nano/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-nano/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-nano/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5.4-nano/#page","headline":"GPT-5.4 nano","description":"GPT-5.4 nano is OpenAI's smallest and fastest model, optimized for edge and low-latency use cases.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5.4-nano/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5.4 pro uses OpenAI's Responses API with built-in tools, improved reasoning, and stateful context management.
title: GPT-5.4 pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5.4 pro

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5.4-pro`

- Third-party
- Zero data retention

GPT-5.4 pro uses OpenAI's Responses API with built-in tools, improved reasoning, and stateful context management.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses |
| Pricing | <ul><li>Input (per 1M tokens)$30.00</li><li>Output (per 1M tokens)$180.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5.4-pro',
  { input: 'What are the three laws of thermodynamics?' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-pro",
  "input": "What are the three laws of thermodynamics?"
}'
```

```
The **three laws of thermodynamics** usually mean:

1. **First Law — Conservation of Energy**  
   Energy cannot be created or destroyed, only transferred or transformed.  
   - In thermodynamics: the change in a system’s internal energy equals heat added to the system minus work done by the system.

2. **Second Law — Entropy Increases**  
   In any natural process, the total entropy of an isolated system tends to increase.  
   - This means energy spontaneously spreads out, and no heat engine can be 100% efficient.
   - Heat naturally flows from hot objects to cold ones, not the reverse without input of work.

3. **Third Law — Entropy at Absolute Zero**  
   As temperature approaches **absolute zero** (0 K), the entropy of a perfect crystal approaches zero.  
   - A consequence is that absolute zero cannot be reached in a finite number of steps.

Small note: thermodynamics also has a **Zeroth Law**, which is often listed before these:
- If system A is in thermal equilibrium with B, and B is in thermal equilibrium with C, then A is in thermal equilibrium with C.  
- This is the basis for the concept of **temperature**.

If you want, I can also give a **one-line intuitive version** of each law.
```

```json
{
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1777054203,
  "created_at": 1777054122,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "resp_00272dd8da5b37c90169ebb1aaeb288194a6e5ddeb7bb03dc8",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {},
  "model": "gpt-5.4-pro-2026-03-05",
  "moderation": null,
  "object": "response",
  "output": [
    {
      "id": "rs_00272dd8da5b37c90169ebb1faf90c81948fd9a67a37b4c209",
      "summary": [],
      "type": "reasoning"
    },
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "The **three laws of thermodynamics** usually mean:\n\n1. **First Law — Conservation of Energy**  \n   Energy cannot be created or destroyed, only transferred or transformed.  \n   - In thermodynamics: the change in a system’s internal energy equals heat added to the system minus work done by the system.\n\n2. **Second Law — Entropy Increases**  \n   In any natural process, the total entropy of an isolated system tends to increase.  \n   - This means energy spontaneously spreads out, and no heat engine can be 100% efficient.\n   - Heat naturally flows from hot objects to cold ones, not the reverse without input of work.\n\n3. **Third Law — Entropy at Absolute Zero**  \n   As temperature approaches **absolute zero** (0 K), the entropy of a perfect crystal approaches zero.  \n   - A consequence is that absolute zero cannot be reached in a finite number of steps.\n\nSmall note: thermodynamics also has a **Zeroth Law**, which is often listed before these:\n- If system A is in thermal equilibrium with B, and B is in thermal equilibrium with C, then A is in thermal equilibrium with C.  \n- This is the basis for the concept of **temperature**.\n\nIf you want, I can also give a **one-line intuitive version** of each law.",
          "type": "output_text"
        }
      ],
      "id": "msg_00272dd8da5b37c90169ebb1fafad0819488ef71fbebf8527a",
      "phase": "final_answer",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "effort": "medium",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 15,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 342,
    "output_tokens_details": {
      "reasoning_tokens": 67
    },
    "total_tokens": 357
  },
  "user": null
}
```

## Examples

<details>

<summary>**With Instructions** — Using instructions to set context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-pro',
  {
    input: 'How do I read a JSON file in Python?',
    instructions: 'You are a helpful coding assistant specializing in Python.',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-pro",
  "input": "How do I read a JSON file in Python?",
  "instructions": "You are a helpful coding assistant specializing in Python."
}'
```

````
Use Python’s built-in `json` module.

### Read a JSON file into a Python object
```python
import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(data)
```

### What you get back
`json.load()` converts JSON into normal Python types:

- JSON object → `dict`
- JSON array → `list`
- JSON string → `str`
- JSON number → `int` / `float`
- JSON true/false → `True` / `False`
- JSON null → `None`

### Example
If `data.json` contains:
```json
{
  "name": "Alice",
  "age": 30,
  "skills": ["Python", "SQL"]
}
```

Then:
```python
import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(data["name"])    # Alice
print(data["skills"])  # ['Python', 'SQL']
```

### Handle errors safely
```python
import json

try:
    with open("data.json", "r", encoding="utf-8") as f:
        data = json.load(f)
except FileNotFoundError:
    print("File not found.")
except json.JSONDecodeError:
    print("Invalid JSON.")
```

### If you already have JSON as a string
Use `json.loads()` instead:
```python
import json

text = '{"name": "Alice", "age": 30}'
data = json.loads(text)
print(data)
```

If you want, I can also show how to **write JSON back to a file**.
````

```json
{
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1777054145,
  "created_at": 1777054123,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "resp_00e5a81e42bf0bda0169ebb1ab449c8190a0d57802b4aebebd",
  "incomplete_details": null,
  "instructions": "You are a helpful coding assistant specializing in Python.",
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {},
  "model": "gpt-5.4-pro-2026-03-05",
  "moderation": null,
  "object": "response",
  "output": [
    {
      "id": "rs_00e5a81e42bf0bda0169ebb1c0e57881909eaf01efa0557a43",
      "summary": [],
      "type": "reasoning"
    },
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "Use Python’s built-in `json` module.\n\n### Read a JSON file into a Python object\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n\nprint(data)\n```\n\n### What you get back\n`json.load()` converts JSON into normal Python types:\n\n- JSON object → `dict`\n- JSON array → `list`\n- JSON string → `str`\n- JSON number → `int` / `float`\n- JSON true/false → `True` / `False`\n- JSON null → `None`\n\n### Example\nIf `data.json` contains:\n```json\n{\n  \"name\": \"Alice\",\n  \"age\": 30,\n  \"skills\": [\"Python\", \"SQL\"]\n}\n```\n\nThen:\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n\nprint(data[\"name\"])    # Alice\nprint(data[\"skills\"])  # ['Python', 'SQL']\n```\n\n### Handle errors safely\n```python\nimport json\n\ntry:\n    with open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n        data = json.load(f)\nexcept FileNotFoundError:\n    print(\"File not found.\")\nexcept json.JSONDecodeError:\n    print(\"Invalid JSON.\")\n```\n\n### If you already have JSON as a string\nUse `json.loads()` instead:\n```python\nimport json\n\ntext = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(text)\nprint(data)\n```\n\nIf you want, I can also show how to **write JSON back to a file**.",
          "type": "output_text"
        }
      ],
      "id": "msg_00e5a81e42bf0bda0169ebb1c0e7608190b3928d22f252a21a",
      "phase": "final_answer",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "effort": "medium",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 30,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 397,
    "output_tokens_details": {
      "reasoning_tokens": 35
    },
    "total_tokens": 427
  },
  "user": null
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with message array</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-pro',
  {
    input: [
      {
        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, name three good stops in one short sentence each.', role: 'user' },
    ],
    max_output_tokens: 16000,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-pro",
  "input": [
    {
      "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, name three good stops in one short sentence each.",
      "role": "user"
    }
  ],
  "max_output_tokens": 16000
}'
```

```
- Monterey is great for the aquarium, Cannery Row, and ocean views.  
- San Luis Obispo is a fun lunch stop with a charming downtown and Mission Plaza.  
- Santa Barbara offers beaches, palm-lined streets, and an easy coastal break.
```

```json
{
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1777421276,
  "created_at": 1777421147,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "resp_08addd0821ac85160169f14b5b16d881968c58b918efd0d015",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 16000,
  "max_tool_calls": null,
  "metadata": {},
  "model": "gpt-5.4-pro-2026-03-05",
  "moderation": null,
  "object": "response",
  "output": [
    {
      "id": "rs_08addd0821ac85160169f14bdca35c819696eb984a7f0beead",
      "summary": [],
      "type": "reasoning"
    },
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "- Monterey is great for the aquarium, Cannery Row, and ocean views.  \n- San Luis Obispo is a fun lunch stop with a charming downtown and Mission Plaza.  \n- Santa Barbara offers beaches, palm-lined streets, and an easy coastal break.",
          "type": "output_text"
        }
      ],
      "id": "msg_08addd0821ac85160169f14bdca4ec8196a5b40b76291544f5",
      "phase": "final_answer",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "effort": "medium",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 78,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 104,
    "output_tokens_details": {
      "reasoning_tokens": 46
    },
    "total_tokens": 182
  },
  "user": null
}
```

</details>

<details>

<summary>**Temperature Control** — Using temperature for creative responses</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-pro',
  { input: 'Write a haiku about artificial intelligence', temperature: 1 },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-pro",
  "input": "Write a haiku about artificial intelligence",
  "temperature": 1
}'
```

```
Silent circuits dream  
Learning patterns in the dark  
Dawn wakes metal minds
```

```json
{
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1777054190,
  "created_at": 1777054156,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "resp_01b04056ffd5d9ac0169ebb1cc85348196a164e1d9e99ac1f5",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {},
  "model": "gpt-5.4-pro-2026-03-05",
  "moderation": null,
  "object": "response",
  "output": [
    {
      "id": "rs_01b04056ffd5d9ac0169ebb1ee42688196859b0cd089b7924c",
      "summary": [],
      "type": "reasoning"
    },
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "Silent circuits dream  \nLearning patterns in the dark  \nDawn wakes metal minds",
          "type": "output_text"
        }
      ],
      "id": "msg_01b04056ffd5d9ac0169ebb1ee44248196aa66c63d28c6a59b",
      "phase": "final_answer",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "effort": "medium",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 13,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 122,
    "output_tokens_details": {
      "reasoning_tokens": 101
    },
    "total_tokens": 135
  },
  "user": null
}
```

</details>

<details>

<summary>**With Reasoning** — Using reasoning effort for complex problems</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.4-pro',
  {
    input:
      'Solve this problem step by step: A train leaves Chicago at 60mph heading east. Another train leaves New York at 80mph heading west. They are 900 miles apart. When do they meet?',
    reasoning: { effort: 'medium' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.4-pro",
  "input": "Solve this problem step by step: A train leaves Chicago at 60mph heading east. Another train leaves New York at 80mph heading west. They are 900 miles apart. When do they meet?",
  "reasoning": {
    "effort": "medium"
  }
}'
```

```
Step 1: Find their combined speed since they are moving toward each other.

- Train from Chicago: **60 mph**
- Train from New York: **80 mph**

Combined speed:

**60 + 80 = 140 mph**

Step 2: Use the distance formula:

\[
\text{time}=\frac{\text{distance}}{\text{speed}}
\]

\[
\text{time}=\frac{900}{140}
\]

\[
\text{time}=6.428571\text{ hours}
\]

Step 3: Convert the decimal part to minutes.

\[
0.428571 \times 60 \approx 25.7 \text{ minutes}
\]

So they meet after about:

**6 hours 26 minutes**

Final answer: **The trains meet about 6 hours 26 minutes after they leave.**
```

```json
{
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1777054263,
  "created_at": 1777054191,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "resp_01e1e7671514bf440169ebb1ef8af88190b68b1e60a0cb59ed",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {},
  "model": "gpt-5.4-pro-2026-03-05",
  "moderation": null,
  "object": "response",
  "output": [
    {
      "id": "rs_01e1e7671514bf440169ebb236f1e88190931dc758c55a4050",
      "summary": [],
      "type": "reasoning"
    },
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "Step 1: Find their combined speed since they are moving toward each other.\n\n- Train from Chicago: **60 mph**\n- Train from New York: **80 mph**\n\nCombined speed:\n\n**60 + 80 = 140 mph**\n\nStep 2: Use the distance formula:\n\n\\[\n\\text{time}=\\frac{\\text{distance}}{\\text{speed}}\n\\]\n\n\\[\n\\text{time}=\\frac{900}{140}\n\\]\n\n\\[\n\\text{time}=6.428571\\text{ hours}\n\\]\n\nStep 3: Convert the decimal part to minutes.\n\n\\[\n0.428571 \\times 60 \\approx 25.7 \\text{ minutes}\n\\]\n\nSo they meet after about:\n\n**6 hours 26 minutes**\n\nFinal answer: **The trains meet about 6 hours 26 minutes after they leave.**",
          "type": "output_text"
        }
      ],
      "id": "msg_01e1e7671514bf440169ebb236f3a88190b6a99b6fc6389fde",
      "phase": "final_answer",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "effort": "medium",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 48,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 272,
    "output_tokens_details": {
      "reasoning_tokens": 88
    },
    "total_tokens": 320
  },
  "user": null
}
```

</details>

## Parameters

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.4-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5.4-pro/#page","headline":"GPT-5.4 pro","description":"GPT-5.4 pro uses OpenAI's Responses API with built-in tools, improved reasoning, and stateful context management.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5.4-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5.5 is OpenAI's flagship model with strong coding, reasoning, and multimodal capabilities.
title: GPT-5.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5.5

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5.5`

- Third-party
- Zero data retention

GPT-5.5 is OpenAI's flagship model with strong coding, reasoning, and multimodal capabilities.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$5.00</li><li>Output (per 1M tokens)$30.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5.5',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The **three laws of thermodynamics** are:

1. **First Law — Conservation of Energy**  
   Energy cannot be created or destroyed, only transferred or transformed.  
   In thermodynamics, this is often written as:  
   \[
   \Delta U = Q - W
   \]  
   where \(\Delta U\) is the change in internal energy, \(Q\) is heat added, and \(W\) is work done by the system.

2. **Second Law — Entropy Increases**  
   In an isolated system, entropy tends to increase over time.  
   This means natural processes tend to move toward greater disorder or energy dispersal, and heat flows spontaneously from hot objects to cold ones.

3. **Third Law — Absolute Zero Is Unattainable**  
   As the temperature of a perfect crystal approaches absolute zero, its entropy approaches zero.  
   It also implies that absolute zero, \(0\,K\), cannot be reached by any finite physical process.

There is also a **Zeroth Law**, which says that if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This is the basis for temperature measurement.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The **three laws of thermodynamics** are:\n\n1. **First Law — Conservation of Energy**  \n   Energy cannot be created or destroyed, only transferred or transformed.  \n   In thermodynamics, this is often written as:  \n   \\[\n   \\Delta U = Q - W\n   \\]  \n   where \\(\\Delta U\\) is the change in internal energy, \\(Q\\) is heat added, and \\(W\\) is work done by the system.\n\n2. **Second Law — Entropy Increases**  \n   In an isolated system, entropy tends to increase over time.  \n   This means natural processes tend to move toward greater disorder or energy dispersal, and heat flows spontaneously from hot objects to cold ones.\n\n3. **Third Law — Absolute Zero Is Unattainable**  \n   As the temperature of a perfect crystal approaches absolute zero, its entropy approaches zero.  \n   It also implies that absolute zero, \\(0\\,K\\), cannot be reached by any finite physical process.\n\nThere is also a **Zeroth Law**, which says that if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This is the basis for temperature measurement.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777055247,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DYFXL1K160il6W2QJPWy2h4LmF7Xr",
  "model": "gpt-5.5-2026-04-23",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 291,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 32,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 15,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 306
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.5',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5",
  "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"
    }
  ]
}'
```

````
You can read a JSON file in Python using the built-in `json` module.

```python
import json

with open("data.json", "r") as file:
    data = json.load(file)

print(data)
```

If `data.json` contains:

```json
{
  "name": "Alice",
  "age": 30
}
```

Then `data` will be a Python dictionary:

```python
{
    "name": "Alice",
    "age": 30
}
```

You can access values like this:

```python
print(data["name"])  # Alice
print(data["age"])   # 30
```

A slightly more explicit version with encoding:

```python
import json

with open("data.json", "r", encoding="utf-8") as file:
    data = json.load(file)
```

If you have a JSON string instead of a file, use `json.loads()`:

```python
import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)

print(data["name"])
```
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "You can read a JSON file in Python using the built-in `json` module.\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\") as file:\n    data = json.load(file)\n\nprint(data)\n```\n\nIf `data.json` contains:\n\n```json\n{\n  \"name\": \"Alice\",\n  \"age\": 30\n}\n```\n\nThen `data` will be a Python dictionary:\n\n```python\n{\n    \"name\": \"Alice\",\n    \"age\": 30\n}\n```\n\nYou can access values like this:\n\n```python\nprint(data[\"name\"])  # Alice\nprint(data[\"age\"])   # 30\n```\n\nA slightly more explicit version with encoding:\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as file:\n    data = json.load(file)\n```\n\nIf you have a JSON string instead of a file, use `json.loads()`:\n\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)\n\nprint(data[\"name\"])\n```",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777055247,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DYFXLJQFBS1K4LCprRF4eOgdbucx7",
  "model": "gpt-5.5-2026-04-23",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 232,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 262
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.5',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5",
  "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"
    }
  ]
}'
```

```
Absolutely — the best stops depend on whether you take the **scenic coastal route** or the **faster inland route**.

## Scenic Route: Highway 1 / 101
This is the classic California road trip route, best if you have **1–3 days**.

### Great stops from north to south
- **Half Moon Bay** – Coastal views, beaches, and a nice breakfast/lunch stop.
- **Santa Cruz** – Beach Boardwalk, surfing, casual food, fun atmosphere.
- **Monterey** – Monterey Bay Aquarium, Cannery Row, harbor views.
- **Carmel-by-the-Sea** – Beautiful village, beach, shops, and restaurants.
- **Big Sur** – One of the most scenic stretches in California. Stop at:
  - Bixby Bridge
  - Pfeiffer Beach
  - McWay Falls
- **San Simeon / Hearst Castle** – Tour Hearst Castle or see the elephant seals nearby.
- **Paso Robles** – Wine tasting and good restaurants, especially if you cut inland.
- **San Luis Obispo** – Great overnight stop; downtown, Mission Plaza, good food.
- **Pismo Beach** – Beach stop, pier, clam chowder.
- **Solvang** – Danish-style town with bakeries, wine tasting, and cute streets.
- **Santa Barbara** – One of the best stops: beaches, State Street, the courthouse, Funk Zone.
- **Malibu** – Scenic coastal drive, beaches, and a final stop before LA.

## Faster Route: I-5
Best if you want to get to LA quickly, about **5.5–6.5 hours** depending on traffic.

Good practical stops:
- **Casa de Fruta** – Roadside stop with snacks, fruit, and restrooms.
- **Harris Ranch** – Popular meal stop, especially for steak.
- **Kettleman City** – Gas, food, and a good halfway break.
- **Tejon Ranch / Grapevine area** – Final major stop before entering LA traffic.

## My recommendation
If you have the time, do at least **one overnight** and take the coast:

**Day 1:** San Francisco → Santa Cruz → Monterey/Carmel → Big Sur → San Luis Obispo  
**Day 2:** San Luis Obispo → Solvang → Santa Barbara → Malibu → Los Angeles

Also, check current road conditions for **Highway 1 near Big Sur**, since closures can happen due to landslides.
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "choices": [
      {
        "finish_reason": "stop",
        "index": 0,
        "message": {
          "annotations": [],
          "content": "Absolutely — the best stops depend on whether you take the **scenic coastal route** or the **faster inland route**.\n\n## Scenic Route: Highway 1 / 101\nThis is the classic California road trip route, best if you have **1–3 days**.\n\n### Great stops from north to south\n- **Half Moon Bay** – Coastal views, beaches, and a nice breakfast/lunch stop.\n- **Santa Cruz** – Beach Boardwalk, surfing, casual food, fun atmosphere.\n- **Monterey** – Monterey Bay Aquarium, Cannery Row, harbor views.\n- **Carmel-by-the-Sea** – Beautiful village, beach, shops, and restaurants.\n- **Big Sur** – One of the most scenic stretches in California. Stop at:\n  - Bixby Bridge\n  - Pfeiffer Beach\n  - McWay Falls\n- **San Simeon / Hearst Castle** – Tour Hearst Castle or see the elephant seals nearby.\n- **Paso Robles** – Wine tasting and good restaurants, especially if you cut inland.\n- **San Luis Obispo** – Great overnight stop; downtown, Mission Plaza, good food.\n- **Pismo Beach** – Beach stop, pier, clam chowder.\n- **Solvang** – Danish-style town with bakeries, wine tasting, and cute streets.\n- **Santa Barbara** – One of the best stops: beaches, State Street, the courthouse, Funk Zone.\n- **Malibu** – Scenic coastal drive, beaches, and a final stop before LA.\n\n## Faster Route: I-5\nBest if you want to get to LA quickly, about **5.5–6.5 hours** depending on traffic.\n\nGood practical stops:\n- **Casa de Fruta** – Roadside stop with snacks, fruit, and restrooms.\n- **Harris Ranch** – Popular meal stop, especially for steak.\n- **Kettleman City** – Gas, food, and a good halfway break.\n- **Tejon Ranch / Grapevine area** – Final major stop before entering LA traffic.\n\n## My recommendation\nIf you have the time, do at least **one overnight** and take the coast:\n\n**Day 1:** San Francisco → Santa Cruz → Monterey/Carmel → Big Sur → San Luis Obispo  \n**Day 2:** San Luis Obispo → Solvang → Santa Barbara → Malibu → Los Angeles\n\nAlso, check current road conditions for **Highway 1 near Big Sur**, since closures can happen due to landslides.",
          "refusal": null,
          "role": "assistant"
        }
      }
    ],
    "created": 1777055396,
    "id": "chatcmpl-DYFZkYd5fz0fm7iFcu6jZFKFuSxKA",
    "model": "gpt-5.5-2026-04-23",
    "object": "chat.completion",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 623,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 93,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 76,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 699
    }
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.5',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
Detective Mara Venn found the clue inside the grandfather clock, though the clock had not worked in twenty years.

The house was silent around her, all velvet shadows and rain-streaked windows, the kind of silence that made every breath feel borrowed. Lord Edevane’s body lay in the study below, surrounded by overturned books, broken glass, and enough obvious evidence to make Mara immediately distrust all of it.

She had come upstairs only because of the ticking.

It was faint, irregular, and impossible.

Mara opened the clock’s warped oak door and raised her lantern. No weights. No pendulum. No mechanism at all.

Just a small glass vial hanging from a red thread.

Inside the vial was a single human tooth, etched with three tiny words in gold:

**ASK THE DEAD.**
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Detective Mara Venn found the clue inside the grandfather clock, though the clock had not worked in twenty years.\n\nThe house was silent around her, all velvet shadows and rain-streaked windows, the kind of silence that made every breath feel borrowed. Lord Edevane’s body lay in the study below, surrounded by overturned books, broken glass, and enough obvious evidence to make Mara immediately distrust all of it.\n\nShe had come upstairs only because of the ticking.\n\nIt was faint, irregular, and impossible.\n\nMara opened the clock’s warped oak door and raised her lantern. No weights. No pendulum. No mechanism at all.\n\nJust a small glass vial hanging from a red thread.\n\nInside the vial was a single human tooth, etched with three tiny words in gold:\n\n**ASK THE DEAD.**",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777055252,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DYFXQ7OpB748Ysf32CgoYeohlL1Qm",
  "model": "gpt-5.5-2026-04-23",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 180,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 8,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 199
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.5',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
Recursion is when a function solves a problem by calling itself with a smaller or simpler version of the same problem.

A recursion usually has two parts:

1. **Base case**: when to stop calling itself.
2. **Recursive case**: the part where the function calls itself.

Example: counting down from a number.

```python
def countdown(n):
    if n == 0:          # base case
        print("Done!")
    else:
        print(n)
        countdown(n - 1) # recursive case

countdown(3)
```

Output:

```text
3
2
1
Done!
```

Here is what happens:

- `countdown(3)` prints `3`, then calls `countdown(2)`
- `countdown(2)` prints `2`, then calls `countdown(1)`
- `countdown(1)` prints `1`, then calls `countdown(0)`
- `countdown(0)` reaches the base case and stops

So, recursion is like breaking a problem into smaller versions of itself until reaching a stopping point.
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777055295,
    "id": "chatcmpl-DYFY7TPENOUYNWL4XUE07mP4N37Jp",
    "model": "gpt-5.5-2026-04-23",
    "obfuscation": "5EGG4gGR",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777055295,
    "id": "chatcmpl-DYFY7TPENOUYNWL4XUE07mP4N37Jp",
    "model": "gpt-5.5-2026-04-23",
    "obfuscation": "PC9MLZ9",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  "... 225 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777055295,
    "id": "chatcmpl-DYFY7TPENOUYNWL4XUE07mP4N37Jp",
    "model": "gpt-5.5-2026-04-23",
    "obfuscation": "0lMavgk",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 228,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 16,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 244
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.5',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5",
  "input": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
  "max_output_tokens": 4096,
  "tools": [
    {
      "type": "web_search_preview"
    }
  ]
}'
```

```
Treating “this week” as **June 15–22, 2026**:

- **Cloudflare had a North America/Europe-impacting service incident on June 22.** Its status page said increased error rates and latency began at **13:35 UTC**, affecting **Analytics, CDN/Cache, and Durable Objects**; Cloudflare later pointed to a **fiber cut in Eastern North America** and said traffic-engineering work had mitigated most congestion/packet drops by the afternoon. ([cloudflarestatus.com](https://www.cloudflarestatus.com/incidents/v3yl7jqmqj51))

- **Cloudflare pushed harder into AI-assisted Zero Trust/SASE deployments.** It launched the **Cloudflare One Stack**, a set of agent “skills” for configuring, migrating, and managing Zero Trust environments, alongside a new **Cloudflare One Design Partner** initiative aimed at partners helping customers move from legacy security architectures; early named partners included Arctiq, Consortium, CMT, Presidio, and The Missing Link. ([blog.cloudflare.com](https://blog.cloudflare.com/cloudflare-one-stack/))

- **Cloudflare advanced its “AI agents can build and deploy” strategy.** It introduced **Temporary Cloudflare Accounts for AI agents**, letting agents use `wrangler deploy --temporary` to ship Workers without a prior account for a 60-minute claim window, and also opened more Agents SDK primitives to frameworks such as **Flue** for durable, production-grade agent workflows. ([blog.cloudflare.com](https://blog.cloudflare.com/temporary-accounts/))
```

```json
{
  "id": "resp_04a2eb20ce6ad6f8016a3999229868819ba43a3002b7e5e301",
  "object": "response",
  "created_at": 1782159650,
  "model": "gpt-5.5-2026-04-23",
  "output": [
    {
      "id": "rs_04a2eb20ce6ad6f8016a399923112c819bbabc8ec848f597e2",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a399923ced4819b94eb840567ee5fc1",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news this week June 2026 Cloudflare",
          "Cloudflare latest news June 2026",
          "site:blog.cloudflare.com Cloudflare June 2026",
          "Cloudflare stock news this week June 2026"
        ],
        "query": "Cloudflare news this week June 2026 Cloudflare"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a3999282ad8819ba080a8ddfee09e0e",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a39992838d8819b82979350fb85558b",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare outage June 22 2026 status incident",
          "Cloudflare June 22 2026 outage",
          "Cloudflare launches partner initiative AI SASE adoption June 18 2026",
          "Cloudflare news June 17 2026"
        ],
        "query": "Cloudflare outage June 22 2026 status incident"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a39992b85b8819b8494e22e7f1ade54",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a39992b9090819b868cc4de44726b49",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "site:blog.cloudflare.com June 18 2026 Cloudflare blog",
          "site:blog.cloudflare.com June 17 2026 Cloudflare blog",
          "site:blog.cloudflare.com June 16 2026 Cloudflare blog",
          "site:blog.cloudflare.com June 15 2026 Cloudflare blog"
        ],
        "query": "site:blog.cloudflare.com June 18 2026 Cloudflare blog"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a39992d42b8819b91e73be8db39cf7f",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a39992d7720819bb7a20bb6db6d12a7",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.cloudflarestatus.com/uptime"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a39992eccb0819ba2f60db633880269",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a39992f55d4819b90baed7dcc1189b4",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.cloudflarestatus.com/incidents/v3yl7jqmqj51"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a3999317194819b8aa69341a57c7022",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a3999321808819b8065a8f50825261d",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare after:2026-06-15 before:2026-06-23 news",
          "Cloudflare site:reuters.com after:2026-06-15 before:2026-06-23",
          "Cloudflare site:finance.yahoo.com after:2026-06-15 before:2026-06-23",
          "Cloudflare site:investors.com after:2026-06-15 before:2026-06-23"
        ],
        "query": "Cloudflare after:2026-06-15 before:2026-06-23 news"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a3999393be8819bb6199dd097e3c451",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a39993a4038819bb990a96c3388c97f",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare Flue agent harnesses frameworks June 2026",
          "site:blog.cloudflare.com Flue Cloudflare June 2026",
          "\"Bringing more agent harnesses\" Cloudflare",
          "Cloudflare AI Agents SDK Flue June 2026"
        ],
        "query": "Cloudflare Flue agent harnesses frameworks June 2026"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a399941a9ec819b9772297dbafe616a",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a399941c820819b9c737c5bbac428a5",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://noise.getoto.net/2026/06/17/bringing-more-agent-harnesses-and-frameworks-to-cloudflare-starting-with-flue/"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a399943832c819bb678926f11223a00",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a399943e4d0819bbfeb601cd55a683d",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://blog.cloudflare.com/agents-platform-flue-sdk/"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a399945c25c819b8329904bba285bd7",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a3999491ed0819b8c1623b7545fca7a",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://blog.cloudflare.com/temporary-cloudflare-accounts-for-ai-agents/"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a39994b78d0819b8e663097a07806c8",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a39994bb2c4819bb73593fb0cf46293",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://blog.cloudflare.com/agents-platform-flue-sdk/"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a39994f2f9c819b9088ecfeb3e06e00",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_04a2eb20ce6ad6f8016a39994f902c819bb852d31e550d7771",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://blog.cloudflare.com/temporary-accounts/"
      }
    },
    {
      "id": "rs_04a2eb20ce6ad6f8016a399950fae4819ba302f413d4bfaf40",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "msg_04a2eb20ce6ad6f8016a399953b544819ba7651b7966a4cb7e",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 511,
              "start_index": 430,
              "title": "Cloudflare Status - Increased Error Rates",
              "url": "https://www.cloudflarestatus.com/incidents/v3yl7jqmqj51"
            },
            {
              "type": "url_citation",
              "end_index": 1021,
              "start_index": 947,
              "title": "Introducing the Cloudflare One stack: agent-powered deployment",
              "url": "https://blog.cloudflare.com/cloudflare-one-stack/"
            },
            {
              "type": "url_citation",
              "end_index": 1471,
              "start_index": 1399,
              "title": "Temporary Cloudflare Accounts for AI agents",
              "url": "https://blog.cloudflare.com/temporary-accounts/"
            }
          ],
          "logprobs": [],
          "text": "Treating “this week” as **June 15–22, 2026**:\n\n- **Cloudflare
... response truncated ...
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5.5/#page","headline":"GPT-5.5","description":"GPT-5.5 is OpenAI's flagship model with strong coding, reasoning, and multimodal capabilities.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5.5 pro uses OpenAI's Responses API with built-in tools, improved reasoning, and stateful context management.
title: GPT-5.5 pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5.5 pro

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5.5-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5.5-pro`

- Third-party
- Zero data retention

GPT-5.5 pro uses OpenAI's Responses API with built-in tools, improved reasoning, and stateful context management.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses |
| Pricing | <ul><li>Input (per 1M tokens)$30.00</li><li>Output (per 1M tokens)$180.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5.5-pro',
  { input: 'What are the three laws of thermodynamics?' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5-pro",
  "input": "What are the three laws of thermodynamics?"
}'
```

```
The **three laws of thermodynamics** are:

1. **First Law — Conservation of Energy**  
   Energy cannot be created or destroyed, only transferred or transformed.  
   In thermodynamics: the change in a system’s internal energy equals heat added to the system minus work done by the system.  
   \[
   \Delta U = Q - W
   \]

2. **Second Law — Entropy Increases**  
   In any natural process, the total entropy of an isolated system tends to increase.  
   Equivalently, heat flows spontaneously from hotter objects to colder ones, and no heat engine can be 100% efficient.

3. **Third Law — Absolute Zero Limit**  
   As temperature approaches absolute zero, the entropy of a perfect crystal approaches zero.  
   It also implies that absolute zero cannot be reached by any finite physical process.

There is also a **Zeroth Law**, often stated separately: if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This is what makes temperature well-defined.
```

```json
{
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1777054314,
  "created_at": 1777054206,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "resp_063e06a488467aad0169ebb1fc91d4819081d5cf054ee32daa",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {},
  "model": "gpt-5.5-pro-2026-04-23",
  "moderation": null,
  "object": "response",
  "output": [
    {
      "id": "rs_063e06a488467aad0169ebb262c1408190aa715f10dd4763dc",
      "summary": [],
      "type": "reasoning"
    },
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "The **three laws of thermodynamics** are:\n\n1. **First Law — Conservation of Energy**  \n   Energy cannot be created or destroyed, only transferred or transformed.  \n   In thermodynamics: the change in a system’s internal energy equals heat added to the system minus work done by the system.  \n   \\[\n   \\Delta U = Q - W\n   \\]\n\n2. **Second Law — Entropy Increases**  \n   In any natural process, the total entropy of an isolated system tends to increase.  \n   Equivalently, heat flows spontaneously from hotter objects to colder ones, and no heat engine can be 100% efficient.\n\n3. **Third Law — Absolute Zero Limit**  \n   As temperature approaches absolute zero, the entropy of a perfect crystal approaches zero.  \n   It also implies that absolute zero cannot be reached by any finite physical process.\n\nThere is also a **Zeroth Law**, often stated separately: if two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This is what makes temperature well-defined.",
          "type": "output_text"
        }
      ],
      "id": "msg_063e06a488467aad0169ebb262c45c819093301855572fac7f",
      "phase": "final_answer",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "24h",
  "reasoning": {
    "effort": "high",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 15,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 293,
    "output_tokens_details": {
      "reasoning_tokens": 66
    },
    "total_tokens": 308
  },
  "user": null
}
```

## Examples

<details>

<summary>**With Instructions** — Using instructions to set context</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.5-pro',
  {
    input: 'How do I read a JSON file in Python?',
    instructions: 'You are a helpful coding assistant specializing in Python.',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5-pro",
  "input": "How do I read a JSON file in Python?",
  "instructions": "You are a helpful coding assistant specializing in Python."
}'
```

````
Use Python’s built-in `json` module:

```python
import json

with open("data.json", "r", encoding="utf-8") as file:
    data = json.load(file)

print(data)
```

If `data.json` contains:

```json
{
  "name": "Alice",
  "age": 30
}
```

Then `data` will be a Python dictionary:

```python
print(data["name"])  # Alice
print(data["age"])   # 30
```

You can also handle common errors:

```python
import json

try:
    with open("data.json", "r", encoding="utf-8") as file:
        data = json.load(file)

    print(data)

except FileNotFoundError:
    print("The JSON file was not found.")

except json.JSONDecodeError:
    print("The file is not valid JSON.")
```

Use `json.load(file)` for reading from a file, and `json.loads(string)` for parsing a JSON string.
````

```json
{
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1777054286,
  "created_at": 1777054264,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "resp_0a5627201ea32bd60169ebb23813c081978bb6448d3757ad16",
  "incomplete_details": null,
  "instructions": "You are a helpful coding assistant specializing in Python.",
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {},
  "model": "gpt-5.5-pro-2026-04-23",
  "moderation": null,
  "object": "response",
  "output": [
    {
      "id": "rs_0a5627201ea32bd60169ebb24e286081979a18901a559d3252",
      "summary": [],
      "type": "reasoning"
    },
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "Use Python’s built-in `json` module:\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as file:\n    data = json.load(file)\n\nprint(data)\n```\n\nIf `data.json` contains:\n\n```json\n{\n  \"name\": \"Alice\",\n  \"age\": 30\n}\n```\n\nThen `data` will be a Python dictionary:\n\n```python\nprint(data[\"name\"])  # Alice\nprint(data[\"age\"])   # 30\n```\n\nYou can also handle common errors:\n\n```python\nimport json\n\ntry:\n    with open(\"data.json\", \"r\", encoding=\"utf-8\") as file:\n        data = json.load(file)\n\n    print(data)\n\nexcept FileNotFoundError:\n    print(\"The JSON file was not found.\")\n\nexcept json.JSONDecodeError:\n    print(\"The file is not valid JSON.\")\n```\n\nUse `json.load(file)` for reading from a file, and `json.loads(string)` for parsing a JSON string.",
          "type": "output_text"
        }
      ],
      "id": "msg_0a5627201ea32bd60169ebb24e2a148197917120444493cfa0",
      "phase": "final_answer",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "24h",
  "reasoning": {
    "effort": "high",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 30,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 387,
    "output_tokens_details": {
      "reasoning_tokens": 170
    },
    "total_tokens": 417
  },
  "user": null
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with message array</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.5-pro',
  {
    input: [
      {
        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, name three good stops in one short sentence each.', role: 'user' },
    ],
    max_output_tokens: 16000,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5-pro",
  "input": [
    {
      "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, name three good stops in one short sentence each.",
      "role": "user"
    }
  ],
  "max_output_tokens": 16000
}'
```

```
- Monterey/Carmel is great for beaches, seafood, and a quick scenic stroll.  
- Big Sur offers dramatic ocean views, Bixby Bridge, and McWay Falls.  
- Santa Barbara is perfect for lunch, State Street, and Stearns Wharf.
```

```json
{
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1777421264,
  "created_at": 1777421233,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "resp_01ed6abc47bd85fc0169f14bb1332481968b1628177ee39463",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 16000,
  "max_tool_calls": null,
  "metadata": {},
  "model": "gpt-5.5-pro-2026-04-23",
  "moderation": null,
  "object": "response",
  "output": [
    {
      "id": "rs_01ed6abc47bd85fc0169f14bcfd2508196b39551bf06fa05b5",
      "summary": [],
      "type": "reasoning"
    },
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "- Monterey/Carmel is great for beaches, seafood, and a quick scenic stroll.  \n- Big Sur offers dramatic ocean views, Bixby Bridge, and McWay Falls.  \n- Santa Barbara is perfect for lunch, State Street, and Stearns Wharf.",
          "type": "output_text"
        }
      ],
      "id": "msg_01ed6abc47bd85fc0169f14bcfd38c81968fbe4768d5cc9b0f",
      "phase": "final_answer",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "24h",
  "reasoning": {
    "effort": "high",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 78,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 251,
    "output_tokens_details": {
      "reasoning_tokens": 191
    },
    "total_tokens": 329
  },
  "user": null
}
```

</details>

<details>

<summary>**Temperature Control** — Using temperature for creative responses</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.5-pro',
  { input: 'Write a haiku about artificial intelligence', temperature: 1 },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5-pro",
  "input": "Write a haiku about artificial intelligence",
  "temperature": 1
}'
```

```
Silent circuits dream  
Learning patterns in starlight  
Dawn hums through the code
```

```json
{
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1777054304,
  "created_at": 1777054296,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "resp_0861b6980fc9f4ab0169ebb2585a388196b5ae496c923d5c46",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {},
  "model": "gpt-5.5-pro-2026-04-23",
  "moderation": null,
  "object": "response",
  "output": [
    {
      "id": "rs_0861b6980fc9f4ab0169ebb260b08c81968600b365effb3d15",
      "summary": [],
      "type": "reasoning"
    },
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "Silent circuits dream  \nLearning patterns in starlight  \nDawn hums through the code",
          "type": "output_text"
        }
      ],
      "id": "msg_0861b6980fc9f4ab0169ebb260b29c81968b2573cb5b00befc",
      "phase": "final_answer",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "24h",
  "reasoning": {
    "effort": "high",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 13,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 121,
    "output_tokens_details": {
      "reasoning_tokens": 97
    },
    "total_tokens": 134
  },
  "user": null
}
```

</details>

<details>

<summary>**With Reasoning** — Using reasoning effort for complex problems</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.5-pro',
  {
    input:
      'Solve this problem step by step: A train leaves Chicago at 60mph heading east. Another train leaves New York at 80mph heading west. They are 900 miles apart. When do they meet?',
    reasoning: { effort: 'medium' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5-pro",
  "input": "Solve this problem step by step: A train leaves Chicago at 60mph heading east. Another train leaves New York at 80mph heading west. They are 900 miles apart. When do they meet?",
  "reasoning": {
    "effort": "medium"
  }
}'
```

```
Assuming both trains leave at the same time:

1. Train from Chicago speed: **60 mph**
2. Train from New York speed: **80 mph**
3. Since they are moving toward each other, add their speeds:

\[
60 + 80 = 140 \text{ mph}
\]

4. They are **900 miles** apart, so time is:

\[
\text{time} = \frac{900}{140}
\]

\[
\text{time} = 6.428571\ldots \text{ hours}
\]

5. Convert the decimal part:

\[
0.428571 \times 60 \approx 25.7 \text{ minutes}
\]

So they meet after about:

\[
\boxed{6 \text{ hours } 26 \text{ minutes}}
\]

More exactly, they meet after **6 hours, 25 minutes, and 43 seconds**.
```

```json
{
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1777054312,
  "created_at": 1777054305,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "resp_03fc3b8888c0aecf0169ebb2616f408195b4462e87d425924a",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {},
  "model": "gpt-5.5-pro-2026-04-23",
  "moderation": null,
  "object": "response",
  "output": [
    {
      "id": "rs_03fc3b8888c0aecf0169ebb2684a4c8195b4fd258c0d92977d",
      "summary": [],
      "type": "reasoning"
    },
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "Assuming both trains leave at the same time:\n\n1. Train from Chicago speed: **60 mph**\n2. Train from New York speed: **80 mph**\n3. Since they are moving toward each other, add their speeds:\n\n\\[\n60 + 80 = 140 \\text{ mph}\n\\]\n\n4. They are **900 miles** apart, so time is:\n\n\\[\n\\text{time} = \\frac{900}{140}\n\\]\n\n\\[\n\\text{time} = 6.428571\\ldots \\text{ hours}\n\\]\n\n5. Convert the decimal part:\n\n\\[\n0.428571 \\times 60 \\approx 25.7 \\text{ minutes}\n\\]\n\nSo they meet after about:\n\n\\[\n\\boxed{6 \\text{ hours } 26 \\text{ minutes}}\n\\]\n\nMore exactly, they meet after **6 hours, 25 minutes, and 43 seconds**.",
          "type": "output_text"
        }
      ],
      "id": "msg_03fc3b8888c0aecf0169ebb2684bc0819589f472918a0073f2",
      "phase": "final_answer",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "24h",
  "reasoning": {
    "effort": "medium",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 48,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 381,
    "output_tokens_details": {
      "reasoning_tokens": 182
    },
    "total_tokens": 429
  },
  "user": null
}
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.5-pro',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.5-pro",
  "input": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
  "max_output_tokens": 4096,
  "tools": [
    {
      "type": "web_search_preview"
    }
  ]
}'
```

```
Assuming **“this week” = Jun 16–22, 2026**:

- **Cloudflare service incident:** Cloudflare reported increased error rates/latency from 13:35 UTC today, affecting Analytics, CDN/Cache and Durable Objects; it later pointed to a fiber cut in Eastern North America and said traffic engineering had mitigated most congestion/packet loss. ([cloudflarestatus.com](https://www.cloudflarestatus.com/incidents/v3yl7jqmqj51))
- **New anti-bot/privacy protocol:** Cloudflare announced work with Mozilla Firefox, Google Chrome, Microsoft Edge and Shopify on **Private Access Control Tokens (PACT)**, meant to verify legitimate humans/agents without CAPTCHAs or invasive tracking. ([cloudflare.com](https://www.cloudflare.com/press/press-releases/2026/cloudflare-collaborates-with-leading-browsers-to-develop-a-privacy-first-protocol-for-the-global-internet/))
- **AI + SASE partner push:** Cloudflare launched a **Cloudflare One Design Partner** program and **Cloudflare One Stack**, giving select partners AI-powered workflows to help customers deploy and manage Zero Trust/SASE migrations. ([cloudflare.com](https://www.cloudflare.com/press/press-releases/2026/cloudflare-launches-design-partner-designation-to-accelerate-secure-ai-and-seamless-sase-adoption/))
```

```json
{
  "id": "resp_0fe61a92ccd82def016a3999c63130819a802271120be10eb8",
  "object": "response",
  "created_at": 1782159814,
  "model": "gpt-5.5-pro-2026-04-23",
  "output": [
    {
      "id": "rs_0fe61a92ccd82def016a399a21cc1c819abf92ab7bc7693b91",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0fe61a92ccd82def016a399a21d2bc819ab3ca33a96dbae75b",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news this week June 2026",
          "Cloudflare latest news June 2026",
          "site:blog.cloudflare.com Cloudflare June 2026",
          "Cloudflare stock news June 2026"
        ],
        "query": "Cloudflare news this week June 2026"
      }
    },
    {
      "id": "rs_0fe61a92ccd82def016a399a23240c819abcb66f4e6074d9bb",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0fe61a92ccd82def016a399a233940819a886fe58c76af4475",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare June 22 2026 outage",
          "Cloudflare outage June 22 2026",
          "Cloudflare news June 22 2026",
          "Cloudflare news June 18 2026"
        ],
        "query": "Cloudflare June 22 2026 outage"
      }
    },
    {
      "id": "rs_0fe61a92ccd82def016a399a26503c819aa08c657db048d931",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0fe61a92ccd82def016a399a266c3c819a9c2ab66307ca1f26",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.cloudflarestatus.com/"
      }
    },
    {
      "id": "rs_0fe61a92ccd82def016a399a26f1cc819a9e03d45e77d279df",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0fe61a92ccd82def016a399a2716f4819a9192da4315b2d3d4",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.cloudflarestatus.com/incidents/v3yl7jqmqj51"
      }
    },
    {
      "id": "rs_0fe61a92ccd82def016a399a27525c819a8a61f7405ee19d00",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0fe61a92ccd82def016a399a276a7c819a99477a5b3d1eeaba",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.cloudflare.com/press/press-releases/"
      }
    },
    {
      "id": "rs_0fe61a92ccd82def016a399a27c9b4819aa415421854c8a235",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0fe61a92ccd82def016a399a27e6f0819aad66447fbfd41467",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.cloudflare.com/press/press-releases/2026/cloudflare-launches-design-partner-designation-to-accelerate-secure-ai-and-seamless-sase-adoption/"
      }
    },
    {
      "id": "rs_0fe61a92ccd82def016a399a28247c819aa2f43a2401eed9a2",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0fe61a92ccd82def016a399a2840a4819aa0ce23de6ec658cb",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare PACT privacy-first protocol browsers news June 22 2026",
          "Cloudflare leading browsers PACT Mozilla Google Microsoft Shopify June 22 2026",
          "Cloudflare One Stack agent-powered deployment news June 17 2026",
          "Cloudflare Design Partner Cloudflare One Stack SASE adoption June 17 2026"
        ],
        "query": "Cloudflare PACT privacy-first protocol browsers news June 22 2026"
      }
    },
    {
      "id": "rs_0fe61a92ccd82def016a399a2ec420819a8391167e995a57d9",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0fe61a92ccd82def016a399a2ef608819a9cbcc945e42d0791",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare June 2026 latest site:theregister.com",
          "Cloudflare June 2026 latest site:bleepingcomputer.com OR site:thehackernews.com",
          "Cloudflare June 2026 \"June 22\" \"error rates\"",
          "Cloudflare June 2026 \"PACT\" \"Private Access Control Tokens\""
        ],
        "query": "Cloudflare June 2026 latest site:theregister.com"
      }
    },
    {
      "id": "rs_0fe61a92ccd82def016a399a340edc819a95e0c1e4b5614f10",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0fe61a92ccd82def016a399a349134819ab8bc982a5aa737ad",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare",
          "Cloudflare news",
          "Cloudflare outage",
          "Cloudflare PACT"
        ],
        "query": "Cloudflare"
      }
    },
    {
      "id": "rs_0fe61a92ccd82def016a399a3e086c819aab8c4070f38deb93",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0fe61a92ccd82def016a399a3e3d44819aa420a1a6e9206955",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "site:blog.cloudflare.com/ 2026/06/17 Cloudflare",
          "site:blog.cloudflare.com/ 2026/06/18 Cloudflare",
          "site:blog.cloudflare.com/ 2026/06/19 Cloudflare",
          "site:blog.cloudflare.com/ 2026/06/22 Cloudflare"
        ],
        "query": "site:blog.cloudflare.com/ 2026/06/17 Cloudflare"
      }
    },
    {
      "id": "rs_0fe61a92ccd82def016a399a416410819a99bdad035902ddd9",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0fe61a92ccd82def016a399a41a87c819a918ac53a59f75243",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://blog.cloudflare.com/cloudflare-one-stack/"
      }
    },
    {
      "id": "rs_0fe61a92ccd82def016a399a42968c819a9016993c608908de",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "msg_0fe61a92ccd82def016a399a42a7f8819aa00992b84608e5ac",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 414,
              "start_index": 333,
              "title": "Cloudflare Status - Increased Error Rates",
              "url": "https://www.cloudflarestatus.com/incidents/v3yl7jqmqj51"
            },
            {
              "type": "url_citation",
              "end_index": 846,
              "start_index": 667,
              "title": "www.cloudflare.com",
              "url": "https://www.cloudflare.com/press/press-releases/2026/cloudflare-collaborates-with-leading-browsers-to-develop-a-privacy-first-protocol-for-the-global-internet/"
            },
            {
              "type": "url_citation",
              "end_index": 1250,
              "start_index": 1079,
              "title": "www.cloudflare.com",
              "url": "https://www.cloudflare.com/press/press-releases/2026/cloudflare-launches-design-partner-designation-to-accelerate-secure-ai-and-seamless-sase-adoption/"
            }
          ],
          "logprobs": [],
          "text": "Assuming **“this week” = Jun 16–22, 2026**:\n\n- **Cloudflare service incident:** Cloudflare reported increased error rates/latency from 13:35 UTC today, affecting Analytics, CDN/Cache and Durable Objects; it later pointed to a fiber cut in Eastern North Americ
... response truncated ...
```

</details>

## Parameters

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.5-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.5-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.5-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.5-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5.5-pro/#page","headline":"GPT-5.5 pro","description":"GPT-5.5 pro uses OpenAI's Responses API with built-in tools, improved reasoning, and stateful context management.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5.5-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5.6 Luna is an OpenAI GPT-5.6 model optimized for cost-sensitive workloads, using the Responses API for efficient text generation.
title: GPT-5.6 Luna
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5.6 Luna

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-luna/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5.6-luna`

- Third-party

GPT-5.6 Luna is an OpenAI GPT-5.6 model optimized for cost-sensitive workloads, using the Responses API for efficient text generation.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,050,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Request formats | Responses |
| Pricing | <ul><li>Input (per 1M tokens)$0.20</li><li>Output (per 1M tokens)$1.20</li><li>Cached input (per 1M tokens)$0.02</li><li>Cache creation (per 1M tokens)$0.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5.6-luna',
  {
    input: 'Summarize the benefits of API rate limiting in three bullets.',
    max_output_tokens: 256,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.6-luna",
  "input": "Summarize the benefits of API rate limiting in three bullets.",
  "max_output_tokens": 256
}'
```

```
- **Protects system stability:** Prevents overload, reduces outages, and ensures predictable performance during traffic spikes.
- **Ensures fair access:** Stops individual users or applications from consuming disproportionate resources.
- **Improves security and cost control:** Helps mitigate abuse, brute-force attacks, and unexpected infrastructure usage.
```

```json
{
  "id": "resp_0e481f0cb46bf357016a4fe99bd5fc8194b6ce2049aa65ab08",
  "object": "response",
  "created_at": 1783622043,
  "status": "completed",
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1783622044,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 256,
  "max_tool_calls": null,
  "model": "gpt-5.6-luna",
  "moderation": null,
  "output": [
    {
      "id": "msg_0e481f0cb46bf357016a4fe99c2e288194a6fd0ce3f5f88786",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "- **Protects system stability:** Prevents overload, reduces outages, and ensures predictable performance during traffic spikes.\n- **Ensures fair access:** Stops individual users or applications from consuming disproportionate resources.\n- **Improves security and cost control:** Helps mitigate abuse, brute-force attacks, and unexpected infrastructure usage."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "all_turns",
    "effort": "medium",
    "mode": "standard",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tool_usage": {
    "image_gen": {
      "input_tokens": 0,
      "input_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "output_tokens": 0,
      "output_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "total_tokens": 0
    },
    "web_search": {
      "num_requests": 0
    }
  },
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 19,
    "input_tokens_details": {
      "cache_write_tokens": 0,
      "cached_tokens": 0
    },
    "output_tokens": 66,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 85
  },
  "user": null,
  "metadata": {}
}
```

## Examples

<details>

<summary>**Pull Request Description** — Using instructions for a cost-sensitive drafting task</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.6-luna',
  {
    input:
      'Write a brief pull request description for a bug fix that prevents duplicate webhook deliveries.',
    instructions: 'Keep it under 100 words.',
    max_output_tokens: 256,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.6-luna",
  "input": "Write a brief pull request description for a bug fix that prevents duplicate webhook deliveries.",
  "instructions": "Keep it under 100 words.",
  "max_output_tokens": 256
}'
```

```
## Summary
Prevents duplicate webhook deliveries by ensuring each event is processed only once, even when retries or concurrent requests occur.

## Changes
- Added idempotency checks for webhook events.
- Prevented duplicate delivery attempts.
- Added regression tests covering retries and concurrent processing.

## Testing
All existing and new tests pass.
```

```json
{
  "id": "resp_0bed05adeda548a1016a4fe99d1e408194bb0375bad96ab71a",
  "object": "response",
  "created_at": 1783622045,
  "status": "completed",
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1783622046,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": "Keep it under 100 words.",
  "max_output_tokens": 256,
  "max_tool_calls": null,
  "model": "gpt-5.6-luna",
  "moderation": null,
  "output": [
    {
      "id": "msg_0bed05adeda548a1016a4fe99daa748194992854423ba08e72",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "## Summary\nPrevents duplicate webhook deliveries by ensuring each event is processed only once, even when retries or concurrent requests occur.\n\n## Changes\n- Added idempotency checks for webhook events.\n- Prevented duplicate delivery attempts.\n- Added regression tests covering retries and concurrent processing.\n\n## Testing\nAll existing and new tests pass."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "all_turns",
    "effort": "medium",
    "mode": "standard",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tool_usage": {
    "image_gen": {
      "input_tokens": 0,
      "input_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "output_tokens": 0,
      "output_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "total_tokens": 0
    },
    "web_search": {
      "num_requests": 0
    }
  },
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 33,
    "input_tokens_details": {
      "cache_write_tokens": 0,
      "cached_tokens": 0
    },
    "output_tokens": 69,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 102
  },
  "user": null,
  "metadata": {}
}
```

</details>

## Parameters

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-luna/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-luna/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-luna/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-luna/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5.6-luna/#page","headline":"GPT-5.6 Luna","description":"GPT-5.6 Luna is an OpenAI GPT-5.6 model optimized for cost-sensitive workloads, using the Responses API for efficient text generation.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5.6-luna/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5.6 Sol is OpenAI's frontier GPT-5.6 model for complex professional work, using the Responses API for reasoning and stateful context management.
title: GPT-5.6 Sol
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5.6 Sol

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-sol/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5.6-sol`

- Third-party

GPT-5.6 Sol is OpenAI's frontier GPT-5.6 model for complex professional work, using the Responses API for reasoning and stateful context management.

Tip

GPT-5.6 Sol is 50% off through Sept 18

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,050,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Request formats | Responses |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Output (per 1M tokens)$10.00</li><li>Cached input (per 1M tokens)$0.25</li><li>Cache creation (per 1M tokens)$3.125</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5.6-sol',
  {
    input: 'Create a concise launch checklist for migrating a production API to a new region.',
    instructions: 'Use five bullets and focus on risk reduction.',
    max_output_tokens: 512,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.6-sol",
  "input": "Create a concise launch checklist for migrating a production API to a new region.",
  "instructions": "Use five bullets and focus on risk reduction.",
  "max_output_tokens": 512
}'
```

```
- **Validate readiness:** Confirm capacity, quotas, security controls, certificates, secrets, dependencies, and compliance requirements in the new region.
- **Protect data:** Take verified backups; validate replication consistency, encryption, retention, and restore procedures before cutover.
- **Test end to end:** Run load, latency, failover, integration, and smoke tests using production-like traffic and data.
- **Control cutover:** Lower DNS TTLs, deploy gradually with canary traffic, freeze risky changes, and monitor errors, latency, saturation, and data integrity.
- **Prepare rollback:** Define go/no-go thresholds, owners, communication channels, and a rehearsed rollback plan; retain the old region until stability is confirmed.
```

```json
{
  "id": "resp_0f038c9de2c94eb6016a4fe97e94f081909f0edfecbfb2abd9",
  "object": "response",
  "created_at": 1783622014,
  "status": "completed",
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1783622017,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": "Use five bullets and focus on risk reduction.",
  "max_output_tokens": 512,
  "max_tool_calls": null,
  "model": "gpt-5.6-sol",
  "moderation": null,
  "output": [
    {
      "id": "rs_0f038c9de2c94eb6016a4fe97f2bac81909bf1c27c448cf46b",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "msg_0f038c9de2c94eb6016a4fe97fa0688190a1b4958a6a0aa218",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "- **Validate readiness:** Confirm capacity, quotas, security controls, certificates, secrets, dependencies, and compliance requirements in the new region.\n- **Protect data:** Take verified backups; validate replication consistency, encryption, retention, and restore procedures before cutover.\n- **Test end to end:** Run load, latency, failover, integration, and smoke tests using production-like traffic and data.\n- **Control cutover:** Lower DNS TTLs, deploy gradually with canary traffic, freeze risky changes, and monitor errors, latency, saturation, and data integrity.\n- **Prepare rollback:** Define go/no-go thresholds, owners, communication channels, and a rehearsed rollback plan; retain the old region until stability is confirmed."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "all_turns",
    "effort": "medium",
    "mode": "standard",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tool_usage": {
    "image_gen": {
      "input_tokens": 0,
      "input_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "output_tokens": 0,
      "output_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "total_tokens": 0
    },
    "web_search": {
      "num_requests": 0
    }
  },
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 34,
    "input_tokens_details": {
      "cache_write_tokens": 0,
      "cached_tokens": 0
    },
    "output_tokens": 182,
    "output_tokens_details": {
      "reasoning_tokens": 32
    },
    "total_tokens": 216
  },
  "user": null,
  "metadata": {}
}
```

## Examples

<details>

<summary>**Operational Reasoning** — Using reasoning effort for a multi-step operational decision</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.6-sol',
  {
    input:
      'A service has 99.9% monthly availability and just had 31 minutes of downtime. Has it exceeded the monthly error budget for a 30-day month? Show the calculation briefly.',
    max_output_tokens: 512,
    reasoning: { effort: 'medium' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.6-sol",
  "input": "A service has 99.9% monthly availability and just had 31 minutes of downtime. Has it exceeded the monthly error budget for a 30-day month? Show the calculation briefly.",
  "max_output_tokens": 512,
  "reasoning": {
    "effort": "medium"
  }
}'
```

```
- Total minutes in 30 days: \(30 \times 24 \times 60 = 43{,}200\)
- Error budget at 99.9% availability: \(43{,}200 \times 0.001 = 43.2\) minutes
- Downtime used: 31 minutes

**No**, it has not exceeded the monthly error budget. It has **12.2 minutes remaining**.
```

```json
{
  "id": "resp_0fcb12a6aa68f25a016a4fe98205b881978b6ab83321e02e3b",
  "object": "response",
  "created_at": 1783622018,
  "status": "completed",
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1783622020,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 512,
  "max_tool_calls": null,
  "model": "gpt-5.6-sol",
  "moderation": null,
  "output": [
    {
      "id": "rs_0fcb12a6aa68f25a016a4fe98293e081979139ff657f9b612b",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "msg_0fcb12a6aa68f25a016a4fe98354fc8197a4b488662491fdd8",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "- Total minutes in 30 days: \\(30 \\times 24 \\times 60 = 43{,}200\\)\n- Error budget at 99.9% availability: \\(43{,}200 \\times 0.001 = 43.2\\) minutes\n- Downtime used: 31 minutes\n\n**No**, it has not exceeded the monthly error budget. It has **12.2 minutes remaining**."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "all_turns",
    "effort": "medium",
    "mode": "standard",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tool_usage": {
    "image_gen": {
      "input_tokens": 0,
      "input_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "output_tokens": 0,
      "output_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "total_tokens": 0
    },
    "web_search": {
      "num_requests": 0
    }
  },
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 44,
    "input_tokens_details": {
      "cache_write_tokens": 0,
      "cached_tokens": 0
    },
    "output_tokens": 159,
    "output_tokens_details": {
      "reasoning_tokens": 63
    },
    "total_tokens": 203
  },
  "user": null,
  "metadata": {}
}
```

</details>

## Parameters

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-sol/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-sol/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-sol/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-sol/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5.6-sol/#page","headline":"GPT-5.6 Sol","description":"GPT-5.6 Sol is OpenAI's frontier GPT-5.6 model for complex professional work, using the Responses API for reasoning and stateful context management.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5.6-sol/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-5.6 Terra is an OpenAI GPT-5.6 model that balances intelligence and cost, using the Responses API for reasoning and stateful context management.
title: GPT-5.6 Terra
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-5.6 Terra

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-terra/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-5.6-terra`

- Third-party

GPT-5.6 Terra is an OpenAI GPT-5.6 model that balances intelligence and cost, using the Responses API for reasoning and stateful context management.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,050,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Request formats | Responses |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Output (per 1M tokens)$12.00</li><li>Cached input (per 1M tokens)$0.20</li><li>Cache creation (per 1M tokens)$2.50</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-5.6-terra',
  {
    input: 'Compare blue-green and canary deployments for a small engineering team.',
    instructions: 'Answer in two concise paragraphs.',
    max_output_tokens: 512,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.6-terra",
  "input": "Compare blue-green and canary deployments for a small engineering team.",
  "instructions": "Answer in two concise paragraphs.",
  "max_output_tokens": 512
}'
```

```
Blue-green deployments run two identical production environments: one active (“blue”) and one idle (“green”). A new version is deployed and tested on green, then traffic is switched over all at once. This makes rollback very fast—switch traffic back to blue—but requires maintaining duplicate infrastructure and handling database/schema compatibility carefully. For a small team, blue-green is often appealing when releases are infrequent, the system is simple enough to duplicate cheaply, and a clear cutover/rollback procedure matters more than gradual validation.

Canary deployments release the new version to a small percentage of users or requests first, then progressively increase traffic while monitoring errors, latency, and business metrics. They reduce the blast radius of defects and provide real-production validation, but require traffic splitting, strong observability, automated rollout controls, and usually feature-flag or version-compatibility discipline. For a small team, canaries are best when the platform already supports them or when the cost of a faulty release is high; otherwise, blue-green generally offers a simpler operational model.
```

```json
{
  "id": "resp_06924a0adf314715016a4fe98e1d2c81978067f843c9a357f1",
  "object": "response",
  "created_at": 1783622030,
  "status": "completed",
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1783622032,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": "Answer in two concise paragraphs.",
  "max_output_tokens": 512,
  "max_tool_calls": null,
  "model": "gpt-5.6-terra",
  "moderation": null,
  "output": [
    {
      "id": "msg_06924a0adf314715016a4fe98e76c4819780adfca3dd3ad1f3",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "Blue-green deployments run two identical production environments: one active (“blue”) and one idle (“green”). A new version is deployed and tested on green, then traffic is switched over all at once. This makes rollback very fast—switch traffic back to blue—but requires maintaining duplicate infrastructure and handling database/schema compatibility carefully. For a small team, blue-green is often appealing when releases are infrequent, the system is simple enough to duplicate cheaply, and a clear cutover/rollback procedure matters more than gradual validation.\n\nCanary deployments release the new version to a small percentage of users or requests first, then progressively increase traffic while monitoring errors, latency, and business metrics. They reduce the blast radius of defects and provide real-production validation, but require traffic splitting, strong observability, automated rollout controls, and usually feature-flag or version-compatibility discipline. For a small team, canaries are best when the platform already supports them or when the cost of a faulty release is high; otherwise, blue-green generally offers a simpler operational model."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "all_turns",
    "effort": "medium",
    "mode": "standard",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tool_usage": {
    "image_gen": {
      "input_tokens": 0,
      "input_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "output_tokens": 0,
      "output_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "total_tokens": 0
    },
    "web_search": {
      "num_requests": 0
    }
  },
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 29,
    "input_tokens_details": {
      "cache_write_tokens": 0,
      "cached_tokens": 0
    },
    "output_tokens": 211,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 240
  },
  "user": null,
  "metadata": {}
}
```

## Examples

<details>

<summary>**Customer Incident Update** — Using instructions to tune the model's response style</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-5.6-terra',
  {
    input: 'Draft a short incident update for customers after elevated API latency.',
    instructions: 'Be transparent, calm, and avoid unnecessary technical detail.',
    max_output_tokens: 512,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5.6-terra",
  "input": "Draft a short incident update for customers after elevated API latency.",
  "instructions": "Be transparent, calm, and avoid unnecessary technical detail.",
  "max_output_tokens": 512
}'
```

```
**Incident Update:**  
Earlier today, some customers experienced elevated API latency. Our team identified the issue and applied mitigation steps, and API performance has returned to normal.

We’ll continue monitoring closely and will share a follow-up with additional details if needed. We apologize for the disruption and appreciate your patience.
```

```json
{
  "id": "resp_0072e6076b1b184d016a4fe99105888190b25ef699c2a83380",
  "object": "response",
  "created_at": 1783622033,
  "status": "completed",
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1783622034,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": "Be transparent, calm, and avoid unnecessary technical detail.",
  "max_output_tokens": 512,
  "max_tool_calls": null,
  "model": "gpt-5.6-terra",
  "moderation": null,
  "output": [
    {
      "id": "msg_0072e6076b1b184d016a4fe9916d6081909385f3b15352b1a7",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "**Incident Update:**  \nEarlier today, some customers experienced elevated API latency. Our team identified the issue and applied mitigation steps, and API performance has returned to normal.\n\nWe’ll continue monitoring closely and will share a follow-up with additional details if needed. We apologize for the disruption and appreciate your patience."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "all_turns",
    "effort": "medium",
    "mode": "standard",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tool_usage": {
    "image_gen": {
      "input_tokens": 0,
      "input_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "output_tokens": 0,
      "output_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "total_tokens": 0
    },
    "web_search": {
      "num_requests": 0
    }
  },
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 33,
    "input_tokens_details": {
      "cache_write_tokens": 0,
      "cached_tokens": 0
    },
    "output_tokens": 64,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 97
  },
  "user": null,
  "metadata": {}
}
```

</details>

## Parameters

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-terra/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-terra/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-terra/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-5.6-terra/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-5.6-terra/#page","headline":"GPT-5.6 Terra","description":"GPT-5.6 Terra is an OpenAI GPT-5.6 model that balances intelligence and cost, using the Responses API for reasoning and stateful context management.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-5.6-terra/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-6 Astra is OpenAI's most capable model, built for complex reasoning, coding, computer use, research, and document creation.
title: GPT-6 Astra
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-6 Astra

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-6-astra/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-6-astra`

- Third-party

GPT-6 Astra is OpenAI's most capable model, built for complex reasoning, coding, computer use, research, and document creation.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,050,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://developers.openai.com/api/docs/models/gpt-6-astra) |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Short-context input (per 1M)$10.00</li><li>Short-context cached input (per 1M)$1.00</li><li>Short-context cache write (per 1M)$12.00</li><li>Short-context output (per 1M)$50.00</li><li>Long-context input (per 1M)$20.00</li><li>Long-context cached input (per 1M)$2.00</li><li>Long-context cache write (per 1M)$25.00</li><li>Long-context output (per 1M)$75.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-6-astra',
  {
    input:
      'A service has 99.9% monthly availability and just had 31 minutes of downtime. Has it exceeded the monthly error budget for a 30-day month? Show the calculation briefly.',
    max_output_tokens: 512,
    reasoning: { effort: 'high' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-6-astra",
  "input": "A service has 99.9% monthly availability and just had 31 minutes of downtime. Has it exceeded the monthly error budget for a 30-day month? Show the calculation briefly.",
  "max_output_tokens": 512,
  "reasoning": {
    "effort": "high"
  }
}'
```

```
No. For a 30-day month:

- Total time: \(30 \times 24 \times 60 = 43{,}200\) minutes
- Error budget: \(43{,}200 \times (1 - 0.999) = 43.2\) minutes
- Remaining budget: \(43.2 - 31 = 12.2\) minutes

Assuming 31 minutes is the total downtime this month, it is **within the error budget**.
```

```json
{
  "id": "resp_0f4dd4f38f19eb60016a99d9b6aaec87d1ab6bb0c344527fbc",
  "object": "response",
  "created_at": 1788467638,
  "model": "gpt-6-astra",
  "output": [
    {
      "id": "rs_0f4dd4f38f19eb60016a99d9b77c6087d1ab41b79ccdf5a833",
      "type": "reasoning",
      "content": [],
      "encrypted_content": "gAAAAABqmdm5bNo3TE240J65AqELJf45m_Forsch1ik0e0iiz5B-XZsvljWjY5PfmKXyel-6WvdoKmKulsRo3PX0fCqdNQFUaSYufMITZh61KSdsWBeeKRAwczgj8ihQBEbSF95MmTwkoQzsHX5SBitcf0n7CrMhXt8-LcE2tXqY309dnpgzAtjeI8H318LR1JyAWKsbver3s30gE1TRh0GC3YisTLrfACSclHB8_cOPA5QvEwKJNljm8R7eVDJx7LTFoB2Av93eaSD7l4fbAJzR_afL8K_Akj5NsjYaZVrsbPPxTYlYpqRhE0c-3C2U0oJ31-4UVa6_nT94QYtnDJ9YNjEdRC8sMkq6DwLhkbIIJGVNJGqHmWP3vQu3JCq9VDUtC3ss3FCkgWwhIV5tAFTFOtppnHenz1Xi2UYwaBNwaHWYJdrTBidNcpEQwPcIdSRAfOHv2r-ueFywhAZmj8Rx_GcJO_5_RWjvglhuNRBTbC92icwLx6wt4LWYBpLW-0itkHNtdy2cqsiKYSxWyMRzaEwyhW3wQo6jC9w9MRUG35wT3drTsuvnMDV5yhtzCtxq57eTRpIpCM9343ITl5DUwS-d7vouI7QH2MAIkZknxTO-_vVPYVQrQ4Th0g6Cb8CrGd-nHQ39xYKnPG7oUmvRobLSaGpKmQREzp-uoQeVK8dypZCl3Xd1uHSUO7w-HKsob-t5whmpE-ziHFaqciWh9YcssC0YE1ztbq0f9tGRy386ZzkkihD23sGR0khZukCdiGSw3Njakpe4AMWujU-t2BtomDJa6pdtLEuvG7p3MbIbHRoXkyK-9h74NgBY2jO7fk0BgItjpmqhcPHelCtMxIhP_OroanM0rCUjfQdqcSBVxwOd_hJ5wcNHmWdyf3gVvKEO83M4cj-sVljJ1afzFfhFsAQH5Zw-JTeBI1udknm3oy5lDwEzRoZpTcQs2Ix8lyUBtZ4MypqRLTnKLXzyij8G8XdgTIqwUkOHhMrm8Zc0_ndcrwPoVjwTq0NugRGJMDAxPKl-aqg6XvEfCYCUF2WYIu8jGo3KK6An8GJ5HFLyidgUslKGJtN2TJmKBOPwc0fXoiW4qyUQdVi2Hz23KBMOQE77jIF0cccZAWDToq67zPLVw9I4j-VKRpti-tOfcg9tz0wr4zJRi49uOqTw038Xn03VXzTolhb3GwwQkMZxWLjam3buEX6SLuS1A7XXZn3aKeLu6KhUin6_aR3jP0s2_Y50Mjv3x0EouaIKQJEINqYRgi9K2SKAxzRSKjGksdNGNcNRGs6cydkHSJF-f60p9HRBbBsN7duP8qm0K2URSJ1DX30=",
      "summary": []
    },
    {
      "id": "msg_0f4dd4f38f19eb60016a99d9b7d7f087d191f17156c41c2f32",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "No. For a 30-day month:\n\n- Total time: \\(30 \\times 24 \\times 60 = 43{,}200\\) minutes\n- Error budget: \\(43{,}200 \\times (1 - 0.999) = 43.2\\) minutes\n- Remaining budget: \\(43.2 - 31 = 12.2\\) minutes\n\nAssuming 31 minutes is the total downtime this month, it is **within the error budget**."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "status": "completed",
  "usage": {
    "input_tokens": 44,
    "output_tokens": 151,
    "total_tokens": 195,
    "input_tokens_details": {
      "cache_write_tokens": 0,
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 41
    }
  },
  "access_programs": {
    "cyber": "standard"
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1788467641,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 512,
  "max_tool_calls": null,
  "moderation": null,
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "24h",
  "reasoning": {
    "context": "all_turns",
    "effort": "high",
    "mode": "standard",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tool_usage": {
    "image_gen": {
      "input_tokens": 0,
      "input_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "output_tokens": 0,
      "output_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "total_tokens": 0
    },
    "web_search": {
      "num_requests": 0
    }
  },
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "user": null,
  "metadata": {},
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Migration Safeguards** — Generate a concise answer through Chat Completions</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-6-astra',
  {
    messages: [
      { role: 'user', content: 'List three practical safeguards for a production API migration.' },
    ],
    max_completion_tokens: 256,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-6-astra",
  "messages": [
    {
      "role": "user",
      "content": "List three practical safeguards for a production API migration."
    }
  ],
  "max_completion_tokens": 256
}'
```

```
1. **Validate compatibility before rollout.** Run contract and integration tests against real client behaviors. Keep breaking changes behind a new API version, and verify authentication, error formats, and data schemas.

2. **Roll out gradually with monitoring.** Start with internal traffic or a small canary group. Track error rates, latency, and critical business metrics; pause expansion if predefined thresholds are exceeded.

3. **Prepare and test rollback.** Keep the old API available and use a feature flag or traffic switch to revert quickly. Ensure database changes remain backward-compatible, and rehearse the rollback procedure.
```

```json
{
  "id": "chatcmpl-EK8QDqH1XsfW6m8nEHXxUkrKGcWG5",
  "object": "chat.completion",
  "created": 1788467641,
  "model": "gpt-6-astra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "1. **Validate compatibility before rollout.** Run contract and integration tests against real client behaviors. Keep breaking changes behind a new API version, and verify authentication, error formats, and data schemas.\n\n2. **Roll out gradually with monitoring.** Start with internal traffic or a small canary group. Track error rates, latency, and critical business metrics; pause expansion if predefined thresholds are exceeded.\n\n3. **Prepare and test rollback.** Keep the old API available and use a feature flag or traffic switch to revert quickly. Ensure database changes remain backward-compatible, and rehearse the rollback procedure.",
        "refusal": null,
        "annotations": []
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 16,
    "completion_tokens": 151,
    "total_tokens": 167,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "cache_write_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 23,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default",
  "system_fingerprint": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-6-astra/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-6-astra/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-6-astra/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-6-astra/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-6-astra/#page","headline":"GPT-6 Astra","description":"GPT-6 Astra is OpenAI's most capable model, built for complex reasoning, coding, computer use, research, and document creation.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-6-astra/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-6 Luna is OpenAI's most efficient GPT-6 model, built for focused, high-volume tasks.
title: GPT-6 Luna
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-6 Luna

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-6-luna/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-6-luna`

- Third-party

GPT-6 Luna is OpenAI's most efficient GPT-6 model, built for focused, high-volume tasks.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,050,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://developers.openai.com/api/docs/models/gpt-6-luna) |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Short-context input (per 1M)$0.10</li><li>Short-context cached input (per 1M)$0.01</li><li>Short-context cache write (per 1M)$0.125</li><li>Short-context output (per 1M)$0.50</li><li>Long-context input (per 1M)$0.20</li><li>Long-context cached input (per 1M)$0.02</li><li>Long-context cache write (per 1M)$0.25</li><li>Long-context output (per 1M)$0.75</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-6-luna',
  {
    input:
      'A service has 99.9% monthly availability and just had 31 minutes of downtime. Has it exceeded the monthly error budget for a 30-day month? Show the calculation briefly.',
    max_output_tokens: 512,
    reasoning: { effort: 'high' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-6-luna",
  "input": "A service has 99.9% monthly availability and just had 31 minutes of downtime. Has it exceeded the monthly error budget for a 30-day month? Show the calculation briefly.",
  "max_output_tokens": 512,
  "reasoning": {
    "effort": "high"
  }
}'
```

```
No. A 30-day month has 43,200 minutes, so a 99.9% availability target allows **43.2 minutes** of downtime.

**31 minutes < 43.2 minutes** — the service is within its error budget, with **12.2 minutes** remaining.
```

```json
{
  "id": "resp_0834f111f7f68c6e006ab2cf91391887d1b9ed77f9003d8001",
  "object": "response",
  "created_at": 1790103441,
  "status": "completed",
  "access_programs": {
    "cyber": "daybreak_blue"
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1790103442,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 512,
  "max_tool_calls": null,
  "model": "gpt-6-luna",
  "moderation": null,
  "output": [
    {
      "id": "rs_0834f111f7f68c6e006ab2cf91a3dc87d194f310e59b05b545",
      "type": "reasoning",
      "content": [],
      "encrypted_content": "gAAAAABqss-TspJODH9IZcFL8SzWTp9z3qvEH482IoLj1OmrPlxluS5KGNZRrU1yGjrek9eQ7K6QzWND5RagCGsxWPN3ZK7lFfa8HWjztExHY-locYCrFDRWniTGdOmjF0dAUcm_5L5laGAhFa5qiRByPmSSapXvxyhbYx1Qs-_SjUxRF7rvxFIisGHm4XeHSuTMLUaVGk3okdDMWwxJDZrPjOk66JLwvZ_D8n345Iw6WG7L6iS30KsEhOuKVxkdkl0H_T_2fDaGxaJfOIr0WCSFjM62vvZNw6Gi9-zf8tzupmjORta_cLu9YDNSklYSNio-rUS-2RMlfJA1RvFQPKIx8347HtpYUYqHBNFRlNA-Az99fWBdGffyNtYL2vuItF4X0UJ1tDN_KtuFil7qLPJMGHTdXI7_-2YzNw9u-rmeeR9tnp3zbCertjlHMsTAcT0fbuLh_ob-GCDSg0pR8Ac5fsJv75nRqIMVixC_e7sL_5sGDAsJDi-24_nUAtU84zCPinglfdiYNvwBoEOgZQ-bYT8K3DZ-Z6dJaupCz_ncOtsFIvvEehM2JzcVdKkhUv6ilUst-J-RoMEzb3HzpKZE2Y6Ry3R-VDvLOda2HL-DrmbK4zW_o8X5-Yp5I-XXIomnt3yxMRYyH5WI66HkMQAFQtiP7ukmQEpI-_ItySu48cro2tpY3tBnRBJAvAU45yGDm9EhG6F_jThXyEav90yADc4GfJw82gZDzrnmQ0Oki8U0jEfPUipKztlsstiLw06Da5IF6cBxhOMiNq2TbB4j5o3bG48HSxAzwgu8xHHSR00_IWMEFO49l6lWpO9W0FWN9OdeaMKkRFQ8cGNIZCqDgYvkw3x0NlbOtjm_TqIQMRVM7vfsdujWSwb1iidy6BEYde7TVAmEg_D0jk7tq9JPIQIngvbxeWXpE2zmvEGrgDqD9y8d-dF2svsxMegzFpZjVowcWRPhJXcySYsMnPrIYqM8bCmXPhSXoBgmTqvWO8BCBJUPvRLPAkJSUU4JTI3GAsN4XAKVm-NaQghf4t5ofeZkIRx9sc1jkz1KfEZ_hH02_89s_A8u2GaiCREYGisKBd9ZuvtDu2WxzIsqud1YKqn9epw-ZC5zCkS0MfZW5rZGmBmu2K6Zia2swsBgs3mypZPh4ihYkkeuAxs_eX1nFtCW-tdYGFcCKVRBf3tvbA2XRgcfgNr9LH6kmbWSBM53kjxLI5L6hR-CDBJ9lWuWoal1R3GzWL9-uIbU4i4ailowQwcgQ2o8Lnnq_jZTs-yurDDyThIVKeo_ZkrmniqyReoVlwYZYRWKaKsSV6i95J-GosOjqM4BoVZGB0tvebNbEOz4tGzKPmoDFI6ckl4Jede1l3dYWAobbPgGab7pp4QgmerdWhiIyK2-kRrDsocrazxjIv0hEqOZha1jwN_cWqmfPTgfmv7jIHZ9Be0S8xrQdd11Qwwyik1OPyJlYte3Ru1IO6FDcCRNbAE3yFBE9pSU8kOKIg==",
      "summary": []
    },
    {
      "id": "msg_0834f111f7f68c6e006ab2cf925fd487d1b67ccd2ee1e2dfe5",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "No. A 30-day month has 43,200 minutes, so a 99.9% availability target allows **43.2 minutes** of downtime.\n\n**31 minutes < 43.2 minutes** — the service is within its error budget, with **12.2 minutes** remaining."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "24h",
  "reasoning": {
    "context": "all_turns",
    "effort": "high",
    "mode": "standard",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": true,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tool_usage": {
    "image_gen": {
      "input_tokens": 0,
      "input_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "output_tokens": 0,
      "output_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "total_tokens": 0
    },
    "web_search": {
      "num_requests": 0
    }
  },
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 44,
    "input_tokens_details": {
      "cache_write_tokens": 0,
      "cached_tokens": 0
    },
    "output_tokens": 151,
    "output_tokens_details": {
      "reasoning_tokens": 84
    },
    "total_tokens": 195
  },
  "user": null,
  "metadata": {}
}
```

## Examples

<details>

<summary>**Migration Safeguards** — Generate a concise answer through Chat Completions</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-6-luna',
  {
    messages: [
      { role: 'user', content: 'List three practical safeguards for a production API migration.' },
    ],
    max_completion_tokens: 256,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "List three practical safeguards for a production API migration."
    }
  ],
  "max_completion_tokens": 256
}'
```

```
1. **Preserve compatibility:** Version the API or support old and new contracts during the transition; document breaking changes and give clients a migration window.
2. **Roll out gradually:** Test in staging, then use a canary or percentage-based rollout with monitoring for errors, latency, and client failures.
3. **Plan validation and rollback:** Verify key workflows and data before and after cutover, keep backups or a reversible migration path, and define clear rollback triggers.
```

```json
{
  "id": "chatcmpl-EQzy7Or5tZ9ZdoXfjhVAYfwDEj28S",
  "object": "chat.completion",
  "created": 1790103443,
  "model": "gpt-6-luna",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "1. **Preserve compatibility:** Version the API or support old and new contracts during the transition; document breaking changes and give clients a migration window.\n2. **Roll out gradually:** Test in staging, then use a canary or percentage-based rollout with monitoring for errors, latency, and client failures.\n3. **Plan validation and rollback:** Verify key workflows and data before and after cutover, keep backups or a reversible migration path, and define clear rollback triggers.",
        "refusal": null,
        "annotations": []
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 16,
    "completion_tokens": 128,
    "total_tokens": 144,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "cache_write_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 25,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default",
  "system_fingerprint": null
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-6-luna/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-6-luna/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-6-luna/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-6-luna/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-6-luna/#page","headline":"GPT-6 Luna","description":"GPT-6 Luna is OpenAI's most efficient GPT-6 model, built for focused, high-volume tasks.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-6-luna/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-6 Sol is OpenAI's mid-tier GPT-6 model, built to power complex coding and agentic workflows.
title: GPT-6 Sol
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-6 Sol

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-6-sol/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-6-sol`

- Third-party

GPT-6 Sol is OpenAI's mid-tier GPT-6 model, built to power complex coding and agentic workflows.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,050,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://developers.openai.com/api/docs/models/gpt-6-sol) |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Short-context input (per 1M)$2.00</li><li>Short-context cached input (per 1M)$0.20</li><li>Short-context cache write (per 1M)$2.50</li><li>Short-context output (per 1M)$10.00</li><li>Long-context input (per 1M)$4.00</li><li>Long-context cached input (per 1M)$0.40</li><li>Long-context cache write (per 1M)$5.00</li><li>Long-context output (per 1M)$15.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-6-sol',
  {
    input:
      'A service has 99.9% monthly availability and just had 31 minutes of downtime. Has it exceeded the monthly error budget for a 30-day month? Show the calculation briefly.',
    max_output_tokens: 512,
    reasoning: { effort: 'high' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-6-sol",
  "input": "A service has 99.9% monthly availability and just had 31 minutes of downtime. Has it exceeded the monthly error budget for a 30-day month? Show the calculation briefly.",
  "max_output_tokens": 512,
  "reasoning": {
    "effort": "high"
  }
}'
```

```
No. A 30-day month has \(30 \times 24 \times 60 = 43{,}200\) minutes, so the 0.1% downtime budget is **43.2 minutes**. After 31 minutes of downtime, **12.2 minutes remain**.
```

```json
{
  "id": "resp_004a362708bc0a44006ab2cc7bd4c487d1bffa1555dc6c5110",
  "object": "response",
  "created_at": 1790102651,
  "status": "completed",
  "access_programs": {
    "cyber": "daybreak_blue"
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1790102653,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 512,
  "max_tool_calls": null,
  "model": "gpt-6-sol",
  "moderation": null,
  "output": [
    {
      "id": "rs_004a362708bc0a44006ab2cc7c78bc87d1b3ac1095e5bbaaae",
      "type": "reasoning",
      "content": [],
      "encrypted_content": "gAAAAABqssx9oBJ5yr_VdmObO4zvyzJEasvjs_4xsaXswQG7TjMqx-6kfx_szw29t29TiMj1CMtiWD8IdaVjgznOab6hu0poxB9ZuvgbmIrkgiYx_oqp8UHjtJd06fhkzNaTp01_BBaBQpcwhC9bd_Y6VR8HlvEB1Go4JL7-RLhwh2nJN5wjRjWOlqWaHZRaz1Wz2eQon9IYI8pJ9jpxvYMQpNBle___KLzlJiCjeDKw5yFf9NAjKDwqi75YR4f2uhsWYIfRNgi3Eyzx-h_5dnIahzx1-26Bj_UcRQvUhqf0-0jGmIS1PLg1uSVlHJ7iQsuLJwtcwJYG7X-FYEx61X9BtqtiUFODxRODCUpq3RMrZKUm6N9BtNwqB1PkLR6Y5gCyhWPAdf77zvcxGJKncLGIduS4Fei5u3lJTg8NlDpFC5sFNUu6wEmBV3Mz3e_uCo3B2bHVFNAFcK8h-nnvj3hM6EYbVTRnXlaFrb2Fb51_TvZBQ1ReAPmz9nQcdb9bIZRBeRIN7PAKChmwgS4gYD_r3IE3k4q8CWBHOPzzxHeQzOSPgameIHzXR13uc9dy-gBD8o2wWChw616xhktHemPEUZG4l2AIBVSJNuFKIoGS_jT_P7ScPZwynxwS3wSGuyCLa3qAPkZWeP7qqfZQmtDKWj0xnjyipbOGoDQh5pAPtkIMdKIsMBj12RY_Ms-sYB7ojN1vOhUWeN-2MXPDkBmxY_L58hUjNVyLbYo1TUQsZVQX5r0tT0o3_9GI7aAa-vgMz_hXFJ4QepBtzc2hlGDT6CKp5tt235fisry5k0xaMAsl9ae6o-yEn0KDeLmpeIICZX6vDgqIZjPny7D_jpmHNZPLYkC56kQL2xaLI695l3GuMkeV6S5kphxK1y-5yyEJ9lasAT2aEwTIFSQ1fjdMwb9QjCpDXL-w-fUMxAfy_u8LapQBH5aV6XH5L2No4VKP-0IDrstrfh38LEEm9sBt55zVBQ2-UpB_DYy-BsG4Qn77cpDVaKC3MHXBbMhYWaNc6vJ1zsLaUhO2AgH7QW8sCRHexDRb1QO9NRXbp9Y-HSOIV8UxFEXjxbUV_dPxYUABNioPutzYq54kqnJc8ekT45AN-CRgviXVG9824m20cjEz1ryvnVNIKmen_ysou2W98MQqIch2Hh4cqgCkBxOyh7iYTqSS8LhGoJqAtGRgK7XlV8sB-q3xEDLEsW5cD_irRuVzh5Bb1ofy4emT2HNeoYUNdA9SLvpZfK9c8jCHr01ia4NzGrjwSBn4fzujX-eCPoYaN2MLQ2N8mp1cfYGH35LDIhmCjA==",
      "summary": []
    },
    {
      "id": "msg_004a362708bc0a44006ab2cc7ca89487d1a80f11a6def484c5",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "No. A 30-day month has \\(30 \\times 24 \\times 60 = 43{,}200\\) minutes, so the 0.1% downtime budget is **43.2 minutes**. After 31 minutes of downtime, **12.2 minutes remain**."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "24h",
  "reasoning": {
    "context": "all_turns",
    "effort": "high",
    "mode": "standard",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": true,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tool_usage": {
    "image_gen": {
      "input_tokens": 0,
      "input_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "output_tokens": 0,
      "output_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "total_tokens": 0
    },
    "web_search": {
      "num_requests": 0
    }
  },
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 44,
    "input_tokens_details": {
      "cache_write_tokens": 0,
      "cached_tokens": 0
    },
    "output_tokens": 103,
    "output_tokens_details": {
      "reasoning_tokens": 36
    },
    "total_tokens": 147
  },
  "user": null,
  "metadata": {}
}
```

## Examples

<details>

<summary>**Migration Safeguards** — Generate a concise answer through Chat Completions</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-6-sol',
  {
    messages: [
      { role: 'user', content: 'List three practical safeguards for a production API migration.' },
    ],
    max_completion_tokens: 256,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-6-sol",
  "messages": [
    {
      "role": "user",
      "content": "List three practical safeguards for a production API migration."
    }
  ],
  "max_completion_tokens": 256
}'
```

```
1. **Preserve compatibility:** Version breaking changes and run contract tests against existing clients.
2. **Roll out gradually:** Start with a canary or small percentage of traffic, and monitor errors, latency, and key business metrics.
3. **Prepare a rollback:** Keep the previous API deployable, back up data, and rehearse how to reverse any schema changes.
```

```json
{
  "id": "chatcmpl-EQzlOt1nlzMH6eShi7U8iGaHTJByy",
  "object": "chat.completion",
  "created": 1790102654,
  "model": "gpt-6-sol",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "1. **Preserve compatibility:** Version breaking changes and run contract tests against existing clients.\n2. **Roll out gradually:** Start with a canary or small percentage of traffic, and monitor errors, latency, and key business metrics.\n3. **Prepare a rollback:** Keep the previous API deployable, back up data, and rehearse how to reverse any schema changes.",
        "refusal": null,
        "annotations": []
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 16,
    "completion_tokens": 118,
    "total_tokens": 134,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "cache_write_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 34,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default",
  "system_fingerprint": null
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-6-sol/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-6-sol/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-6-sol/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-6-sol/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-6-sol/#page","headline":"GPT-6 Sol","description":"GPT-6 Sol is OpenAI's mid-tier GPT-6 model, built to power complex coding and agentic workflows.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-6-sol/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: GPT-6.1 Sol is OpenAI's newest Sol model, delivering near-Astra performance at a lower cost for complex coding, computer use, and professional work.
title: GPT-6.1 Sol
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT-6.1 Sol

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-6.1-sol/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-6.1-sol`

- Third-party

GPT-6.1 Sol is OpenAI's newest Sol model, delivering near-Astra performance at a lower cost for complex coding, computer use, and professional work.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,050,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://developers.openai.com/api/docs/models/gpt-6.1-sol) |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Short-context input (per 1M)$2.00</li><li>Short-context cached input (per 1M)$0.10</li><li>Short-context cache write (per 1M)$2.50</li><li>Short-context output (per 1M)$10.00</li><li>Long-context input (per 1M)$4.00</li><li>Long-context cached input (per 1M)$0.20</li><li>Long-context cache write (per 1M)$5.00</li><li>Long-context output (per 1M)$15.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-6.1-sol',
  {
    input:
      'A service has 99.9% monthly availability and just had 31 minutes of downtime. Has it exceeded the monthly error budget for a 30-day month? Show the calculation briefly.',
    max_output_tokens: 512,
    reasoning: { effort: 'high' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-6.1-sol",
  "input": "A service has 99.9% monthly availability and just had 31 minutes of downtime. Has it exceeded the monthly error budget for a 30-day month? Show the calculation briefly.",
  "max_output_tokens": 512,
  "reasoning": {
    "effort": "high"
  }
}'
```

```
No. A 30-day month has \(30 \times 24 \times 60 = 43{,}200\) minutes.

The downtime budget is:
\[
43{,}200 \times (1 - 0.999) = 43.2 \text{ minutes}
\]

With **31 minutes** of total downtime, it has **12.2 minutes remaining** in the monthly error budget.
```

```json
{
  "id": "resp_0742f162d8d88f47006abbfb65797087d1bf6067c71ad4f488",
  "object": "response",
  "created_at": 1790704485,
  "status": "completed",
  "access_programs": null,
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1790704489,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 512,
  "max_tool_calls": null,
  "model": "gpt-6.1-sol",
  "moderation": null,
  "output": [
    {
      "id": "rs_0742f162d8d88f47006abbfb66b91887d1b350a855c33b1a1d",
      "type": "reasoning",
      "content": [],
      "encrypted_content": "gAAAAABqu_tp8krmIOoigihwk28V3hw4d1Y_Eool5VFtPYh3G8ZpXSlRoDhZdTuB2XNHizSr-faVPlm3Z-K0RgfU74vlZp8aWqhlnrGs8_XYwk1Iqi-TSacN9S_3wYvHyHpVKFqGAqAaj63TVGuYen-flkgSasvprEnL6KUPPjcJlHFoPMppkXXPFrwuaw7F47QHGv0FAvok_wtBiSgghzbXH4_dgwxvT0hsAcX03xTWRGMQP18n1esxQr47TyrQG2APoynZLdietAvr-qUmghFeKTrTusGjeLgVIFCDDEwSvLBW3sZj5ezX9-mWwKWdAx98-7C2e9322jTGXWSC_8Z3axK8DjKWLf8VXe8bBvAFA3g15o0aBpy144hYrsymXIax1k5SSYqvHvNiuV_eA2pzCG_BcJkvRtZ-9zFQLZ3rtO6objv3UbZ21qXwNfvlp2FGxI4Qv0LbReLaHua5Zttkg7N-t0n0D8NB2Tv2UP6FUdbAgLOqJXMYcivRP2vtvnrkUJz5DN23FIhiqGL8HgGDedg--_AqReHxNWGmh3EUsUK0IBLwJSO0WXF3yfBFqveVW_OWIoXugQha_KDz0SSTS3F4I98UAXCTV51KskT-caWnKs8SrilQtuHdhf-axWo_MnQLlsjoSNvPJI-G3-Dz8f-hLQvlo6yE3WejMXJpTpXtboCFId7ezJgZYrbDZTZJGurWODEGmk9BRmwRvg-BqFRt6OVyTioGafw0efSrEGEne50Lv5ACUfBzOV0-tCQ_bGFp0YW7HwpxLsdWjk0l6IteeFHQ6r6sFDm1lvt0GvYTa0KMmYJJxj3heM-m245AUZIrFf-D0vrII0VwKtHTtBhavXIpS--6P_SQ2A_RP10zMoWj3EOWa4s1tZ9zaJX1W1IFdqwBuOS4ISBAgaOKJe-GwypcOWMzmhNDV9ZGWtHwdkgzdd3ksZ6m5VF1mm1ngooUdJT1KidlGLLpamsmEPlUAJskSHBcMOcaT5RXqp4nPx3CPcHFetUTbSsYH0ArFRdPuPM8L8tR_HJ11sEM2fFWwKdgntQ48sS1o3ZS_t72yKBWxVO3XHWY-2Ej2PHvP1gjEuIRy1gWvZVBchb3KVBbqwGAND9IJ5zWmjlHEo48khWpCZiJUHtS8W1roy4bNOvEF0kWY0pe01-N7HKBDGHLPJbR3ifB0GMtQHkuTR_LhlfluWvvgODrRvzSdaconMNl_9V0p_KRulPSBVYdhQ1Pef_F0mm5S_rVq2aJR1v9Iqb7bF52TBFbZ4iXJphjpft1AxzDEEamX4O1hAiHpu0HgdwAwsV8lTxdUdeQ5c1fksqQyXCVwmBVL-Kiw7NGoiFDW1Q_uVLC1iv6-IiRaHWrFmvo85MLlhF-pUocgZasQC4mM70zW5AUaaT6adJD15cmTGIv3C5_UvjHUbPJ40Fy8Wd65bdZiER0WL2qTD13FUomOIK3JqTGTccqakCzkFDAv_2HCZBbn0xgM_oEdN2WsrP-iiBquNPCUr5Y8jqVsPHsLfxTOgbDCdWRHcAl-oe5aN_RtciAF6aH_oHoAft4LLRzS9APxWemfhUV9vsrQN4jxg32WghgIK3ot5vkKW0bJFnRmhr86esnTXfJIUMOQgjRA4hWvoejNqWnMLiWK9_C8PdvSiNhxTxxGVTEChQmql6WpS-AFYuZdTR9tARXap_cpQ==",
      "summary": []
    },
    {
      "id": "msg_0742f162d8d88f47006abbfb68a39c87d1b289852fcb1469dc",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "No. A 30-day month has \\(30 \\times 24 \\times 60 = 43{,}200\\) minutes.\n\nThe downtime budget is:\n\\[\n43{,}200 \\times (1 - 0.999) = 43.2 \\text{ minutes}\n\\]\n\nWith **31 minutes** of total downtime, it has **12.2 minutes remaining** in the monthly error budget."
        }
      ],
      "phase": "final_answer",
      "role": "assistant"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "24h",
  "reasoning": {
    "context": "all_turns",
    "effort": "high",
    "mode": "standard",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": true,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tool_usage": {
    "image_gen": {
      "input_tokens": 0,
      "input_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "output_tokens": 0,
      "output_tokens_details": {
        "image_tokens": 0,
        "text_tokens": 0
      },
      "total_tokens": 0
    },
    "web_search": {
      "num_requests": 0
    }
  },
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.98,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 44,
    "input_tokens_details": {
      "cache_write_tokens": 0,
      "cached_tokens": 0
    },
    "output_tokens": 222,
    "output_tokens_details": {
      "reasoning_tokens": 129
    },
    "total_tokens": 266
  },
  "user": null,
  "metadata": {}
}
```

## Examples

<details>

<summary>**Migration Safeguards** — Generate a concise answer through Chat Completions</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-6.1-sol',
  {
    messages: [
      { role: 'user', content: 'List three practical safeguards for a production API migration.' },
    ],
    max_completion_tokens: 256,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-6.1-sol",
  "messages": [
    {
      "role": "user",
      "content": "List three practical safeguards for a production API migration."
    }
  ],
  "max_completion_tokens": 256
}'
```

```
1. **Validate backward compatibility:** Run contract and integration tests against real client workflows. Version breaking changes and keep the old API available during the transition.

2. **Roll out gradually with monitoring:** Start with a small canary group, then increase traffic while tracking error rates, latency, and data correctness. Define thresholds that pause or reverse the rollout.

3. **Test the rollback plan:** Use feature flags or traffic routing to restore the old API quickly. Back up affected data and ensure schema changes remain compatible with the old version.
```

```json
{
  "id": "chatcmpl-ETWKQsjDdzqugdVw1xUKVJuFad33U",
  "object": "chat.completion",
  "created": 1790704490,
  "model": "gpt-6.1-sol",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "1. **Validate backward compatibility:** Run contract and integration tests against real client workflows. Version breaking changes and keep the old API available during the transition.\n\n2. **Roll out gradually with monitoring:** Start with a small canary group, then increase traffic while tracking error rates, latency, and data correctness. Define thresholds that pause or reverse the rollout.\n\n3. **Test the rollback plan:** Use feature flags or traffic routing to restore the old API quickly. Back up affected data and ensure schema changes remain compatible with the old version.",
        "refusal": null,
        "annotations": []
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 16,
    "completion_tokens": 155,
    "total_tokens": 171,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "cache_write_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 40,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default",
  "system_fingerprint": null
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-6.1-sol/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-6.1-sol/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-6.1-sol/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-6.1-sol/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-6.1-sol/#page","headline":"GPT-6.1 Sol","description":"GPT-6.1 Sol is OpenAI's newest Sol model, delivering near-Astra performance at a lower cost for complex coding, computer use, and professional work.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-6.1-sol/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: OpenAI's image generation model that creates and edits images from text prompts, supporting multiple quality levels and output sizes.
title: GPT Image 1.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT Image 1.5

Text-to-Image • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-image-1.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-image-1.5`

- Third-party
- Zero data retention

OpenAI's image generation model that creates and edits images from text prompts, supporting multiple quality levels and output sizes.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Input (per 1M tokens)$5.00</li><li>Input image (per 1M tokens)$8.00</li><li>Cached input (per 1M tokens)$1.25</li><li>Cached input image (per 1M tokens)$2.00</li><li>Output image (per 1M tokens)$32.00</li><li>Output (per 1M tokens)$10.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-image-1.5',
  { prompt: 'A golden retriever puppy playing in autumn leaves' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-1.5",
  "input": {
    "prompt": "A golden retriever puppy playing in autumn leaves"
  }
}'
```

![Simple Generation](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-1.5/simple-generation.png)

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-1.5/simple-generation.png"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**High Quality** — Generate a high-quality detailed image</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-1.5',
  {
    prompt:
      'A detailed botanical illustration of exotic tropical flowers with fine line work and watercolor textures',
    quality: 'high',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-1.5",
  "input": {
    "prompt": "A detailed botanical illustration of exotic tropical flowers with fine line work and watercolor textures",
    "quality": "high"
  }
}'
```

![High Quality](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-1.5/high-quality.png)

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-1.5/high-quality.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Low Quality Draft** — Fast, rough draft for iteration</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-1.5',
  {
    prompt: 'A quiet Japanese garden in morning mist with a stone lantern and koi pond',
    quality: 'low',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-1.5",
  "input": {
    "prompt": "A quiet Japanese garden in morning mist with a stone lantern and koi pond",
    "quality": "low"
  }
}'
```

![Low Quality Draft](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-1.5/low-quality-draft.png)

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-1.5/low-quality-draft.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Medium Quality** — Balanced quality for most uses</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-1.5',
  {
    prompt:
      'A neon-lit cyberpunk figure standing in the rain beneath a holographic billboard, cinematic lighting',
    quality: 'medium',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-1.5",
  "input": {
    "prompt": "A neon-lit cyberpunk figure standing in the rain beneath a holographic billboard, cinematic lighting",
    "quality": "medium"
  }
}'
```

![Medium Quality](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-1.5/medium-quality.png)

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-1.5/medium-quality.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Auto Quality** — Let the model pick an appropriate quality level</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-1.5',
  {
    prompt:
      'A panoramic view of the northern lights over a snowy mountain range, vivid greens and purples dancing across the sky',
    quality: 'auto',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-1.5",
  "input": {
    "prompt": "A panoramic view of the northern lights over a snowy mountain range, vivid greens and purples dancing across the sky",
    "quality": "auto"
  }
}'
```

![Auto Quality](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-1.5/auto-quality.png)

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-1.5/auto-quality.png"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`requiredText prompt describing the image to generate or edit

▶images\[]

`array`maxItems: 16Input images for image editing, 1-16 entries. Each entry is base64-encoded (raw string or data:image/{png|jpeg|webp};base64,... URI).

quality

`string`enum: low, medium, high, autoQuality of the generated image

size

`string`enum: 256x256, 512x512, 1024x1024, 1792x1024, 1024x1792Size of the generated image

style

`string`enum: vivid, naturalStyle of the generated image

image

`string`format: uriURL to the generated image

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-image-1.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-image-1.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-image-1.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-image-1.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-image-1.5/#page","headline":"GPT Image 1.5","description":"OpenAI's image generation model that creates and edits images from text prompts, supporting multiple quality levels and output sizes.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-image-1.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: "OpenAI's next-generation image model that creates and edits images from text prompts, with support for multiple quality levels, sizes, and output formats. Note: transparent backgrounds are not supported — use openai/gpt-image-1.5 for transparent PNGs."
title: GPT Image 2
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT Image 2

Text-to-Image • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-image-2/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-image-2`

- Third-party
- Zero data retention

OpenAI's next-generation image model that creates and edits images from text prompts, with support for multiple quality levels, sizes, and output formats. Note: transparent backgrounds are not supported — use openai/gpt-image-1.5 for transparent PNGs.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Cached input image (per 1M tokens)$2.00</li><li>Cached input (per 1M tokens)$1.25</li><li>Input image (per 1M tokens)$8.00</li><li>Input (per 1M tokens)$5.00</li><li>Output image (per 1M tokens)$30.00</li><li>Output (per 1M tokens)$10.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-image-2',
  { prompt: 'A golden retriever puppy playing in autumn leaves' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2",
  "input": {
    "prompt": "A golden retriever puppy playing in autumn leaves"
  }
}'
```

![Simple Generation](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/simple-generation.png)

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/simple-generation.png"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**High Quality** — Generate a high-quality detailed image</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-2',
  {
    prompt:
      'A detailed botanical illustration of exotic tropical flowers with fine line work and watercolor textures',
    quality: 'high',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2",
  "input": {
    "prompt": "A detailed botanical illustration of exotic tropical flowers with fine line work and watercolor textures",
    "quality": "high"
  }
}'
```

![High Quality](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/high-quality.png)

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/high-quality.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Custom Size** — Generate a portrait-oriented image</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-2',
  {
    prompt: 'A towering redwood forest with sunbeams filtering through the canopy, misty atmosphere',
    size: '1024x1536',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2",
  "input": {
    "prompt": "A towering redwood forest with sunbeams filtering through the canopy, misty atmosphere",
    "size": "1024x1536"
  }
}'
```

![Custom Size](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/custom-size.png)

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/custom-size.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**WebP Output** — Generate an image in WebP format for smaller file size</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-2',
  {
    prompt:
      'A neon-lit cyberpunk cityscape at night with rain-slicked streets and holographic billboards',
    output_format: 'webp',
    quality: 'high',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2",
  "input": {
    "prompt": "A neon-lit cyberpunk cityscape at night with rain-slicked streets and holographic billboards",
    "output_format": "webp",
    "quality": "high"
  }
}'
```

![WebP Output](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/webp-output.webp)

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/webp-output.webp"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Image Edit** — Edit an existing image by providing it in the images array as base64 (a raw string or a data:image/{png|jpeg|webp};base64,... URI). This routes the call to OpenAI's /v1/images/edits endpoint. The example uses a tiny 32x32 smiley-face PNG - real inputs are the full base64 encoding of your source image.</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-2',
  {
    prompt:
      'Transform this cartoon smiley into a photorealistic 3D clay sculpture sitting on a marble pedestal, studio lighting',
    images: [
      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAnklEQVR42u2XQRLAIAgD8/839i/26qFCACm0ozPe1KwcQsAoXvgcAABxpwFowl4QWITHxW0LCBhxVngF4gKIirMQyBRnIJAtrkE8AuwWnyFEgKzfS1UA+3sWTju3BGAu7gKYIfBW+Q/AAQgBeMCkt1wVsLZjcwUYG2Z9wGLHZitWk1DEisubUYt2XB5IWkSyFqG0RSxvMZi0Gc1+Ox3fm00ZJ5mGVtkAAAAASUVORK5CYII=',
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2",
  "input": {
    "prompt": "Transform this cartoon smiley into a photorealistic 3D clay sculpture sitting on a marble pedestal, studio lighting",
    "images": [
      "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAnklEQVR42u2XQRLAIAgD8/839i/26qFCACm0ozPe1KwcQsAoXvgcAABxpwFowl4QWITHxW0LCBhxVngF4gKIirMQyBRnIJAtrkE8AuwWnyFEgKzfS1UA+3sWTju3BGAu7gKYIfBW+Q/AAQgBeMCkt1wVsLZjcwUYG2Z9wGLHZitWk1DEisubUYt2XB5IWkSyFqG0RSxvMZi0Gc1+Ox3fm00ZJ5mGVtkAAAAASUVORK5CYII="
    ]
  }
}'
```

![Image Edit](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/image-edit.png)

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/image-edit.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Multi-Image Edit** — Compose multiple input images by passing up to 16 base64 strings in the images array. The model blends the references; useful for combining subjects, styles, or reference shots. The example pairs a smiley-face PNG with a red ball PNG.</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-2',
  {
    prompt:
      'Combine these into a single photorealistic scene: a ceramic smiley-face mug next to a red rubber ball on a sunlit wooden table',
    images: [
      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAnklEQVR42u2XQRLAIAgD8/839i/26qFCACm0ozPe1KwcQsAoXvgcAABxpwFowl4QWITHxW0LCBhxVngF4gKIirMQyBRnIJAtrkE8AuwWnyFEgKzfS1UA+3sWTju3BGAu7gKYIfBW+Q/AAQgBeMCkt1wVsLZjcwUYG2Z9wGLHZitWk1DEisubUYt2XB5IWkSyFqG0RSxvMZi0Gc1+Ox3fm00ZJ5mGVtkAAAAASUVORK5CYII=',
      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAhklEQVR42u2XsRHAMAgDNY73nye7OG2KgGUnGCWH76j/oTACPfnhcwIA3AoTGIFXRTADPlqjakYEDJwFWyJLAk/hrAQi4YwEouEjiVuBt+FXCVcgqntvCtjVvTUF7OremkIJlEAJ6Aikf0QSX3H6MpJYx+mBRCKSSYRSiVgucZjInGa/vY5PvB72/7IdMuAAAAAASUVORK5CYII=',
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2",
  "input": {
    "prompt": "Combine these into a single photorealistic scene: a ceramic smiley-face mug next to a red rubber ball on a sunlit wooden table",
    "images": [
      "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAnklEQVR42u2XQRLAIAgD8/839i/26qFCACm0ozPe1KwcQsAoXvgcAABxpwFowl4QWITHxW0LCBhxVngF4gKIirMQyBRnIJAtrkE8AuwWnyFEgKzfS1UA+3sWTju3BGAu7gKYIfBW+Q/AAQgBeMCkt1wVsLZjcwUYG2Z9wGLHZitWk1DEisubUYt2XB5IWkSyFqG0RSxvMZi0Gc1+Ox3fm00ZJ5mGVtkAAAAASUVORK5CYII=",
      "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAhklEQVR42u2XsRHAMAgDNY73nye7OG2KgGUnGCWH76j/oTACPfnhcwIA3AoTGIFXRTADPlqjakYEDJwFWyJLAk/hrAQi4YwEouEjiVuBt+FXCVcgqntvCtjVvTUF7OremkIJlEAJ6Aikf0QSX3H6MpJYx+mBRCKSSYRSiVgucZjInGa/vY5PvB72/7IdMuAAAAAASUVORK5CYII="
    ]
  }
}'
```

![Multi-Image Edit](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/multi-image-edit.png)

```json
{
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__gpt-image-2/multi-image-edit.png"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`requiredText prompt describing the image to generate or edit

▶images\[]

`array`maxItems: 16Input images for image editing, 1-16 entries. Each entry is base64-encoded (raw string or data:image/{png|jpeg|webp};base64,... URI).

quality

`string`enum: low, medium, high, autoQuality of the generated image

size

`string`enum: 1024x1024, 1024x1536, 1536x1024, autoSize of the generated image

background

`string`enum: transparent, opaque, autoBackground transparency setting. Use transparent for images with no background, opaque for a solid background, or auto to let the model decide.

output\_format

`string`enum: png, webp, jpegOutput format for the generated image

image

`string`format: uriURL to the generated image

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-image-2/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-image-2/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-image-2/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-image-2/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-image-2/#page","headline":"GPT Image 2","description":"OpenAI's next-generation image model that creates and edits images from text prompts, with support for multiple quality levels, sizes, and output formats. Note: transparent backgrounds are not supported — use openai/gpt-image-1.5 for transparent PNGs.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-image-2/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: OpenAI's fastest high-quality everyday image generation model. It accepts text and image inputs and produces images with low, medium, high, xhigh, max, and auto quality settings.
title: GPT Image 2.5 Flare
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT Image 2.5 Flare

Text-to-Image • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-flare/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-image-2.5-flare`

- Third-party

OpenAI's fastest high-quality everyday image generation model. It accepts text and image inputs and produces images with low, medium, high, xhigh, max, and auto quality settings.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://developers.openai.com/api/docs/models/gpt-image-2.5-flare) |
| Pricing | <ul><li>Cached input image (per 1M tokens)$3.00</li><li>Cached input (per 1M tokens)$1.25</li><li>Input image (per 1M tokens)$8.00</li><li>Input (per 1M tokens)$5.00</li><li>Output image (per 1M tokens)$30.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-image-2.5-flare',
  {
    prompt:
      'A premium studio product photograph of a translucent orange mechanical keyboard on a cobalt blue acrylic pedestal, a few keys glowing amber, crisp reflections, bold geometric shadows, clean commercial art direction, no logos or readable words',
    quality: 'high',
    size: '1024x1024',
    output_format: 'jpeg',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2.5-flare",
  "input": {
    "prompt": "A premium studio product photograph of a translucent orange mechanical keyboard on a cobalt blue acrylic pedestal, a few keys glowing amber, crisp reflections, bold geometric shadows, clean commercial art direction, no logos or readable words",
    "quality": "high",
    "size": "1024x1024",
    "output_format": "jpeg"
  }
}'
```

![Commercial Product Scene](https://examples.aig.cloudflare.com/openai/gpt-image-2.5-flare/commercial-product-scene.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/openai/gpt-image-2.5-flare/commercial-product-scene.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Environmental Concept Frame** — Generate a wide environmental concept frame</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-2.5-flare',
  {
    prompt:
      'A wide establishing shot of a hidden mountain library carved into basalt cliffs, tiny figures crossing rope bridges, waterfalls disappearing into mist, late afternoon sun, grounded fantasy concept art with realistic scale',
    quality: 'xhigh',
    size: '1536x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2.5-flare",
  "input": {
    "prompt": "A wide establishing shot of a hidden mountain library carved into basalt cliffs, tiny figures crossing rope bridges, waterfalls disappearing into mist, late afternoon sun, grounded fantasy concept art with realistic scale",
    "quality": "xhigh",
    "size": "1536x1024"
  }
}'
```

![Environmental Concept Frame](https://examples.aig.cloudflare.com/openai/gpt-image-2.5-flare/environmental-concept-frame.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/openai/gpt-image-2.5-flare/environmental-concept-frame.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Poster Reference Edit** — Transform a reference sketch into a finished illustration</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-2.5-flare',
  {
    prompt:
      'Reimagine the reference as a vibrant risograph poster for a fictional night market. Keep the central market stall silhouette and hanging lantern arrangement, add layered coral, teal, and navy ink textures, imperfect registration, and a lively crowd rendered as abstract shapes',
    images: [
      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAnklEQVR42u2XQRLAIAgD8/839i/26qFCACm0ozPe1KwcQsAoXvgcAABxpwFowl4QWITHxW0LCBhxVngF4gKIirMQyBRnIJAtrkE8AuwWnyFEgKzfS1UA+3sWTju3BGAu7gKYIfBW+Q/AAQgBeMCkt1wVsLZjcwUYG2Z9wGLHZitWk1DEisubUYt2XB5IWkSyFqG0RSxvMZi0Gc1+Ox3fm00ZJ5mGVtkAAAAASUVORK5CYII=',
    ],
    quality: 'medium',
    output_format: 'png',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2.5-flare",
  "input": {
    "prompt": "Reimagine the reference as a vibrant risograph poster for a fictional night market. Keep the central market stall silhouette and hanging lantern arrangement, add layered coral, teal, and navy ink textures, imperfect registration, and a lively crowd rendered as abstract shapes",
    "images": [
      "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAnklEQVR42u2XQRLAIAgD8/839i/26qFCACm0ozPe1KwcQsAoXvgcAABxpwFowl4QWITHxW0LCBhxVngF4gKIirMQyBRnIJAtrkE8AuwWnyFEgKzfS1UA+3sWTju3BGAu7gKYIfBW+Q/AAQgBeMCkt1wVsLZjcwUYG2Z9wGLHZitWk1DEisubUYt2XB5IWkSyFqG0RSxvMZi0Gc1+Ox3fm00ZJ5mGVtkAAAAASUVORK5CYII="
    ],
    "quality": "medium",
    "output_format": "png"
  }
}'
```

![Poster Reference Edit](https://examples.aig.cloudflare.com/openai/gpt-image-2.5-flare/poster-reference-edit.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/openai/gpt-image-2.5-flare/poster-reference-edit.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredText prompt describing the image to generate or edit

▶images\[]

`array`maxItems: 16Input images for image editing, 1-16 entries. Each entry is base64-encoded (raw string or data:image/{png|jpeg|webp};base64,... URI).

quality

`string`enum: low, medium, high, xhigh, max, autoQuality of the generated image

size

`string`enum: 1024x1024, 1024x1536, 1536x1024, autoSize of the generated image

background

`string`enum: transparent, opaque, autoBackground transparency setting

output\_format

`string`enum: png, webp, jpegOutput format for the generated image

image

`string`format: uriURL to the generated image

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-flare/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-flare/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-flare/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-flare/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-flare/#page","headline":"GPT Image 2.5 Flare","description":"OpenAI's fastest high-quality everyday image generation model. It accepts text and image inputs and produces images with low, medium, high, xhigh, max, and auto quality settings.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-flare/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: OpenAI's most capable image generation and editing model. It accepts text and image inputs and produces images with low, medium, high, xhigh, max, and auto quality settings.
title: GPT Image 2.5 Sunburst
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# GPT Image 2.5 Sunburst

Text-to-Image • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-sunburst/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/gpt-image-2.5-sunburst`

- Third-party

OpenAI's most capable image generation and editing model. It accepts text and image inputs and produces images with low, medium, high, xhigh, max, and auto quality settings.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://developers.openai.com/api/docs/models/gpt-image-2.5-sunburst) |
| Pricing | <ul><li>Cached input image (per 1M tokens)$3.00</li><li>Cached input (per 1M tokens)$1.25</li><li>Input image (per 1M tokens)$8.00</li><li>Input (per 1M tokens)$5.00</li><li>Output image (per 1M tokens)$30.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/gpt-image-2.5-sunburst',
  {
    prompt:
      'A cutaway editorial illustration of a floating ocean research station during a storm, showing laboratories, hydroponic gardens, autonomous submersibles, and illuminated underwater cables, precise technical details, dramatic but realistic lighting',
    quality: 'max',
    size: '1536x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2.5-sunburst",
  "input": {
    "prompt": "A cutaway editorial illustration of a floating ocean research station during a storm, showing laboratories, hydroponic gardens, autonomous submersibles, and illuminated underwater cables, precise technical details, dramatic but realistic lighting",
    "quality": "max",
    "size": "1536x1024"
  }
}'
```

![Technical Editorial Illustration](https://examples.aig.cloudflare.com/openai/gpt-image-2.5-sunburst/technical-editorial-illustration.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/openai/gpt-image-2.5-sunburst/technical-editorial-illustration.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Portrait WebP** — Generate a portrait composition in WebP format</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-2.5-sunburst',
  {
    prompt:
      'A fashion portrait of an astronaut botanist in a glass greenhouse on Mars, crimson dust visible through the windows, translucent fabric, delicate blue flowers in the foreground, soft rim light, sophisticated magazine photography',
    quality: 'xhigh',
    size: '1024x1536',
    output_format: 'webp',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2.5-sunburst",
  "input": {
    "prompt": "A fashion portrait of an astronaut botanist in a glass greenhouse on Mars, crimson dust visible through the windows, translucent fabric, delicate blue flowers in the foreground, soft rim light, sophisticated magazine photography",
    "quality": "xhigh",
    "size": "1024x1536",
    "output_format": "webp"
  }
}'
```

![Portrait WebP](https://examples.aig.cloudflare.com/openai/gpt-image-2.5-sunburst/portrait-webp.webp)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/openai/gpt-image-2.5-sunburst/portrait-webp.webp"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Cinematic Reference Edit** — Edit a reference image into a cinematic scene while preserving its main subject</summary>



```ts
const response = await env.AI.run(
  'openai/gpt-image-2.5-sunburst',
  {
    prompt:
      "Turn the reference drawing into a polished cinematic stop-motion scene. Preserve the character's face and red scarf, add a miniature train platform at night, warm station lights, shallow depth of field, handcrafted felt and paper textures",
    images: [
      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAnklEQVR42u2XQRLAIAgD8/839i/26qFCACm0ozPe1KwcQsAoXvgcAABxpwFowl4QWITHxW0LCBhxVngF4gKIirMQyBRnIJAtrkE8AuwWnyFEgKzfS1UA+3sWTju3BGAu7gKYIfBW+Q/AAQgBeMCkt1wVsLZjcwUYG2Z9wGLHZitWk1DEisubUYt2XB5IWkSyFqG0RSxvMZi0Gc1+Ox3fm00ZJ5mGVtkAAAAASUVORK5CYII=',
    ],
    quality: 'high',
    background: 'opaque',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-image-2.5-sunburst",
  "input": {
    "prompt": "Turn the reference drawing into a polished cinematic stop-motion scene. Preserve the character'\''s face and red scarf, add a miniature train platform at night, warm station lights, shallow depth of field, handcrafted felt and paper textures",
    "images": [
      "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAnklEQVR42u2XQRLAIAgD8/839i/26qFCACm0ozPe1KwcQsAoXvgcAABxpwFowl4QWITHxW0LCBhxVngF4gKIirMQyBRnIJAtrkE8AuwWnyFEgKzfS1UA+3sWTju3BGAu7gKYIfBW+Q/AAQgBeMCkt1wVsLZjcwUYG2Z9wGLHZitWk1DEisubUYt2XB5IWkSyFqG0RSxvMZi0Gc1+Ox3fm00ZJ5mGVtkAAAAASUVORK5CYII="
    ],
    "quality": "high",
    "background": "opaque"
  }
}'
```

![Cinematic Reference Edit](https://examples.aig.cloudflare.com/openai/gpt-image-2.5-sunburst/cinematic-reference-edit.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/openai/gpt-image-2.5-sunburst/cinematic-reference-edit.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredText prompt describing the image to generate or edit

▶images\[]

`array`maxItems: 16Input images for image editing, 1-16 entries. Each entry is base64-encoded (raw string or data:image/{png|jpeg|webp};base64,... URI).

quality

`string`enum: low, medium, high, xhigh, max, autoQuality of the generated image

size

`string`enum: 1024x1024, 1024x1536, 1536x1024, autoSize of the generated image

background

`string`enum: transparent, opaque, autoBackground transparency setting

output\_format

`string`enum: png, webp, jpegOutput format for the generated image

image

`string`format: uriURL to the generated image

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-sunburst/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-sunburst/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-sunburst/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-sunburst/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-sunburst/#page","headline":"GPT Image 2.5 Sunburst","description":"OpenAI's most capable image generation and editing model. It accepts text and image inputs and produces images with low, medium, high, xhigh, max, and auto quality settings.","url":"https://developers.cloudflare.com/ai/models/openai/gpt-image-2.5-sunburst/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: o3 is OpenAI’s general-purpose reasoning model, balancing strong analytical performance with reasonable latency and cost.
title: o3
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# o3

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/o3/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/o3`

- Third-party
- Zero data retention

o3 is OpenAI’s general-purpose reasoning model, balancing strong analytical performance with reasonable latency and cost.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 200,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Output (per 1M tokens)$8.00</li><li>Cached input (per 1M tokens)$0.50</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/o3',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o3",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The three fundamental laws of thermodynamics can be stated informally as follows:

1. First Law (Law of Energy Conservation)  
   Energy cannot be created or destroyed; it can only change form. For any closed system the change in internal energy equals the heat added to the system minus the work done by the system.

2. Second Law (Law of Entropy)  
   In any natural (spontaneous) process the total entropy of an isolated system always increases or, at best, remains constant. Equivalently, heat cannot spontaneously flow from a colder body to a hotter body, and no heat engine operating in a cycle can be 100 % efficient.

3. Third Law (Absolute-zero Limit)  
   As the temperature of a perfect crystalline substance approaches absolute zero, its entropy approaches a minimum value (taken as zero). Therefore it is impossible to reach absolute zero by any finite series of processes.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "The three fundamental laws of thermodynamics can be stated informally as follows:\n\n1. First Law (Law of Energy Conservation)  \n   Energy cannot be created or destroyed; it can only change form. For any closed system the change in internal energy equals the heat added to the system minus the work done by the system.\n\n2. Second Law (Law of Entropy)  \n   In any natural (spontaneous) process the total entropy of an isolated system always increases or, at best, remains constant. Equivalently, heat cannot spontaneously flow from a colder body to a hotter body, and no heat engine operating in a cycle can be 100 % efficient.\n\n3. Third Law (Absolute-zero Limit)  \n   As the temperature of a perfect crystalline substance approaches absolute zero, its entropy approaches a minimum value (taken as zero). Therefore it is impossible to reach absolute zero by any finite series of processes.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319513,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMHh2qmPkLVJgEKu27EuhV3Zx6yU",
  "model": "o3-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 203,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 15,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 218
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/o3',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o3",
  "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"
    }
  ]
}'
```

````
Reading a JSON file in Python is straightforward with the built-in json module. Below are the most common patterns, from the simplest one-liner to approaches that add error handling, use pathlib, or parse to a pandas DataFrame.

────────────────────────
1. Quick start (basic usage)
────────────────────────
```python
import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)      # `data` is now a Python dict or list
```
• json.load() converts the JSON in the file to native Python objects (dict, list, int, float, str, bool, None).  
• encoding="utf-8" is often optional but safest—especially on Windows.

────────────────────────────────────────────────
2. Using pathlib (cleaner path handling, cross-platform)
───────────────────────────────────────────────────────
```python
from pathlib import Path
import json

json_path = Path("path") / "to" / "data.json"

with json_path.open(encoding="utf-8") as f:
    data = json.load(f)
```

──────────────────────────────────────────────
3. Adding error handling / validation
──────────────────────────────────────────────
```python
import json
from pathlib import Path

def read_json(path):
    try:
        with Path(path).open(encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"File not found: {path}")
    except json.JSONDecodeError as exc:
        print(f"Invalid JSON in {path}: {exc}")
    return None

data = read_json("data.json")
```

──────────────────────────────────────────────────────
4. Loading a JSON lines (NDJSON) file (one JSON per line)
──────────────────────────────────────────────────────
```python
import json

records = []
with open("data.ndjson", encoding="utf-8") as f:
    for line in f:
        records.append(json.loads(line))
```

──────────────────────────────────────
5. Directly into a pandas DataFrame
──────────────────────────────────────
If your JSON is an array of objects (list of dicts) or NDJSON:
```python
import pandas as pd

df = pd.read_json("data.json")          # Works for many cases
# For NDJSON:
df = pd.read_json("data.ndjson", lines=True)
```

────────────────────────
6. Writing JSON back out
────────────────────────
```python
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)
```
• indent adds pretty-printing.  
• ensure_ascii=False keeps non-ASCII characters intact.

That’s all you need to read (and write) JSON in Python!
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Reading a JSON file in Python is straightforward with the built-in json module. Below are the most common patterns, from the simplest one-liner to approaches that add error handling, use pathlib, or parse to a pandas DataFrame.\n\n────────────────────────\n1. Quick start (basic usage)\n────────────────────────\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)      # `data` is now a Python dict or list\n```\n• json.load() converts the JSON in the file to native Python objects (dict, list, int, float, str, bool, None).  \n• encoding=\"utf-8\" is often optional but safest—especially on Windows.\n\n────────────────────────────────────────────────\n2. Using pathlib (cleaner path handling, cross-platform)\n───────────────────────────────────────────────────────\n```python\nfrom pathlib import Path\nimport json\n\njson_path = Path(\"path\") / \"to\" / \"data.json\"\n\nwith json_path.open(encoding=\"utf-8\") as f:\n    data = json.load(f)\n```\n\n──────────────────────────────────────────────\n3. Adding error handling / validation\n──────────────────────────────────────────────\n```python\nimport json\nfrom pathlib import Path\n\ndef read_json(path):\n    try:\n        with Path(path).open(encoding=\"utf-8\") as f:\n            return json.load(f)\n    except FileNotFoundError:\n        print(f\"File not found: {path}\")\n    except json.JSONDecodeError as exc:\n        print(f\"Invalid JSON in {path}: {exc}\")\n    return None\n\ndata = read_json(\"data.json\")\n```\n\n──────────────────────────────────────────────────────\n4. Loading a JSON lines (NDJSON) file (one JSON per line)\n──────────────────────────────────────────────────────\n```python\nimport json\n\nrecords = []\nwith open(\"data.ndjson\", encoding=\"utf-8\") as f:\n    for line in f:\n        records.append(json.loads(line))\n```\n\n──────────────────────────────────────\n5. Directly into a pandas DataFrame\n──────────────────────────────────────\nIf your JSON is an array of objects (list of dicts) or NDJSON:\n```python\nimport pandas as pd\n\ndf = pd.read_json(\"data.json\")          # Works for many cases\n# For NDJSON:\ndf = pd.read_json(\"data.ndjson\", lines=True)\n```\n\n────────────────────────\n6. Writing JSON back out\n────────────────────────\n```python\nwith open(\"output.json\", \"w\", encoding=\"utf-8\") as f:\n    json.dump(data, f, indent=2, ensure_ascii=False)\n```\n• indent adds pretty-printing.  \n• ensure_ascii=False keeps non-ASCII characters intact.\n\nThat’s all you need to read (and write) JSON in Python!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319516,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMHkoogfY6tsXPCpST3p05XLwgi6",
  "model": "o3-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 599,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 629
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/o3',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o3",
  "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"
    }
  ]
}'
```

```
Below are two classic ways to get from San Francisco to Los Angeles, followed by the best stops on each. Pick the route (or combine sections of both) that matches the time you have and the mood you’re after.

────────────────────────
1. SCENIC COAST ROUTE
   Highway 1 / Pacific Coast Highway (PCH)
────────────────────────
Total distance: ≈ 460 mi  
Driving time (no stops): ≈ 9 hrs  
Ideal trip length: 2–4 days

North-to-South Highlights
1. Santa Cruz (75 mi / 1½ hr from SF)  
   • Surfing scene at Steamer Lane, Beach Boardwalk amusement park, funky downtown cafés.  
   • 10 min detour inland: Roaring Camp steam train through redwoods.

2. Monterey & Pacific Grove (45 mi)  
   • Monterey Bay Aquarium, Cannery Row, whale-watch/via kayak, 17-Mile Drive coastal loop.

3. Carmel-by-the-Sea (5 mi)  
   • Fairy-tale cottages, white-sand Carmel Beach, art galleries.  
   • Food tip: La Bicyclette or picnic from 5th Ave Deli.

4. Big Sur Corridor (25-90 mi)  
   • Bixby Creek Bridge photo stop.  
   • Garrapata & Pfeiffer Big Sur State Parks (purple-sand Pfeiffer Beach).  
   • Nepenthe Restaurant for clifftop views.  
   • McWay Falls at Julia Pfeiffer Burns SP (¼-mile walk to overlook).  
   • Overnight options: Big Sur Lodge, Ventana glamping, or campground sites book early.

5. Ragged Point (35 mi)  
   • “Gateway to Big Sur” cliffside vista + coffee/snack.

6. San Simeon / Hearst Castle (15 mi)  
   • 2-hr hilltop tour of William Randolph Hearst’s mansion.  
   • Elephant seal rookery at Piedras Blancas (free, near parking lot).

7. Cambria (8 mi)  
   • Moonstone Beach boardwalk, galleries, Linn’s pies.

8. Morro Bay (22 mi)  
   • Kayak around Morro Rock, sea otters in the marina, fish-n-chips on Embarcadero.

9. San Luis Obispo (13 mi)  
   • Thursday night farmers market, Mission San Luis Obispo, Bubblegum Alley.  
   • Unique stay: Madonna Inn’s themed rooms.

10. Pismo Beach / Oceano Dunes (12 mi)  
    • Walk the pier at sunset; rent an ATV on the dunes. Splash Café for chowder.

11. Danish Village of Solvang (55 mi)  
    • Windmills, aebleskiver pastries, nearby Santa Ynez wine tasting.

12. Santa Barbara (35 mi)  
    • Mediterranean downtown, Funk Zone wine bars, Stearns Wharf.  
    • Quick hike: Inspiration Point (3 mi round-trip).

13. Ventura & Channel Islands Gateway (30 mi)  
    • If you have a half-day, boat to Anacapa or Santa Cruz Island for hiking/kayaking.  
    • Otherwise stroll Ventura Pier and old-town Main St.

14. Malibu (29 mi)  
    • Lunch at Malibu Farm Café on the pier, surf at Zuma Beach, quick cliff walk at Point Dume.

15. Santa Monica & LA arrival (18 mi)  
    • Ferris wheel on the pier, bike path to Venice Beach.  
    • From here it’s 15–25 mi into Hollywood/Downtown depending on traffic.

────────────────────────
2. QUICK(ER) INLAND ROUTE
   US-101 ➜ CA-154 ➜ US-101 or I-5
────────────────────────
Total distance: ≈ 385 mi  
Driving time (no stops): ≈ 5 hrs 45 min  
Ideal trip length: 1–2 days  
Character: Rolling hills, vineyards, missions, fewer hairpin turns than Hwy 1.

Key Stops (North-to-South)
• Gilroy – Garlic capital, outlet shopping.  
• Paso Robles – 200+ wineries, Tin City craft beverage hub, Sensorio light--field art installation (night).  
• San Luis Obispo / Pismo (see above).  
• Solvang & Santa Ynez wine region (see above).  
• Santa Barbara (see above).  
• Optional fast cutover: at Gaviota take CA-154 (San Marcos Pass) to shave ~20 min and drop into Santa Barbara’s north side.  
• From Santa Barbara you can stay on 101 along the coast or jump to I-5 at Ventura (via CA-126) for a straight shot into LA.

────────────────────────
3. PLANNING TIPS
────────────────────────
Time of year
• Winter–spring: Whale migrations, lush green hills in Big Sur, chance of mudslides (check Caltrans).  
• Summer: Long daylight, heavier traffic, book lodgings far ahead. Coastal fog (“June Gloom”) often burns off by noon.  
• Fall: Warm, clear, vineyards in harvest, lighter crowds.

Road & safety
• Fill up before Big Sur; fuel is scarce/pricey between Carmel and Cambria.  
• Cell service is sporadic in Big Sur—download offline maps.  
• Carry layers: temperatures swing 30 °F between sun and coastal fog.

Lodging snapshot
• Quick overnights: Monterey, Cambria, San Luis Obispo, Santa Barbara.  
• Camping gems: Pfeiffer Big Sur SP, Kirk Creek (ocean bluff), Morro Bay SP, Refugio State Beach (just past Santa Barbara).  
• Boutique splurges: Post Ranch Inn (Big Sur), Hotel Cheval (Paso Robles), El Encanto (Santa Barbara).

Driving pace guide (coast route)
SF → Santa Cruz: 1½ hr  
Santa Cruz → Monterey/Carmel: 45 min  
Carmel → Ragged Point (start of Big Sur): 2 hrs (allow 3-4 hrs with view stops)  
Ragged Point → SLO: 1½ hrs  
SLO → Santa Barbara: 1½ hrs  
Santa Barbara → LA (Santa Monica): 1½ hrs (traffic can double this)

────────────────────────
4. SAMPLE ITINERARIES
────────────────────────
Two-day “Greatest Hits” (coast)
Day 1: SF → Monterey (aquarium & 17-Mile Drive) → Bixby Bridge sunset → overnight in Big Sur or Cambria.  
Day 2: Hearst Castle → Morro Bay lunch → Santa Barbara stroll/dinner → evening arrival in LA.

Three-day Leisure (mixed routes)
Day 1: SF → Santa Cruz boardwalk → Carmel lunch → Big Sur hiking → overnight in Cambria.  
Day 2: Cambria → Paso Robles wine tasting → Pismo Beach ATV at dunes → overnight in San Luis Obispo (Thursday farmers market).  
Day 3: Solvang pastries → Santa Barbara beach and mission → Malibu sunset → LA.

Express one-day (inland)
Morning: Leave SF 7 a.m. → coffee in Paso Robles (~11 a.m.) → lunch in Santa Barbara (~2 p.m.) → LA by dinner (~6 p.m.), assuming light traffic.

Enjoy the ride, keep an eye on real-time road conditions at quickmap.dot.ca.gov, and don’t forget your camera—this stretch is one of America’s finest coastal drives!
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Below are two classic ways to get from San Francisco to Los Angeles, followed by the best stops on each. Pick the route (or combine sections of both) that matches the time you have and the mood you’re after.\n\n────────────────────────\n1. SCENIC COAST ROUTE\n   Highway 1 / Pacific Coast Highway (PCH)\n────────────────────────\nTotal distance: ≈ 460 mi  \nDriving time (no stops): ≈ 9 hrs  \nIdeal trip length: 2–4 days\n\nNorth-to-South Highlights\n1. Santa Cruz (75 mi / 1½ hr from SF)  \n   • Surfing scene at Steamer Lane, Beach Boardwalk amusement park, funky downtown cafés.  \n   • 10 min detour inland: Roaring Camp steam train through redwoods.\n\n2. Monterey & Pacific Grove (45 mi)  \n   • Monterey Bay Aquarium, Cannery Row, whale-watch/via kayak, 17-Mile Drive coastal loop.\n\n3. Carmel-by-the-Sea (5 mi)  \n   • Fairy-tale cottages, white-sand Carmel Beach, art galleries.  \n   • Food tip: La Bicyclette or picnic from 5th Ave Deli.\n\n4. Big Sur Corridor (25-90 mi)  \n   • Bixby Creek Bridge photo stop.  \n   • Garrapata & Pfeiffer Big Sur State Parks (purple-sand Pfeiffer Beach).  \n   • Nepenthe Restaurant for clifftop views.  \n   • McWay Falls at Julia Pfeiffer Burns SP (¼-mile walk to overlook).  \n   • Overnight options: Big Sur Lodge, Ventana glamping, or campground sites book early.\n\n5. Ragged Point (35 mi)  \n   • “Gateway to Big Sur” cliffside vista + coffee/snack.\n\n6. San Simeon / Hearst Castle (15 mi)  \n   • 2-hr hilltop tour of William Randolph Hearst’s mansion.  \n   • Elephant seal rookery at Piedras Blancas (free, near parking lot).\n\n7. Cambria (8 mi)  \n   • Moonstone Beach boardwalk, galleries, Linn’s pies.\n\n8. Morro Bay (22 mi)  \n   • Kayak around Morro Rock, sea otters in the marina, fish-n-chips on Embarcadero.\n\n9. San Luis Obispo (13 mi)  \n   • Thursday night farmers market, Mission San Luis Obispo, Bubblegum Alley.  \n   • Unique stay: Madonna Inn’s themed rooms.\n\n10. Pismo Beach / Oceano Dunes (12 mi)  \n    • Walk the pier at sunset; rent an ATV on the dunes. Splash Café for chowder.\n\n11. Danish Village of Solvang (55 mi)  \n    • Windmills, aebleskiver pastries, nearby Santa Ynez wine tasting.\n\n12. Santa Barbara (35 mi)  \n    • Mediterranean downtown, Funk Zone wine bars, Stearns Wharf.  \n    • Quick hike: Inspiration Point (3 mi round-trip).\n\n13. Ventura & Channel Islands Gateway (30 mi)  \n    • If you have a half-day, boat to Anacapa or Santa Cruz Island for hiking/kayaking.  \n    • Otherwise stroll Ventura Pier and old-town Main St.\n\n14. Malibu (29 mi)  \n    • Lunch at Malibu Farm Café on the pier, surf at Zuma Beach, quick cliff walk at Point Dume.\n\n15. Santa Monica & LA arrival (18 mi)  \n    • Ferris wheel on the pier, bike path to Venice Beach.  \n    • From here it’s 15–25 mi into Hollywood/Downtown depending on traffic.\n\n────────────────────────\n2. QUICK(ER) INLAND ROUTE\n   US-101 ➜ CA-154 ➜ US-101 or I-5\n────────────────────────\nTotal distance: ≈ 385 mi  \nDriving time (no stops): ≈ 5 hrs 45 min  \nIdeal trip length: 1–2 days  \nCharacter: Rolling hills, vineyards, missions, fewer hairpin turns than Hwy 1.\n\nKey Stops (North-to-South)\n• Gilroy – Garlic capital, outlet shopping.  \n• Paso Robles – 200+ wineries, Tin City craft beverage hub, Sensorio light--field art installation (night).  \n• San Luis Obispo / Pismo (see above).  \n• Solvang & Santa Ynez wine region (see above).  \n• Santa Barbara (see above).  \n• Optional fast cutover: at Gaviota take CA-154 (San Marcos Pass) to shave ~20 min and drop into Santa Barbara’s north side.  \n• From Santa Barbara you can stay on 101 along the coast or jump to I-5 at Ventura (via CA-126) for a straight shot into LA.\n\n────────────────────────\n3. PLANNING TIPS\n────────────────────────\nTime of year\n• Winter–spring: Whale migrations, lush green hills in Big Sur, chance of mudslides (check Caltrans).  \n• Summer: Long daylight, heavier traffic, book lodgings far ahead. Coastal fog (“June Gloom”) often burns off by noon.  \n• Fall: Warm, clear, vineyards in harvest, lighter crowds.\n\nRoad & safety\n• Fill up before Big Sur; fuel is scarce/pricey between Carmel and Cambria.  \n• Cell service is sporadic in Big Sur—download offline maps.  \n• Carry layers: temperatures swing 30 °F between sun and coastal fog.\n\nLodging snapshot\n• Quick overnights: Monterey, Cambria, San Luis Obispo, Santa Barbara.  \n• Camping gems: Pfeiffer Big Sur SP, Kirk Creek (ocean bluff), Morro Bay SP, Refugio State Beach (just past Santa Barbara).  \n• Boutique splurges: Post Ranch Inn (Big Sur), Hotel Cheval (Paso Robles), El Encanto (Santa Barbara).\n\nDriving pace guide (coast route)\nSF → Santa Cruz: 1½ hr  \nSanta Cruz → Monterey/Carmel: 45 min  \nCarmel → Ragged Point (start of Big Sur): 2 hrs (allow 3-4 hrs with view stops)  \nRagged Point → SLO: 1½ hrs  \nSLO → Santa Barbara: 1½ hrs  \nSanta Barbara → LA (Santa Monica): 1½ hrs (traffic can double this)\n\n────────────────────────\n4. SAMPLE ITINERARIES\n────────────────────────\nTwo-day “Greatest Hits” (coast)\nDay 1: SF → Monterey (aquarium & 17-Mile Drive) → Bixby Bridge sunset → overnight in Big Sur or Cambria.  \nDay 2: Hearst Castle → Morro Bay lunch → Santa Barbara stroll/dinner → evening arrival in LA.\n\nThree-day Leisure (mixed routes)\nDay 1: SF → Santa Cruz boardwalk → Carmel lunch → Big Sur hiking → overnight in Cambria.  \nDay 2: Cambria → Paso Robles wine tasting → Pismo Beach ATV at dunes → overnight in San Luis Obispo (Thursday farmers market).  \nDay 3: Solvang pastries → Santa Barbara beach and mission → Malibu sunset → LA.\n\nExpress one-day (inland)\nMorning: Leave SF 7 a.m. → coffee in Paso Robles (~11 a.m.) → lunch in Santa Barbara (~2 p.m.) → LA by dinner (~6 p.m.), assuming light traffic.\n\nEnjoy the ride, keep an eye on real-time road conditions at quickmap.dot.ca.gov, and don’t forget your camera—this stretch is one of America’s finest coastal drives!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319524,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMHsVe39soRjpmDmECvFIoQCf6wr",
  "model": "o3-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 1844,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 128,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 76,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 1920
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/o3',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o3",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
Detective Lila Navarro crouched beside the overturned rowboat, lantern light trembling across the damp boards. The crime scene smelled of salt, river mud, and something sweeter—freshly ground cinnamon. That scent didn’t belong anywhere near the derelict wharf, yet here it lingered, strongest beneath one splintered plank. She wedged her penknife into the crack and lifted. Nestled in the dark hollow was a single, spotless chess pawn carved from cinnamon bark, its base stamped with today’s date. Lila straightened, pulse quickening. Whoever killed the dock watchman hadn’t just left a calling card; they’d seasoned the night with a puzzle only she would taste.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Detective Lila Navarro crouched beside the overturned rowboat, lantern light trembling across the damp boards. The crime scene smelled of salt, river mud, and something sweeter—freshly ground cinnamon. That scent didn’t belong anywhere near the derelict wharf, yet here it lingered, strongest beneath one splintered plank. She wedged her penknife into the crack and lifted. Nestled in the dark hollow was a single, spotless chess pawn carved from cinnamon bark, its base stamped with today’s date. Lila straightened, pulse quickening. Whoever killed the dock watchman hadn’t just left a calling card; they’d seasoned the night with a puzzle only she would taste.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319534,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMI2T4AGhgxBOrHO2qbtI0kqcaKK",
  "model": "o3-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 160,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 179
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/o3',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o3",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
Recursion is a problem-solving technique in which a function (or procedure) solves a task by calling itself on smaller or simpler parts of the original problem. Each self-call works on a reduced input until a condition is met that stops further calls; this stopping condition is called the base case.  

Why it works:  
1. Every call handles only a small piece of the work.  
2. The base case guarantees the chain of calls eventually ends.  
3. After the base case is reached, the results “bubble back” through the earlier calls to build the final answer.

Simple example: computing the factorial of a non-negative integer n (written n!).  
Factorial definition:  
• n! = n × (n − 1) × (n − 2) × … × 2 × 1  
• 0! is defined as 1.

Recursive idea:  
– Base case: 0! = 1 (also 1! = 1).  
– Recursive step: n! = n × (n − 1)! for n > 0.

Python-like pseudocode:

```
def factorial(n):
    if n == 0:           # base case
        return 1
    else:                # recursive case
        return n * factorial(n - 1)
```

How factorial(4) is evaluated:

1. factorial(4) = 4 × factorial(3)  
2. factorial(3) = 3 × factorial(2)  
3. factorial(2) = 2 × factorial(1)  
4. factorial(1) = 1 × factorial(0)  
5. factorial(0) = 1  ← base case reached  
Now the results return:  
– factorial(1) = 1 × 1 = 1  
– factorial(2) = 2 × 1 = 2  
– factorial(3) = 3 × 2 = 6  
– factorial(4) = 4 × 6 = 24

Thus factorial(4) = 24.

Key points to remember:  
• A recursive function must have at least one base case.  
• Each recursive call should bring the problem closer to that base case.  
• Recursion often leads to concise, readable solutions for problems that exhibit self-similar structure (e.g., factorial, Fibonacci numbers, tree traversal).
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777319539,
    "id": "chatcmpl-DZMI7UOwfhRHx1WTlcRkuP5IAox0f",
    "model": "o3-2025-04-16",
    "obfuscation": "6M1dnR1hOq2Q8",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777319539,
    "id": "chatcmpl-DZMI7UOwfhRHx1WTlcRkuP5IAox0f",
    "model": "o3-2025-04-16",
    "obfuscation": "C4AaX2uB3c8I",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  "... 507 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777319539,
    "id": "chatcmpl-DZMI7UOwfhRHx1WTlcRkuP5IAox0f",
    "model": "o3-2025-04-16",
    "obfuscation": "EueFN2OzMKtz",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 525,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 16,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 541
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'openai/o3',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o3",
  "input": "What were the top news stories about Cloudflare this week? Summarise in three bullets.",
  "max_output_tokens": 4096,
  "tools": [
    {
      "type": "web_search_preview"
    }
  ]
}'
```

```
• June 22, 2026 – A major Cloudflare network disruption rippled across the internet for several hours, knocking sites and apps such as X, Reddit, Zoom and Microsoft Teams offline worldwide.  Downdetector showed tens of thousands of outage reports before Cloudflare identified the root cause and began rolling out a fix. ([harianbasis.co](https://www.harianbasis.co/en/cloudflare-network-disruption-internet-outage))

• June 20, 2026 – Cloudflare confirmed it has completed the acquisition of VoidZero, the open-source team behind the Vite JavaScript build tool.  The deal folds Vite, Vitest and other high-performance developer utilities into Cloudflare’s Workers platform and edge network, with Cloudflare pledging to keep the tooling open-source and seeding a $1 million Vite ecosystem fund. ([harianbasis.co](https://www.harianbasis.co/en/cloudflare-acquires-voidzero-enhance-developer-tools))

• June 18, 2026 – The company launched a “Cloudflare One Design Partner” designation and an AI-powered deployment toolkit to help channel partners speed up Secure Access Service Edge (SASE) and Zero-Trust migrations.  Initial partners include Arctiq, Consortium, CMT, Presidio and The Missing Link, signalling deeper co-investment in partner-led security projects. ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption))
```

```json
{
  "id": "resp_0e3c03908b88cc21016a399b47cc30819b8238762306128bad",
  "object": "response",
  "created_at": 1782160199,
  "model": "o3-2025-04-16",
  "output": [
    {
      "id": "rs_0e3c03908b88cc21016a399b488764819b816bc9d4cf79f6f1",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b48e084819b82268938a45565d2",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news June 2026",
          "Cloudflare announces June 2026",
          "Cloudflare outage June 2026"
        ],
        "query": "Cloudflare news June 2026"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b4a2bc8819bbad43fa6282be05d",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b4b2adc819b914b6d039f72e7e4",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare outage June 20 2026"
        ],
        "query": "Cloudflare outage June 20 2026"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b4c4bac819bb1b53eb7cccd99c2",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b4c7170819bb3d0139a67899225",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare investor day June 2026 New York Stock Exchange",
          "Cloudflare AI security partner June 17 2026",
          "Cloudflare threat intelligence report 2026"
        ],
        "query": "Cloudflare investor day June 2026 New York Stock Exchange"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b4e29ac819baa943cc991c126e4",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b4e9464819b8eed3b9bb4b7ccb9",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "June 21 2026 Cloudflare",
          "June 22 2026 Cloudflare network disruption"
        ],
        "query": "June 21 2026 Cloudflare"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b505be0819bb23d59a0a7d12a01",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b5066b0819baa7bea052770d18f",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.harianbasis.co/en/cloudflare-network-disruption-internet-outage"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b512518819b8541cae697a2aae8",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b517544819b9aec941bfbb141de",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare outage June 22 2026 Reddit down"
        ],
        "query": "Cloudflare outage June 22 2026 Reddit down"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b53d520819b935ec374a95af017",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b5406fc819ba5032e5b6d5d5eb2",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://brandergroup.net/2026/06/cloudflares-ipv6-route-leak-exposed-routing-gaps/"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b54ffcc819ba4768f93b1a56964",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b5547b4819b9be06625da300d90",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b56169c819babddc29f78583f91",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b562c1c819b9149894d84b930c8",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.channele2e.com/brief/cloudflare-adds-design-partner-designation-for-sase-and-ai-security"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b56efa8819bb02217b18a3e8138",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b574c8c819ba0deefda3eaf09b8",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare stock June 19 2026 restructuring charge"
        ],
        "query": "Cloudflare stock June 19 2026 restructuring charge"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b5a8ffc819b8543d55709b897cb",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b5ac598819bb6c2c56a0a709731",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.investing.com/news/insider-trading-news/cloudflare-president-zatlyn-sells-175m-in-company-stock-93CH-4751078"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b5b9d6c819bb763557fd2291d72",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b5bb3f0819b96bd37a897758396",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "find_in_page",
        "pattern": "sold a total",
        "url": "https://www.investing.com/news/insider-trading-news/cloudflare-president-zatlyn-sells-175m-in-company-stock-93CH-4751078"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b5cc124819ba8a75c28875a8710",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b5dd75c819ba8eb3635a87e461c",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare acquires June 2026"
        ],
        "query": "Cloudflare acquires June 2026"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b60d610819b9f002ec12a155d11",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0e3c03908b88cc21016a399b61ea40819ba99cc8d1e20cf113",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.harianbasis.co/en/cloudflare-acquires-voidzero-enhance-developer-tools"
      }
    },
    {
      "id": "rs_0e3c03908b88cc21016a399b646190819bb4cd09ac04932b9e",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "msg_0e3c03908b88cc21016a399b6820bc819bb3680bc388bee072",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 415,
              "start_index": 320,
              "title": "Cloudflare Network Disruption Triggers Widespread Internet Outages",
              "url": "https://www.harianbasis.co/en/cloudflare-network-disruption-internet-outage"
            },
            {
              "type": "url_citation",
              "end_index": 896,
              "start_index": 794,
              "title": "Cloudflare Acquires VoidZero to Enhance G
... response truncated ...
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/o3/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/o3/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/o3/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/o3/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/o3/#page","headline":"o3","description":"o3 is OpenAI’s general-purpose reasoning model, balancing strong analytical performance with reasonable latency and cost.","url":"https://developers.cloudflare.com/ai/models/openai/o3/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: o3-mini is the lightweight, low-cost reasoning variant of o3, well suited to quick analytical tasks at scale.
title: o3-mini
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# o3-mini

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/o3-mini/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/o3-mini`

- Third-party
- Zero data retention

o3-mini is the lightweight, low-cost reasoning variant of o3, well suited to quick analytical tasks at scale.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 200,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$1.10</li><li>Output (per 1M tokens)$4.40</li><li>Cached input (per 1M tokens)$0.55</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/o3-mini',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o3-mini",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
There are a few ways people count the laws of thermodynamics, but a common approach (especially in basic texts) is to focus on these three:

1. First Law of Thermodynamics (Law of Energy Conservation)  
 • This law states that energy cannot be created or destroyed—only converted from one form to another. In a closed system, the total energy remains constant. For example, when you burn fuel, the chemical energy is converted into heat and work.

2. Second Law of Thermodynamics  
 • This law introduces the concept of entropy, a measure of disorder. It states that in any natural (irreversible) process, the total entropy of an isolated system increases (or remains constant in ideal reversible cases). This explains why heat flows spontaneously from hot to cold and why certain processes (like perpetual motion machines) are impossible.

3. Third Law of Thermodynamics  
 • The third law states that as the temperature of a system approaches absolute zero (0 Kelvin), the entropy of a perfect crystal approaches zero. This law implies that absolute zero is unattainable and provides a reference point for the measurement of entropy.

Note: There is also the Zeroth Law of Thermodynamics, which is sometimes considered foundational. 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 is crucial in defining temperature but is not always numbered among the “three” if one starts counting from the first law.

These laws together form the basis of classical thermodynamics, helping us understand energy flow, heat transfer, and the directionality of physical processes.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "There are a few ways people count the laws of thermodynamics, but a common approach (especially in basic texts) is to focus on these three:\n\n1. First Law of Thermodynamics (Law of Energy Conservation)  \n • This law states that energy cannot be created or destroyed—only converted from one form to another. In a closed system, the total energy remains constant. For example, when you burn fuel, the chemical energy is converted into heat and work.\n\n2. Second Law of Thermodynamics  \n • This law introduces the concept of entropy, a measure of disorder. It states that in any natural (irreversible) process, the total entropy of an isolated system increases (or remains constant in ideal reversible cases). This explains why heat flows spontaneously from hot to cold and why certain processes (like perpetual motion machines) are impossible.\n\n3. Third Law of Thermodynamics  \n • The third law states that as the temperature of a system approaches absolute zero (0 Kelvin), the entropy of a perfect crystal approaches zero. This law implies that absolute zero is unattainable and provides a reference point for the measurement of entropy.\n\nNote: There is also the Zeroth Law of Thermodynamics, which is sometimes considered foundational. 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 is crucial in defining temperature but is not always numbered among the “three” if one starts counting from the first law.\n\nThese laws together form the basis of classical thermodynamics, helping us understand energy flow, heat transfer, and the directionality of physical processes.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319807,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMRxtcAbZLwD8Nd6POej2jkkjhT",
  "model": "o3-mini-2025-01-31",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_4e608cacbe",
  "usage": {
    "completion_tokens": 851,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 512,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 15,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 866
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/o3-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o3-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"
    }
  ]
}'
```

```
To read a JSON file in Python, you can use the built-in json module. This module provides methods for encoding and decoding JSON data. Typically, you'll want to use the json.load() function to read and parse JSON data from a file. Here’s a simple step-by-step example:

1. Import the json module.
2. Open the JSON file using the with context manager (this automatically closes the file after you're done).
3. Use json.load() to parse the file.

Below is the complete example code:

--------------------------------------------------
import json

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

# Now 'data' contains the JSON file content as a Python dictionary (or list, depending on JSON structure)
print(data)
--------------------------------------------------

Explanation:
• The with statement is used to open the file, which ensures that the file is properly closed even if an error occurs.
• The 'r' mode is specified to open the file in read mode.
• json.load(file) parses the JSON content and returns a Python object.
• The resulting data is stored in the variable data, which you can then work with as needed.

If you have any questions or need further assistance, feel free to ask!
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "To read a JSON file in Python, you can use the built-in json module. This module provides methods for encoding and decoding JSON data. Typically, you'll want to use the json.load() function to read and parse JSON data from a file. Here’s a simple step-by-step example:\n\n1. Import the json module.\n2. Open the JSON file using the with context manager (this automatically closes the file after you're done).\n3. Use json.load() to parse the file.\n\nBelow is the complete example code:\n\n--------------------------------------------------\nimport json\n\n# Open the JSON file and load its content\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\n# Now 'data' contains the JSON file content as a Python dictionary (or list, depending on JSON structure)\nprint(data)\n--------------------------------------------------\n\nExplanation:\n• The with statement is used to open the file, which ensures that the file is properly closed even if an error occurs.\n• The 'r' mode is specified to open the file in read mode.\n• json.load(file) parses the JSON content and returns a Python object.\n• The resulting data is stored in the variable data, which you can then work with as needed.\n\nIf you have any questions or need further assistance, feel free to ask!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319809,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMT5z8IEzwWx4HmgAYT2WScVD5o",
  "model": "o3-mini-2025-01-31",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_7a15bf1b39",
  "usage": {
    "completion_tokens": 400,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 128,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 430
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/o3-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o3-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"
    }
  ]
}'
```

```
Great! When planning a road trip along the scenic coast (California's Highway 1), here are some must-see stops between San Francisco and Los Angeles:

1. Santa Cruz:  
   • Enjoy the laid-back vibe at the Santa Cruz Beach Boardwalk.  
   • Take a stroll by the beach or check out the local shops and cafés downtown.

2. Monterey & Cannery Row:  
   • Visit the famous Monterey Bay Aquarium, a highlight of the area.  
   • Walk along Cannery Row and relish the coastal views or even take a local boat tour.
   • If time allows, consider the 17-Mile Drive in nearby Pebble Beach for a fantastic coastline drive.

3. Carmel-by-the-Sea:  
   • This charming town offers art galleries, boutique shopping, and quaint cafés in a picturesque setting.  
   • Enjoy the beautiful white-sand Carmel Beach and a stroll through the fairy-tale village.

4. Big Sur:  
   • Drive through one of the most breathtaking stretches of coastline in the world.  
   • Stop at iconic landmarks like Bixby Creek Bridge or take in the views from Nepenthe.  
   • Enjoy a short hike or simply take in the ocean views over cliffs—just be sure to check road conditions, as parts of Highway 1 can be winding.

5. San Simeon/Hearst Castle:  
   • Explore Hearst Castle, a historic mansion with impressive architecture and art.  
   • Enjoy nearby coastal views and wildlife, including elephant seals which often hang out at the beaches.

6. Santa Barbara (Optional Stop):  
   • Once you start heading toward Los Angeles, a stop in Santa Barbara can be a relaxing break.  
   • Stroll through the downtown area, visit the historic Mission Santa Barbara or relax at the beach.

Depending on your schedule and interests, you can choose to spend more time in one area than another. For instance, if you're a nature lover, spending a day in Big Sur might be perfect for you. Alternatively, beer or foodie enthusiasts might enjoy more time exploring the eateries in Monterey or Santa Barbara.

Some additional tips:  
• Always check for road conditions and parking information especially in Big Sur, as it can get busy on weekends.  
• Consider making reservations at popular restaurants or attractions in advance.  
• Pack some snacks and water, as some stretches between stops can be remote.

Would you like more detailed itineraries for any of these stops, or do you have specific interests (like hiking, dining, or cultural attractions) that we should highlight?
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Great! When planning a road trip along the scenic coast (California's Highway 1), here are some must-see stops between San Francisco and Los Angeles:\n\n1. Santa Cruz:  \n   • Enjoy the laid-back vibe at the Santa Cruz Beach Boardwalk.  \n   • Take a stroll by the beach or check out the local shops and cafés downtown.\n\n2. Monterey & Cannery Row:  \n   • Visit the famous Monterey Bay Aquarium, a highlight of the area.  \n   • Walk along Cannery Row and relish the coastal views or even take a local boat tour.\n   • If time allows, consider the 17-Mile Drive in nearby Pebble Beach for a fantastic coastline drive.\n\n3. Carmel-by-the-Sea:  \n   • This charming town offers art galleries, boutique shopping, and quaint cafés in a picturesque setting.  \n   • Enjoy the beautiful white-sand Carmel Beach and a stroll through the fairy-tale village.\n\n4. Big Sur:  \n   • Drive through one of the most breathtaking stretches of coastline in the world.  \n   • Stop at iconic landmarks like Bixby Creek Bridge or take in the views from Nepenthe.  \n   • Enjoy a short hike or simply take in the ocean views over cliffs—just be sure to check road conditions, as parts of Highway 1 can be winding.\n\n5. San Simeon/Hearst Castle:  \n   • Explore Hearst Castle, a historic mansion with impressive architecture and art.  \n   • Enjoy nearby coastal views and wildlife, including elephant seals which often hang out at the beaches.\n\n6. Santa Barbara (Optional Stop):  \n   • Once you start heading toward Los Angeles, a stop in Santa Barbara can be a relaxing break.  \n   • Stroll through the downtown area, visit the historic Mission Santa Barbara or relax at the beach.\n\nDepending on your schedule and interests, you can choose to spend more time in one area than another. For instance, if you're a nature lover, spending a day in Big Sur might be perfect for you. Alternatively, beer or foodie enthusiasts might enjoy more time exploring the eateries in Monterey or Santa Barbara.\n\nSome additional tips:  \n• Always check for road conditions and parking information especially in Big Sur, as it can get busy on weekends.  \n• Consider making reservations at popular restaurants or attractions in advance.  \n• Pack some snacks and water, as some stretches between stops can be remote.\n\nWould you like more detailed itineraries for any of these stops, or do you have specific interests (like hiking, dining, or cultural attractions) that we should highlight?",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319813,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMXgd7WUjV61fWbXbNNhOFEVnNB",
  "model": "o3-mini-2025-01-31",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_7a15bf1b39",
  "usage": {
    "completion_tokens": 917,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 384,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 74,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 991
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/o3-mini',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o3-mini",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
Detective Elena Marquez stood motionless in the dim glow of the abandoned warehouse, her eyes fixated on a peculiar object half-buried in layers of dust and cobwebs. Amidst scattered papers and defaced photographs, the unusual clue—a small porcelain figurine with an ethereal, almost luminescent crack running down its side—seemed to beckon her closer. Its delicate features, strangely out of place in this grim setting, whispered secrets of a long-forgotten past and hinted at connections far deeper than any ordinary case.

As she carefully lifted the figurine with gloved hands, Elena noted an inscription faintly etched along its base, its characters reminiscent of an undiscovered language. The artifact pulsed with an energy that both unnerved and fascinated her, a silent promise that solving its mystery might unravel the threads of a labyrinthine conspiracy. In that hushed moment, the detective realized that this was no random piece of debris—it was an intentional breadcrumb leading to a truth hidden beneath layers of time and deceit.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Detective Elena Marquez stood motionless in the dim glow of the abandoned warehouse, her eyes fixated on a peculiar object half-buried in layers of dust and cobwebs. Amidst scattered papers and defaced photographs, the unusual clue—a small porcelain figurine with an ethereal, almost luminescent crack running down its side—seemed to beckon her closer. Its delicate features, strangely out of place in this grim setting, whispered secrets of a long-forgotten past and hinted at connections far deeper than any ordinary case.\n\nAs she carefully lifted the figurine with gloved hands, Elena noted an inscription faintly etched along its base, its characters reminiscent of an undiscovered language. The artifact pulsed with an energy that both unnerved and fascinated her, a silent promise that solving its mystery might unravel the threads of a labyrinthine conspiracy. In that hushed moment, the detective realized that this was no random piece of debris—it was an intentional breadcrumb leading to a truth hidden beneath layers of time and deceit.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319815,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMMZ0kiOSZsAi3ZVIKwPfnLDiAIz",
  "model": "o3-mini-2025-01-31",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": "fp_7a15bf1b39",
  "usage": {
    "completion_tokens": 414,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 192,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 433
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/o3-mini',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o3-mini",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

```
Recursion is a technique in programming where a function calls itself to solve a problem. The function breaks the problem into smaller, similar subproblems until it reaches a simple case that can be solved directly—this is known as the base case. Once the base case is reached, the recursion stops, and the solutions to the smaller subproblems are combined to solve the original problem.

A simple example is calculating the factorial of a number. The factorial of a non-negative integer n (written as n!) is defined as:

  n! = n × (n-1) × (n-2) × ... × 1

By definition, 0! is 1. Using recursion, you can express the factorial function as:

  factorial(n) = n × factorial(n-1)

with the base case:

  factorial(0) = 1

Here’s a step-by-step explanation:

1. If n is 0, return 1 (base case).
2. Otherwise, return n multiplied by the factorial of (n-1).

For example, to compute 3!:
  • factorial(3) = 3 × factorial(2)
  • factorial(2) = 2 × factorial(1)
  • factorial(1) = 1 × factorial(0)
  • factorial(0) = 1 (base case)

Working back up:
  • factorial(1) = 1 × 1 = 1
  • factorial(2) = 2 × 1 = 2
  • factorial(3) = 3 × 2 = 6

Thus, 3! equals 6.

This example illustrates how recursion solves a problem by simplifying it step by step until it reaches a solution.
```

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777319820,
    "id": "chatcmpl-DZMMetd1XpZ1frdVc0o4T4L12OVXk",
    "model": "o3-mini-2025-01-31",
    "obfuscation": "zz38RTm3YrrY6",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_b5e0a50a2e",
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1777319820,
    "id": "chatcmpl-DZMMetd1XpZ1frdVc0o4T4L12OVXk",
    "model": "o3-mini-2025-01-31",
    "obfuscation": "Q2PVeG8xwBfH",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_b5e0a50a2e",
    "usage": null
  },
  "... 371 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777319820,
    "id": "chatcmpl-DZMMetd1XpZ1frdVc0o4T4L12OVXk",
    "model": "o3-mini-2025-01-31",
    "obfuscation": "2wTYZNsXap",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": "fp_b5e0a50a2e",
    "usage": {
      "completion_tokens": 640,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 256,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 16,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 656
    }
  }
]
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/o3-mini/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/o3-mini/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/o3-mini/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/o3-mini/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/o3-mini/#page","headline":"o3-mini","description":"o3-mini is the lightweight, low-cost reasoning variant of o3, well suited to quick analytical tasks at scale.","url":"https://developers.cloudflare.com/ai/models/openai/o3-mini/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: OpenAI's fast, lightweight reasoning model optimized for multi-step problem solving at lower cost.
title: o4-mini
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# o4-mini

Text Generation • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/o4-mini/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/o4-mini`

- Third-party
- Zero data retention

OpenAI's fast, lightweight reasoning model optimized for multi-step problem solving at lower cost.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 200,000 tokens |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://openai.com/) |
| Zero data retention | Yes |
| Request formats | Responses, Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$1.10</li><li>Output (per 1M tokens)$4.40</li><li>Cached input (per 1M tokens)$0.275</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/o4-mini',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o4-mini",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
Here are the three (classical) laws of thermodynamics:

1. First Law (Conservation of Energy)  
     – Statement: Energy can neither be created nor destroyed, only converted from one form to another.  
     – Formulation: ΔU = Q – W  
      • ΔU is the change in internal energy of the system  
      • Q is heat added to the system  
      • W is work done by the system  

2. Second Law (Entropy Increase)  
     – Statement: In any spontaneous process, the total entropy of an isolated system never decreases; it increases for irreversible processes and remains constant for reversible ones.  
     – Key consequences:  
      • Heat cannot spontaneously flow from cold to hot (Clausius statement)  
      • No heat engine can be 100% efficient (Kelvin–Planck statement)  

3. Third Law (Unattainability of Absolute Zero)  
     – Statement: As the temperature of a perfect crystalline substance approaches absolute zero (0 K), its entropy approaches a constant minimum (often taken as zero).  
     – Consequence: It is impossible to reach absolute zero in a finite number of steps.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Here are the three (classical) laws of thermodynamics:\n\n1. First Law (Conservation of Energy)  \n     – Statement: Energy can neither be created nor destroyed, only converted from one form to another.  \n     – Formulation: ΔU = Q – W  \n      • ΔU is the change in internal energy of the system  \n      • Q is heat added to the system  \n      • W is work done by the system  \n\n2. Second Law (Entropy Increase)  \n     – Statement: In any spontaneous process, the total entropy of an isolated system never decreases; it increases for irreversible processes and remains constant for reversible ones.  \n     – Key consequences:  \n      • Heat cannot spontaneously flow from cold to hot (Clausius statement)  \n      • No heat engine can be 100% efficient (Kelvin–Planck statement)  \n\n3. Third Law (Unattainability of Absolute Zero)  \n     – Statement: As the temperature of a perfect crystalline substance approaches absolute zero (0 K), its entropy approaches a constant minimum (often taken as zero).  \n     – Consequence: It is impossible to reach absolute zero in a finite number of steps.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470984,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnXkjut2BEk7At18pcFMPV5TOSoc",
  "model": "o4-mini-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 505,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 192,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 15,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 520
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'openai/o4-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o4-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"
    }
  ]
}'
```

````
Here’s the most common way, using Python’s built-in json module:

```python
import json

# 1. Open the file
with open("data.json", "r", encoding="utf-8") as f:
    # 2. Parse the JSON into a Python object (dict or list)
    data = json.load(f)

# 3. Now `data` is a normal Python dict/list
print(data)
print(type(data))      # e.g. <class 'dict'>
print(data["someKey"]) # access fields as usual
```

Explanation:

 1. `open(..., "r", encoding="utf-8")` opens in read-mode.
 2. `json.load(f)` reads the entire file and deserializes it to a Python object.
 3. You can now work with it like any dict or list.

If you already have a JSON string in memory, use `json.loads()`:

```python
import json

json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)
```

Error handling example:

```python
import json

try:
    with open("data.json", encoding="utf-8") as f:
        data = json.load(f)
except FileNotFoundError:
    print("File not found")
except json.JSONDecodeError as e:
    print("Invalid JSON:", e)
else:
    # success
    print(data)
```

Alternative with pathlib:

```python
from pathlib import Path
import json

text = Path("data.json").read_text(encoding="utf-8")
data = json.loads(text)
```

That’s all you need to read JSON files in Python!
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Here’s the most common way, using Python’s built-in json module:\n\n```python\nimport json\n\n# 1. Open the file\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    # 2. Parse the JSON into a Python object (dict or list)\n    data = json.load(f)\n\n# 3. Now `data` is a normal Python dict/list\nprint(data)\nprint(type(data))      # e.g. <class 'dict'>\nprint(data[\"someKey\"]) # access fields as usual\n```\n\nExplanation:\n\n 1. `open(..., \"r\", encoding=\"utf-8\")` opens in read-mode.\n 2. `json.load(f)` reads the entire file and deserializes it to a Python object.\n 3. You can now work with it like any dict or list.\n\nIf you already have a JSON string in memory, use `json.loads()`:\n\n```python\nimport json\n\njson_str = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_str)\n```\n\nError handling example:\n\n```python\nimport json\n\ntry:\n    with open(\"data.json\", encoding=\"utf-8\") as f:\n        data = json.load(f)\nexcept FileNotFoundError:\n    print(\"File not found\")\nexcept json.JSONDecodeError as e:\n    print(\"Invalid JSON:\", e)\nelse:\n    # success\n    print(data)\n```\n\nAlternative with pathlib:\n\n```python\nfrom pathlib import Path\nimport json\n\ntext = Path(\"data.json\").read_text(encoding=\"utf-8\")\ndata = json.loads(text)\n```\n\nThat’s all you need to read JSON files in Python!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470984,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnXkrglfCO4sLEI5BodnMzerw1Ev",
  "model": "o4-mini-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 499,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 128,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 529
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'openai/o4-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o4-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"
    }
  ]
}'
```

```
Here are two popular ways to make the trip—with suggested stops—so you can pick the one that best fits your interests and schedule.  

1. Coastal Highway (CA-1 / Pacific Coast Highway)  
   Total driving time: ~8–10 hours (no major traffic), 450 miles  
   Recommended pace: 2–3 days  

   • Half Moon Bay (30 mi / 45 min from SF)  
     – Stroll the beaches, grab coffee or seafood at the harbor.  
     – Quick dune hike at Poplar Beach or Fitzgerald Marine Reserve.  

   • Santa Cruz (50 mi / 1 hr from Half Moon Bay)  
     – Santa Cruz Beach Boardwalk for rides & arcade.  
     – Downtown Pacific Avenue for shops and local brews.  

   • Capitola (5 mi / 10 min from Santa Cruz)  
     – Colorful seaside village with boutique shops and cafés.  
     – Great spot for sunset on Capitola Beach.  

   • Monterey & Carmel (45 mi / 1 hr from Capitola)  
     – Monterey Bay Aquarium, Cannery Row, coastal bike path.  
     – Carmel-by-the-Sea: fairy-tale cottages, art galleries, Carmel Mission.  
     – 17-Mile Drive (pebbled beaches, peacocks, iconic Lone Cypress).  

   • Big Sur (30 mi / 1 hr from Carmel)  
     – Bixby Creek Bridge photo-op.  
     – Pfeiffer Beach (purple sand) and McWay Falls at Julia Pfeiffer Burns State Park.  
     – Ragged Point for coastal vistas and snacks.  
     Overnight option: Big Sur Lodge or camping.  

   • San Simeon & Cambria (45 mi / 1 hr from Big Sur)  
     – Hearst Castle tour.  
     – Elephant Seal Vista Point just north of San Simeon.  
     – Cambria’s Moonstone Beach Boardwalk and quaint Main Street.  

   • Morro Bay (25 mi / 35 min from Cambria)  
     – Morro Rock, waterfront restaurants, kayaking and bird-watching.  

   • San Luis Obispo (30 mi / 35 min from Morro Bay)  
     – Mission San Luis Obispo de Tolosa.  
     – Bubblegum Alley and bustling Higuera Street for dinner or a brew.  
     Overnight option: downtown SLO.  

   • Pismo Beach & Solvang (option)  
     – Pismo: pier, ATV dunes at nearby Oceano Dunes.  
     – Solvang: Danish-style village and bakeries (20 mi inland from Pismo).  

   • Santa Barbara (100 mi / 2 hrs from SLO)  
     – State Street shopping, Stearns Wharf, Mission Santa Barbara.  
     – Wine tasting in the nearby Funk Zone or Santa Ynez Valley.  

   • Malibu & Santa Monica (90 mi / 1½–2 hrs from SB)  
     – Malibu’s Zuma Beach or Point Dume.  
     – Santa Monica Pier, Third Street Promenade.  

   • Los Angeles (20 mi / 30 min from Santa Monica)  
     – Welcome to LA!  

2. Faster Inland Route (I-5)  
   Total driving time: ~6 hrs, 380 miles  
   Good if you’re pressed for time;  fewer scenic overlooks but easier mileage.  

   Key stops along I-5:  
   • Gilroy (40 mi / 45 min from SF) – Home of the Garlic Festival; farm stands.  
   • Kettleman City (160 mi / 2½ hrs from Gilroy) – Bravo Farms for ice cream and picnic.  
   • Harris Ranch (80 mi / 1 hr from Kettleman) – Large steakhouse, deli and wine shop.  
   • Grapevine / Tejon Pass (65 mi / 1 hr from Harris) – Decent rest-stop restaurants and views as you descend into Southern California.  
   • Valencia / Santa Clarita (30 mi / 30 min from Grapevine) – Valencia Town Center for shops.  
   • Los Angeles (35 mi / 40 min from Valencia)  

—  
Tips:  
• Plan fuel and rest stops in Big Sur — services are sparse.  
• Book lodging early if traveling weekends or holidays (Big Sur, SLO, Santa Barbara are popular).  
• Allow extra time for traffic, especially near Malibu, Santa Barbara, and LA.  

Enjoy your trip! Let me know if you need more detail on any stop or lodging suggestions.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Here are two popular ways to make the trip—with suggested stops—so you can pick the one that best fits your interests and schedule.  \n\n1. Coastal Highway (CA-1 / Pacific Coast Highway)  \n   Total driving time: ~8–10 hours (no major traffic), 450 miles  \n   Recommended pace: 2–3 days  \n\n   • Half Moon Bay (30 mi / 45 min from SF)  \n     – Stroll the beaches, grab coffee or seafood at the harbor.  \n     – Quick dune hike at Poplar Beach or Fitzgerald Marine Reserve.  \n\n   • Santa Cruz (50 mi / 1 hr from Half Moon Bay)  \n     – Santa Cruz Beach Boardwalk for rides & arcade.  \n     – Downtown Pacific Avenue for shops and local brews.  \n\n   • Capitola (5 mi / 10 min from Santa Cruz)  \n     – Colorful seaside village with boutique shops and cafés.  \n     – Great spot for sunset on Capitola Beach.  \n\n   • Monterey & Carmel (45 mi / 1 hr from Capitola)  \n     – Monterey Bay Aquarium, Cannery Row, coastal bike path.  \n     – Carmel-by-the-Sea: fairy-tale cottages, art galleries, Carmel Mission.  \n     – 17-Mile Drive (pebbled beaches, peacocks, iconic Lone Cypress).  \n\n   • Big Sur (30 mi / 1 hr from Carmel)  \n     – Bixby Creek Bridge photo-op.  \n     – Pfeiffer Beach (purple sand) and McWay Falls at Julia Pfeiffer Burns State Park.  \n     – Ragged Point for coastal vistas and snacks.  \n     Overnight option: Big Sur Lodge or camping.  \n\n   • San Simeon & Cambria (45 mi / 1 hr from Big Sur)  \n     – Hearst Castle tour.  \n     – Elephant Seal Vista Point just north of San Simeon.  \n     – Cambria’s Moonstone Beach Boardwalk and quaint Main Street.  \n\n   • Morro Bay (25 mi / 35 min from Cambria)  \n     – Morro Rock, waterfront restaurants, kayaking and bird-watching.  \n\n   • San Luis Obispo (30 mi / 35 min from Morro Bay)  \n     – Mission San Luis Obispo de Tolosa.  \n     – Bubblegum Alley and bustling Higuera Street for dinner or a brew.  \n     Overnight option: downtown SLO.  \n\n   • Pismo Beach & Solvang (option)  \n     – Pismo: pier, ATV dunes at nearby Oceano Dunes.  \n     – Solvang: Danish-style village and bakeries (20 mi inland from Pismo).  \n\n   • Santa Barbara (100 mi / 2 hrs from SLO)  \n     – State Street shopping, Stearns Wharf, Mission Santa Barbara.  \n     – Wine tasting in the nearby Funk Zone or Santa Ynez Valley.  \n\n   • Malibu & Santa Monica (90 mi / 1½–2 hrs from SB)  \n     – Malibu’s Zuma Beach or Point Dume.  \n     – Santa Monica Pier, Third Street Promenade.  \n\n   • Los Angeles (20 mi / 30 min from Santa Monica)  \n     – Welcome to LA!  \n\n2. Faster Inland Route (I-5)  \n   Total driving time: ~6 hrs, 380 miles  \n   Good if you’re pressed for time;  fewer scenic overlooks but easier mileage.  \n\n   Key stops along I-5:  \n   • Gilroy (40 mi / 45 min from SF) – Home of the Garlic Festival; farm stands.  \n   • Kettleman City (160 mi / 2½ hrs from Gilroy) – Bravo Farms for ice cream and picnic.  \n   • Harris Ranch (80 mi / 1 hr from Kettleman) – Large steakhouse, deli and wine shop.  \n   • Grapevine / Tejon Pass (65 mi / 1 hr from Harris) – Decent rest-stop restaurants and views as you descend into Southern California.  \n   • Valencia / Santa Clarita (30 mi / 30 min from Grapevine) – Valencia Town Center for shops.  \n   • Los Angeles (35 mi / 40 min from Valencia)  \n\n—  \nTips:  \n• Plan fuel and rest stops in Big Sur — services are sparse.  \n• Book lodging early if traveling weekends or holidays (Big Sur, SLO, Santa Barbara are popular).  \n• Allow extra time for traffic, especially near Malibu, Santa Barbara, and LA.  \n\nEnjoy your trip! Let me know if you need more detail on any stop or lodging suggestions.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470989,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnXph5iAItZ049bKX3IMVRStv3NL",
  "model": "o4-mini-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 1331,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 320,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 76,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 1407
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'openai/o4-mini',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o4-mini",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
Detective Mara Ellington crouched in the alley’s muted glow, rain dripping from her brimmed hat. The city’s midnight hush was deafening, broken only by distant sirens and the scurry of rats. She’d come to inspect the scene of a daring daylight burglary at the old Currier estate, expecting shattered glass and empty safes. Instead, on the damp cobblestones, she found a single porcelain doll’s head—its cheek chipped, one glass eye staring blankly at the moon. 

Heat prickled her neck. No burglar would leave such a thing behind. She reached for it, careful of the spider-web crack snaking from its temple. The doll’s painted lips were twisted into an unnatural grin, and tucked beneath its chin was a scrap of yellowed paper, edges singed. Mara unfolded it, breath catching as she read the single word scrawled in crimson ink: “Found.”
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Detective Mara Ellington crouched in the alley’s muted glow, rain dripping from her brimmed hat. The city’s midnight hush was deafening, broken only by distant sirens and the scurry of rats. She’d come to inspect the scene of a daring daylight burglary at the old Currier estate, expecting shattered glass and empty safes. Instead, on the damp cobblestones, she found a single porcelain doll’s head—its cheek chipped, one glass eye staring blankly at the moon. \n\nHeat prickled her neck. No burglar would leave such a thing behind. She reached for it, careful of the spider-web crack snaking from its temple. The doll’s painted lips were twisted into an unnatural grin, and tucked beneath its chin was a scrap of yellowed paper, edges singed. Mara unfolded it, breath catching as she read the single word scrawled in crimson ink: “Found.”",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470989,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnXpXvTKSGQ5iGgAj5ky00Ve4KC2",
  "model": "o4-mini-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 269,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 64,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 288
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'openai/o4-mini',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o4-mini",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
Recursion is a technique where a function (or routine) calls itself in order to break a problem down into smaller, more manageable pieces. Every recursive solution has two essential parts:

1. Base Case  
    – A condition under which the function returns a result directly, without making any further recursive calls.  
2. Recursive Case  
    – The part of the function that calls itself with a smaller or simpler input, moving the overall problem toward the base case.

Simple Example: Computing Factorial

The factorial of a non-negative integer n (written n!) is the product of all positive integers up to n.  
  – 0! is defined as 1 (this will be our base case).  
  – For n > 0, n! = n × (n – 1)! 

Here’s how you could write it in Python:

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

How it works for factorial(4):
 1. factorial(4)  
    → 4 * factorial(3)  
 2. factorial(3)  
    → 3 * factorial(2)  
 3. factorial(2)  
    → 2 * factorial(1)  
 4. factorial(1)  
    → 1 * factorial(0)  
 5. factorial(0)  
    → 1   (base case reached)

Then the calls “unwind”:
  – factorial(1) returns 1 × 1 = 1  
  – factorial(2) returns 2 × 1 = 2  
  – factorial(3) returns 3 × 2 = 6  
  – factorial(4) returns 4 × 6 = 24  

Key points to remember:
- Always define a clear base case, or the recursion will never stop.  
- Each recursive call should make progress toward that base case (e.g. decreasing n by 1).  
- Recursion is especially handy for problems that naturally split into similar subproblems (tree traversals, divide-and-conquer algorithms, combinatorial searches, etc.).
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "",
          "refusal": null,
          "role": "assistant"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1776470992,
    "id": "chatcmpl-DVnXsdpE8VJOrtvNaSXE4EEPhwEuq",
    "model": "o4-mini-2025-04-16",
    "obfuscation": "3Y9X9fW8",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Rec"
        },
        "finish_reason": null,
        "index": 0
      }
    ],
    "created": 1776470992,
    "id": "chatcmpl-DVnXsdpE8VJOrtvNaSXE4EEPhwEuq",
    "model": "o4-mini-2025-04-16",
    "obfuscation": "bNp9XsA",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": null
  },
  "... 470 more chunks omitted ...",
  {
    "choices": [],
    "created": 1776470992,
    "id": "chatcmpl-DVnXsdpE8VJOrtvNaSXE4EEPhwEuq",
    "model": "o4-mini-2025-04-16",
    "obfuscation": "EcvXn",
    "object": "chat.completion.chunk",
    "service_tier": "default",
    "system_fingerprint": null,
    "usage": {
      "completion_tokens": 680,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 192,
        "rejected_prediction_tokens": 0
      },
      "prompt_tokens": 16,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
      },
      "total_tokens": 696
    }
  }
]
```

</details>

<details>

<summary>**Web Search** — Letting the model use OpenAI's built-in web search tool to answer with current information</summary>



```ts
const response = await env.AI.run(
  'openai/o4-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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/o4-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"
    }
  ]
}'
```

```
- On June 18, Cloudflare unveiled a new “Cloudflare One Design Partner” designation within its PowerUP Partner Program and introduced an AI-powered toolkit to streamline migrations to its Cloudflare One platform, helping organizations modernize legacy security architectures and accelerate adoption of secure access service edge (SASE) solutions; the initial cohort includes partners such as Arctiq, Consortium, CMT, Presidio, and The Missing Link ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))  

- On June 17, Cloudflare strengthened its AI agent ecosystem by open-sourcing Flue 1.0 Beta—an extensible framework for deploying production-grade AI agents—and expanding its Agents SDK with durable execution primitives, making it easier for developers to build, run, and maintain long-running AI-driven workflows on the edge ([spyingbee.com](https://spyingbee.com/updates/cloudflare/2026-06))  

- Between June 16 and June 22, Cloudflare investigated and resolved a dashboard bug that caused paid invoices to appear as unpaid for customers; the issue, which affected payments made since June 11, was fully remediated by June 22 following identification of the root cause and deployment of a fix ([cloudflarestatus.com](https://www.cloudflarestatus.com/))
```

```json
{
  "id": "resp_0f41967bfc550c15016a399cbfa0ac819b80994a339b9c1547",
  "object": "response",
  "created_at": 1782160575,
  "model": "o4-mini-2025-04-16",
  "output": [
    {
      "id": "rs_0f41967bfc550c15016a399cc07a14819ba4e5122ca57d8119",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0f41967bfc550c15016a399cc2d864819bb451de59ff6791f5",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare news June 2026"
        ],
        "query": "Cloudflare news June 2026"
      }
    },
    {
      "id": "rs_0f41967bfc550c15016a399cc41770819b81de6f54fba4e7d8",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0f41967bfc550c15016a399cc57694819b89c557cbcb3db307",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare June 15 2026 press release Cloudflare Jun 2026",
          "site:cloudflare.com June 2026 Cloudflare news June 15 Jun 21"
        ],
        "query": "Cloudflare June 15 2026 press release Cloudflare Jun 2026"
      }
    },
    {
      "id": "rs_0f41967bfc550c15016a399cc7885c819b9c95fdeffec9914e",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0f41967bfc550c15016a399cc8b4f8819bb841eb34accab156",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Cloudflare outage June 2026 Cloudflare service degraded"
        ],
        "query": "Cloudflare outage June 2026 Cloudflare service degraded"
      }
    },
    {
      "id": "rs_0f41967bfc550c15016a399ccc3b8c819ba4eb3d2bd8ece5f9",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0f41967bfc550c15016a399ccd17a4819bb264ac00b2e3351e",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "search",
        "queries": [
          "Immerse Seattle Cloudflare June 18 2026"
        ],
        "query": "Immerse Seattle Cloudflare June 18 2026"
      }
    },
    {
      "id": "rs_0f41967bfc550c15016a399ccfab90819ba3ec10fb21ec44bb",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0f41967bfc550c15016a399cd1b3c8819b9d9e53b2bce8a04f",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://www.cloudflarestatus.com/"
      }
    },
    {
      "id": "rs_0f41967bfc550c15016a399cd2aeec819b9ff03483519c6a50",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "ws_0f41967bfc550c15016a399cd51788819bb3b37aaed05a1246",
      "type": "web_search_call",
      "status": "completed",
      "action": {
        "type": "open_page",
        "url": "https://spyingbee.com/updates/cloudflare/2026-06"
      }
    },
    {
      "id": "rs_0f41967bfc550c15016a399cd66aa8819ba3f7172a1f2d2d5b",
      "type": "reasoning",
      "content": [],
      "summary": []
    },
    {
      "id": "msg_0f41967bfc550c15016a399cdebf8c819ba14e3d49fcd5ec12",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [
            {
              "type": "url_citation",
              "end_index": 612,
              "start_index": 448,
              "title": "Cloudflare launches new partner initiative to support AI and SASE adoption",
              "url": "https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai"
            },
            {
              "type": "url_citation",
              "end_index": 1009,
              "start_index": 942,
              "title": "Cloudflare: 153 product updates in June 2026 | Spyingbee",
              "url": "https://spyingbee.com/updates/cloudflare/2026-06"
            },
            {
              "type": "url_citation",
              "end_index": 1371,
              "start_index": 1312,
              "title": "Cloudflare Status",
              "url": "https://www.cloudflarestatus.com/"
            }
          ],
          "logprobs": [],
          "text": "- On June 18, Cloudflare unveiled a new “Cloudflare One Design Partner” designation within its PowerUP Partner Program and introduced an AI-powered toolkit to streamline migrations to its Cloudflare One platform, helping organizations modernize legacy security architectures and accelerate adoption of secure access service edge (SASE) solutions; the initial cohort includes partners such as Arctiq, Consortium, CMT, Presidio, and The Missing Link ([itpro.com](https://www.itpro.com/technology/artificial-intelligence/cloudflare-launches-new-partner-initiative-to-support-ai-and-sase-adoption?utm_source=openai))  \n\n- On June 17, Cloudflare strengthened its AI agent ecosystem by open-sourcing Flue 1.0 Beta—an extensible framework for deploying production-grade AI agents—and expanding its Agents SDK with durable execution primitives, making it easier for developers to build, run, and maintain long-running AI-driven workflows on the edge ([spyingbee.com](https://spyingbee.com/updates/cloudflare/2026-06))  \n\n- Between June 16 and June 22, Cloudflare investigated and resolved a dashboard bug that caused paid invoices to appear as unpaid for customers; the issue, which affected payments made since June 11, was fully remediated by June 22 following identification of the root cause and deployment of a fix ([cloudflarestatus.com](https://www.cloudflarestatus.com/))"
        }
      ],
      "role": "assistant"
    }
  ],
  "status": "completed",
  "usage": {
    "input_tokens": 29004,
    "output_tokens": 3661,
    "total_tokens": 32665,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 3200
    }
  },
  "background": false,
  "billing": {
    "payer": "developer"
  },
  "completed_at": 1782160608,
  "error": null,
  "frequency_penalty": 0,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 4096,
  "max_tool_calls": null,
  "moderation": null,
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "prompt_cache_retention": "in_memory",
  "reasoning": {
    "context": "current_turn",
    "effort": "medium",
    "summary": null
  },
  "safety_identifier": null,
  "service_tier": "default",
  "store": false,
  "temperature": 1,
  "text": {
    "format": {
      "type": "text"
    },
    "verbosity": "medium"
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "web_search_preview",
      "search_content_types": [
        "text"
      ],
      "search_context_size": "medium",
      "user_location": {
        "type": "approximate",
        "city": null,
        "country": "US",
        "region": null,
        "timezone": null
      }
    }
  ],
  "top_logprobs": 0,
  "top_p": 1,
  "truncation": "disabled",
  "user": null,
  "metadata": {},
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

Schema variant

ResponsesChat Completions

▶input

`one of`required

instructions

`string`

temperature

`number`minimum: 0maximum: 2

max\_output\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

stream

`boolean`

▶tools\[]

`array`

tool\_choice

▶text{}

`object`

▶reasoning{}

`object`

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`const: response

created\_at

`number`

model

`string`

▶output\[]

`array`

output\_text

`string`

status

`string`enum: in\_progress, completed, failed, incomplete

▶usage{}

`object`

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/o4-mini/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/o4-mini/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/o4-mini/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/o4-mini/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/o4-mini/#page","headline":"o4-mini","description":"OpenAI's fast, lightweight reasoning model optimized for multi-step problem solving at lower cost.","url":"https://developers.cloudflare.com/ai/models/openai/o4-mini/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: OpenAI's text-to-speech model optimized for real-time use with low latency.
title: TTS-1
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# TTS-1

Text-to-Speech • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/tts-1/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/tts-1`

- Third-party
- Zero data retention

OpenAI's text-to-speech model optimized for real-time use with low latency.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://platform.openai.com/docs/guides/text-to-speech) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per character$0.000015</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/tts-1',
  {
    response_format: 'mp3',
    speed: 1,
    text: 'Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.',
    voice: 'alloy',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/tts-1",
  "input": {
    "response_format": "mp3",
    "speed": 1,
    "text": "Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.",
    "voice": "alloy"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__tts-1/simple-speech.mp3"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Different Voice** — Use the Nova voice for a different tone</summary>



```ts
const response = await env.AI.run(
  'openai/tts-1',
  {
    response_format: 'mp3',
    speed: 1,
    text: 'The weather today is sunny with a high of 72 degrees. Perfect for a walk in the park.',
    voice: 'nova',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/tts-1",
  "input": {
    "response_format": "mp3",
    "speed": 1,
    "text": "The weather today is sunny with a high of 72 degrees. Perfect for a walk in the park.",
    "voice": "nova"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__tts-1/different-voice.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Narration** — Slower narration style with the Onyx voice</summary>



```ts
const response = await env.AI.run(
  'openai/tts-1',
  {
    response_format: 'mp3',
    speed: 0.85,
    text: 'In the beginning, the universe was a singularity of infinite density. Then, in a fraction of a second, it expanded into everything we know today.',
    voice: 'onyx',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/tts-1",
  "input": {
    "response_format": "mp3",
    "speed": 0.85,
    "text": "In the beginning, the universe was a singularity of infinite density. Then, in a fraction of a second, it expanded into everything we know today.",
    "voice": "onyx"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__tts-1/narration.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Echo Voice** — Use the Echo voice for a deeper tone</summary>



```ts
const response = await env.AI.run(
  'openai/tts-1',
  {
    response_format: 'mp3',
    speed: 1,
    text: 'Welcome back to the podcast. Today we are going to talk about the future of artificial intelligence and its impact on creative work.',
    voice: 'echo',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/tts-1",
  "input": {
    "response_format": "mp3",
    "speed": 1,
    "text": "Welcome back to the podcast. Today we are going to talk about the future of artificial intelligence and its impact on creative work.",
    "voice": "echo"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__tts-1/echo-voice.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Fast Playback** — Speed up speech for quick listening</summary>



```ts
const response = await env.AI.run(
  'openai/tts-1',
  {
    response_format: 'mp3',
    speed: 1.5,
    text: 'This is a fast-paced summary of the key findings from the quarterly report. Revenue is up fifteen percent, user growth exceeded expectations, and infrastructure costs remain stable.',
    voice: 'shimmer',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/tts-1",
  "input": {
    "response_format": "mp3",
    "speed": 1.5,
    "text": "This is a fast-paced summary of the key findings from the quarterly report. Revenue is up fifteen percent, user growth exceeded expectations, and infrastructure costs remain stable.",
    "voice": "shimmer"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__tts-1/fast-playback.mp3"
  },
  "state": "Completed"
}
```

</details>

## Parameters

text

`string`requiredmaxLength: 4096The text to generate audio for. Maximum length is 4096 characters.

voice

`string`requireddefault: alloyenum: alloy, echo, fable, onyx, nova, shimmerThe voice to use when generating the audio. Defaults to alloy.

response\_format

`string`requireddefault: mp3enum: mp3, opus, wav, aac, flacThe output format for the audio. Supported formats are mp3, opus, wav, aac and flac.

speed

`number`requireddefault: 1minimum: 0.25maximum: 4The speed of the generated audio. Select a value from 0.25 to 4.0. 1.0 is the default.

audio

`string`URL to the generated audio file

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/tts-1/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/tts-1/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/tts-1/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/tts-1/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/tts-1/#page","headline":"TTS-1","description":"OpenAI's text-to-speech model optimized for real-time use with low latency.","url":"https://developers.cloudflare.com/ai/models/openai/tts-1/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: OpenAI's high-definition text-to-speech model producing higher quality audio output.
title: TTS-1 HD
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![OpenAI logo](https://developers.cloudflare.com/_astro/openai.BBwNKzBb.svg)

# TTS-1 HD

Text-to-Speech • OpenAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/openai/tts-1-hd/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`openai/tts-1-hd`

- Third-party
- Zero data retention

OpenAI's high-definition text-to-speech model producing higher quality audio output.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://openai.com/policies/) |
| More information | [link ↗](https://platform.openai.com/docs/guides/text-to-speech) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per character$0.00003</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'openai/tts-1-hd',
  {
    response_format: 'mp3',
    speed: 1,
    text: 'Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.',
    voice: 'alloy',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/tts-1-hd",
  "input": {
    "response_format": "mp3",
    "speed": 1,
    "text": "Hello! Welcome to Cloudflare AI Gateway. Let me show you what we can do.",
    "voice": "alloy"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__tts-1-hd/simple-speech.mp3"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Storytelling** — HD narration with the Fable voice</summary>



```ts
const response = await env.AI.run(
  'openai/tts-1-hd',
  {
    response_format: 'mp3',
    speed: 0.9,
    text: 'Once upon a time, in a kingdom beyond the clouds, there lived a young inventor who dreamed of building machines that could think.',
    voice: 'fable',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/tts-1-hd",
  "input": {
    "response_format": "mp3",
    "speed": 0.9,
    "text": "Once upon a time, in a kingdom beyond the clouds, there lived a young inventor who dreamed of building machines that could think.",
    "voice": "fable"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__tts-1-hd/storytelling.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Podcast Style** — Conversational podcast narration</summary>



```ts
const response = await env.AI.run(
  'openai/tts-1-hd',
  {
    response_format: 'mp3',
    speed: 1,
    text: "So here's the thing about large language models — they're not actually thinking. They're predicting the next token based on patterns in their training data. But the results can be surprisingly coherent.",
    voice: 'echo',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/tts-1-hd",
  "input": {
    "response_format": "mp3",
    "speed": 1,
    "text": "So here'\''s the thing about large language models — they'\''re not actually thinking. They'\''re predicting the next token based on patterns in their training data. But the results can be surprisingly coherent.",
    "voice": "echo"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__tts-1-hd/podcast-style.mp3"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Shimmer Voice** — Bright and expressive voice</summary>



```ts
const response = await env.AI.run(
  'openai/tts-1-hd',
  {
    response_format: 'mp3',
    speed: 1,
    text: 'Breaking news: scientists have discovered a new species of deep-sea fish that produces its own light using bioluminescence.',
    voice: 'shimmer',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/tts-1-hd",
  "input": {
    "response_format": "mp3",
    "speed": 1,
    "text": "Breaking news: scientists have discovered a new species of deep-sea fish that produces its own light using bioluminescence.",
    "voice": "shimmer"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "audio": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/openai__tts-1-hd/shimmer-voice.mp3"
  },
  "state": "Completed"
}
```

</details>

## Parameters

text

`string`requiredmaxLength: 4096The text to generate audio for. Maximum length is 4096 characters.

voice

`string`requireddefault: alloyenum: alloy, echo, fable, onyx, nova, shimmerThe voice to use when generating the audio. Defaults to alloy.

response\_format

`string`requireddefault: mp3enum: mp3, opus, wav, aac, flacThe output format for the audio. Supported formats are mp3, opus, wav, aac and flac.

speed

`number`requireddefault: 1minimum: 0.25maximum: 4The speed of the generated audio. Select a value from 0.25 to 4.0. 1.0 is the default.

audio

`string`URL to the generated audio file

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/openai/tts-1-hd/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/openai/tts-1-hd/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/openai/tts-1-hd/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/openai/tts-1-hd/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/openai/tts-1-hd/#page","headline":"TTS-1 HD","description":"OpenAI's high-definition text-to-speech model producing higher quality audio output.","url":"https://developers.cloudflare.com/ai/models/openai/tts-1-hd/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Pixverse v5.6 is a video generation model supporting text-to-video and image-to-video with audio generation, customizable aspect ratios, and up to 1080p output.
title: Pixverse v5.6
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![PixVerse logo](https://developers.cloudflare.com/_astro/pixverse.DSyGEAYR.svg)

# Pixverse v5.6

Text-to-Video • PixVerse

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/pixverse/v5.6/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`pixverse/v5.6`

- Third-party
- Zero data retention

Pixverse v5.6 is a video generation model supporting text-to-video and image-to-video with audio generation, customizable aspect ratios, and up to 1080p output.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://pixverse.ai/terms) |
| More information | [link ↗](https://pixverse.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.08</li><li>5s @360p$0.175</li><li>5s @360p w/ audio$0.40</li><li>8s @360p$0.35</li><li>8s @360p w/ audio$0.575</li><li>10s @360p$0.385</li><li>10s @360p w/ audio$0.61</li><li>5s @540p$0.175</li><li>5s @540p w/ audio$0.45</li><li>8s @540p$0.35</li><li>8s @540p w/ audio$0.575</li><li>10s @540p$0.385</li><li>10s @540p w/ audio$0.61</li><li>5s @720p$0.225</li><li>5s @720p w/ audio$0.40</li><li>8s @720p$0.45</li><li>8s @720p w/ audio$0.675</li><li>10s @720p$0.495</li><li>10s @720p w/ audio$0.72</li><li>5s @1080p$0.375</li><li>5s @1080p w/ audio$0.75</li><li>8s @1080p$0.75</li><li>8s @1080p w/ audio$0.975</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'pixverse/v5.6',
  {
    prompt: 'A golden retriever running through a field of sunflowers on a sunny day',
    aspect_ratio: '16:9',
    duration: 5,
    generate_audio: true,
    quality: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pixverse/v5.6",
  "input": {
    "prompt": "A golden retriever running through a field of sunflowers on a sunny day",
    "aspect_ratio": "16:9",
    "duration": 5,
    "generate_audio": true,
    "quality": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://media.pixverse.ai/pixverse%2Fmp4%2Fmedia%2Fweb%2Fori%2F83ca9c7f-6387-4a2c-8d92-bb90a3d519e7_seed1453814635.mp4"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Cinematic Scene with Audio** — Dramatic cinematic video with audio generation</summary>



```ts
const response = await env.AI.run(
  'pixverse/v5.6',
  {
    prompt:
      'A dramatic aerial shot flying over misty mountain peaks at sunrise, cinematic lighting with volumetric fog',
    aspect_ratio: '16:9',
    duration: 8,
    generate_audio: true,
    quality: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pixverse/v5.6",
  "input": {
    "prompt": "A dramatic aerial shot flying over misty mountain peaks at sunrise, cinematic lighting with volumetric fog",
    "aspect_ratio": "16:9",
    "duration": 8,
    "generate_audio": true,
    "quality": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://media.pixverse.ai/pixverse%2Fmp4%2Fmedia%2Fweb%2Fori%2F77e1e5bd-4be9-4b7b-961a-36328e90d7e0_seed735995758.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Portrait Video** — Vertical video for social media</summary>



```ts
const response = await env.AI.run(
  'pixverse/v5.6',
  {
    prompt: 'A barista pouring latte art in a cozy coffee shop, close-up with shallow depth of field',
    aspect_ratio: '9:16',
    duration: 5,
    generate_audio: true,
    quality: '540p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pixverse/v5.6",
  "input": {
    "prompt": "A barista pouring latte art in a cozy coffee shop, close-up with shallow depth of field",
    "aspect_ratio": "9:16",
    "duration": 5,
    "generate_audio": true,
    "quality": "540p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://media.pixverse.ai/pixverse%2Fmp4%2Fmedia%2Fweb%2Fori%2Fa95971bd-798d-431e-8c78-8062b839742c_seed1048220235.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**High Quality Video** — High quality 1080p video with custom seed</summary>



```ts
const response = await env.AI.run(
  'pixverse/v5.6',
  {
    prompt: 'Abstract ink drops spreading through water, vivid colors mixing in slow motion',
    aspect_ratio: '1:1',
    duration: 5,
    generate_audio: true,
    negative_prompt: 'blurry, low quality',
    quality: '1080p',
    seed: 12345,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pixverse/v5.6",
  "input": {
    "prompt": "Abstract ink drops spreading through water, vivid colors mixing in slow motion",
    "aspect_ratio": "1:1",
    "duration": 5,
    "generate_audio": true,
    "negative_prompt": "blurry, low quality",
    "quality": "1080p",
    "seed": 12345
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://media.pixverse.ai/pixverse%2Fmp4%2Fmedia%2Fweb%2Fori%2F557c18df-6c50-409c-a5e5-291bb2086d3f_seed12345.mp4"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`requiredmaxLength: 2048Text prompt describing the video to generate

negative\_prompt

`string`maxLength: 2048Negative text prompt

image\_input

`string`Base64-encoded reference image for image-to-video generation (data:image/...;base64,...). The image will be uploaded to Pixverse automatically.

▶duration

`one of`required

aspect\_ratio

`string`requireddefault: 16:9enum: 16:9, 4:3, 1:1, 3:4, 9:16, 2:3, 3:2, 21:9Video aspect ratio

quality

`string`requireddefault: 720penum: 360p, 540p, 720p, 1080pVideo quality

seed

`integer`minimum: 0maximum: 2147483647Random seed for reproducibility

motion\_mode

`string`enum: normal, fastMotion mode (fast only available when duration=5; 1080p does not support fast)

generate\_audio

`boolean`requireddefault: trueWhether to generate audio with the video

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/pixverse/v5.6/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/pixverse/v5.6/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/pixverse/v5.6/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/pixverse/v5.6/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/pixverse/v5.6/#page","headline":"Pixverse v5.6","description":"Pixverse v5.6 is a video generation model supporting text-to-video and image-to-video with audio generation, customizable aspect ratios, and up to 1080p output.","url":"https://developers.cloudflare.com/ai/models/pixverse/v5.6/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Pixverse v6 is the latest Pixverse video model with support for up to 15-second videos, customizable duration from 1 to 15 seconds, and audio generation.
title: Pixverse v6
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![PixVerse logo](https://developers.cloudflare.com/_astro/pixverse.DSyGEAYR.svg)

# Pixverse v6

Text-to-Video • PixVerse

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/pixverse/v6/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`pixverse/v6`

- Third-party
- Zero data retention

Pixverse v6 is the latest Pixverse video model with support for up to 15-second videos, customizable duration from 1 to 15 seconds, and audio generation.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://pixverse.ai/terms) |
| More information | [link ↗](https://pixverse.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.06</li><li>@360p (per second)$0.025</li><li>@540p (per second)$0.035</li><li>@720p (per second)$0.045</li><li>@1080p (per second)$0.09</li><li>@360p w/ audio (per second)$0.035</li><li>@540p w/ audio (per second)$0.045</li><li>@720p w/ audio (per second)$0.06</li><li>@1080p w/ audio (per second)$0.115</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'pixverse/v6',
  {
    prompt: 'A golden retriever running through a field of sunflowers on a sunny day',
    aspect_ratio: '16:9',
    duration: 5,
    generate_audio: true,
    quality: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pixverse/v6",
  "input": {
    "prompt": "A golden retriever running through a field of sunflowers on a sunny day",
    "aspect_ratio": "16:9",
    "duration": 5,
    "generate_audio": true,
    "quality": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://media.pixverse.ai/pixverse%2Fmp4%2Fmedia%2Fweb%2Fori%2Fda2a0d44-a700-4c6b-a36b-fff6951fd1d4_seed1150795460.mp4"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Long Duration Video** — Extended 15-second video with audio (v6 supports 1-15 seconds)</summary>



```ts
const response = await env.AI.run(
  'pixverse/v6',
  {
    prompt:
      'A time-lapse of a bustling city street from dawn to dusk, showing the flow of people and vehicles',
    aspect_ratio: '16:9',
    duration: 15,
    generate_audio: true,
    quality: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pixverse/v6",
  "input": {
    "prompt": "A time-lapse of a bustling city street from dawn to dusk, showing the flow of people and vehicles",
    "aspect_ratio": "16:9",
    "duration": 15,
    "generate_audio": true,
    "quality": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://media.pixverse.ai/pixverse%2Fmp4%2Fmedia%2Fweb%2Fori%2F46e3adfb-a95f-4c03-bdad-a6d7131a98b8_seed61570270.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Ultra-wide Cinematic** — Cinematic 21:9 aspect ratio video</summary>



```ts
const response = await env.AI.run(
  'pixverse/v6',
  {
    prompt:
      'A dramatic aerial shot flying over misty mountain peaks at sunrise, cinematic lighting with volumetric fog',
    aspect_ratio: '21:9',
    duration: 10,
    generate_audio: true,
    quality: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pixverse/v6",
  "input": {
    "prompt": "A dramatic aerial shot flying over misty mountain peaks at sunrise, cinematic lighting with volumetric fog",
    "aspect_ratio": "21:9",
    "duration": 10,
    "generate_audio": true,
    "quality": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://media.pixverse.ai/pixverse%2Fmp4%2Fmedia%2Fweb%2Fori%2F54327d38-e03a-44de-9a21-2052356779e5_seed286185598.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Silent Video** — Video without audio generation</summary>



```ts
const response = await env.AI.run(
  'pixverse/v6',
  {
    prompt: 'Abstract ink drops spreading through water, vivid colors mixing in slow motion',
    aspect_ratio: '1:1',
    duration: 3,
    generate_audio: false,
    negative_prompt: 'blurry, low quality',
    quality: '540p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pixverse/v6",
  "input": {
    "prompt": "Abstract ink drops spreading through water, vivid colors mixing in slow motion",
    "aspect_ratio": "1:1",
    "duration": 3,
    "generate_audio": false,
    "negative_prompt": "blurry, low quality",
    "quality": "540p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://media.pixverse.ai/pixverse%2Fmp4%2Fmedia%2Fweb%2Fori%2F06c27c41-cadd-44c5-b418-a78b96555479_seed1048443720.mp4"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`requiredmaxLength: 2048Text prompt describing the video to generate

negative\_prompt

`string`maxLength: 2048Negative text prompt

image\_input

`string`Base64-encoded reference image for image-to-video generation (data:image/...;base64,...). The image will be uploaded to Pixverse automatically.

duration

`integer`requireddefault: 5minimum: 1maximum: 15Video duration in seconds (1 to 15)

aspect\_ratio

`string`requireddefault: 16:9enum: 16:9, 4:3, 1:1, 3:4, 9:16, 2:3, 3:2, 21:9Video aspect ratio

quality

`string`requireddefault: 720penum: 360p, 540p, 720p, 1080pVideo quality

seed

`integer`minimum: 0maximum: 2147483647Random seed for reproducibility

generate\_audio

`boolean`requireddefault: trueWhether to generate audio with the video

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/pixverse/v6/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/pixverse/v6/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/pixverse/v6/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/pixverse/v6/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/pixverse/v6/#page","headline":"Pixverse v6","description":"Pixverse v6 is the latest Pixverse video model with support for up to 15-second videos, customizable duration from 1 to 15 seconds, and audio generation.","url":"https://developers.cloudflare.com/ai/models/pixverse/v6/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Pruna's P-Image is an ultra-fast text-to-image model with automatic prompt enhancement and 2-stage refinement, combining exceptional speed with high-quality output and flexible aspect ratios.
title: P-Image
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)

# P-Image

Text-to-Image • Pruna AI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/pruna/p-image/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`pruna/p-image`

- Third-party

Pruna's P-Image is an ultra-fast text-to-image model with automatic prompt enhancement and 2-stage refinement, combining exceptional speed with high-quality output and flexible aspect ratios.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://docs.api.pruna.ai/guides/quickstart) |
| Pricing | <ul><li>Per image$0.005</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'pruna/p-image',
  {
    prompt: 'A majestic lion standing on a rocky cliff at sunset, photorealistic, 4k',
    aspect_ratio: '16:9',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pruna/p-image",
  "input": {
    "prompt": "A majestic lion standing on a rocky cliff at sunset, photorealistic, 4k",
    "aspect_ratio": "16:9"
  }
}'
```

![Lion at Sunset](https://examples.aig.cloudflare.com/pruna/p-image/lion-at-sunset.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/pruna/p-image/lion-at-sunset.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Reading Nook** — Square-format generation with prompt upsampling.</summary>



```ts
const response = await env.AI.run(
  'pruna/p-image',
  {
    prompt: 'A cozy reading nook by a rainy window, warm lighting, detailed illustration',
    aspect_ratio: '1:1',
    prompt_upsampling: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pruna/p-image",
  "input": {
    "prompt": "A cozy reading nook by a rainy window, warm lighting, detailed illustration",
    "aspect_ratio": "1:1",
    "prompt_upsampling": true
  }
}'
```

![Reading Nook](https://examples.aig.cloudflare.com/pruna/p-image/reading-nook.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/pruna/p-image/reading-nook.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredText description of the image to generate. The model automatically enhances prompts for better results.

aspect\_ratio

`string`requireddefault: 16:9enum: 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, customAspect ratio for the image. Use "custom" with width/height for exact dimensions.

width

`integer`minimum: 256maximum: 1440multipleOf: 16Custom width in pixels (256-1440, multiple of 16). Only used when aspect\_ratio="custom".

height

`integer`minimum: 256maximum: 1440multipleOf: 16Custom height in pixels (256-1440, multiple of 16). Only used when aspect\_ratio="custom".

lora\_weights

`string`Load LoRA weights. Supports HuggingFace URLs in the format huggingface.co/\<owner>/\<model-name>\[/\<file.safetensors>].

lora\_scale

`number`requireddefault: 0.5minimum: -1maximum: 3How strongly the LoRA should be applied (-1 to 3).

hf\_api\_token

`string`HuggingFace API token for accessing private LoRAs. This credential is forwarded verbatim to Pruna. It is only written to gateway request-body logs when the gateway-level collectLogPayload debug flag is explicitly enabled — it never appears in structured analytics logs.

prompt\_upsampling

`boolean`requireddefault: falseUpsample the prompt with an LLM for enhanced results.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Random seed for reproducible generation.

disable\_safety\_checker

`boolean`requireddefault: falseDisable safety checker for generated images.

image

`string`format: uriPresigned URL for the generated image.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/pruna/p-image/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-image/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/pruna/p-image/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-image/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/pruna/p-image/#page","headline":"P-Image","description":"Pruna's P-Image is an ultra-fast text-to-image model with automatic prompt enhancement and 2-stage refinement, combining exceptional speed with high-quality output and flexible aspect ratios.","url":"https://developers.cloudflare.com/ai/models/pruna/p-image/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Pruna's P-Image-Edit edits and composes 1-5 reference images with text instructions. It supports complex compositions, style transfers, and targeted edits with flexible output aspect ratios.
title: P-Image-Edit
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)

# P-Image-Edit

Image-to-Image • Pruna AI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/pruna/p-image-edit/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`pruna/p-image-edit`

- Third-party

Pruna's P-Image-Edit edits and composes 1-5 reference images with text instructions. It supports complex compositions, style transfers, and targeted edits with flexible output aspect ratios.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://docs.api.pruna.ai/guides/quickstart) |
| Pricing | <ul><li>Per image$0.01</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'pruna/p-image-edit',
  {
    prompt: 'Transform the subject into a watercolor painting style with vibrant colors',
    images: ['https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg'],
    aspect_ratio: '1:1',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pruna/p-image-edit",
  "input": {
    "prompt": "Transform the subject into a watercolor painting style with vibrant colors",
    "images": [
      "https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg"
    ],
    "aspect_ratio": "1:1"
  }
}'
```

![Watercolor Style](https://examples.aig.cloudflare.com/pruna/p-image-edit/watercolor-style.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/pruna/p-image-edit/watercolor-style.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

prompt

`string`requiredText instruction describing the desired edit or composition.

▶images\[]

`array`requiredminItems: 1maxItems: 5Array of 1-5 reference images. Each entry is an HTTP(S) URL or a base64 data URI (data:image/...;base64,...).

turbo

`boolean`requireddefault: trueRun faster with additional optimizations. For complicated tasks, it is recommended to turn this off.

aspect\_ratio

`string`requireddefault: match\_input\_imageenum: match\_input\_image, 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3Output aspect ratio.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Random seed for reproducible generation.

disable\_safety\_checker

`boolean`requireddefault: falseDisable safety checker for generated images.

image

`string`format: uriPresigned URL for the edited image.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/pruna/p-image-edit/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-image-edit/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/pruna/p-image-edit/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-image-edit/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/pruna/p-image-edit/#page","headline":"P-Image-Edit","description":"Pruna's P-Image-Edit edits and composes 1-5 reference images with text instructions. It supports complex compositions, style transfers, and targeted edits with flexible output aspect ratios.","url":"https://developers.cloudflare.com/ai/models/pruna/p-image-edit/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Pruna's P-Image Try-On virtually fits one or more garments onto a person's photo. Provide a photo of a person plus garment reference images and the model realistically dresses the person in the provided garments.
title: P-Image Try-On
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)

# P-Image Try-On

Image-to-Image • Pruna AI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/pruna/p-image-try-on/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`pruna/p-image-try-on`

- Third-party

Pruna's P-Image Try-On virtually fits one or more garments onto a person's photo. Provide a photo of a person plus garment reference images and the model realistically dresses the person in the provided garments.

Tip

**70% off P-Image-Try-On:** Save 70% on all inference with P-Image-Try-On until Sunday, 21 June at 11:59 PM CEST

| Model Info | |
| --- | --- |
| More information | [link ↗](https://docs.api.pruna.ai/guides/quickstart) |
| Pricing | <ul><li>Per image$0.015</li><li>Per input image$0.008</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'pruna/p-image-try-on',
  {
    person_image:
      'https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg',
    garment_images: [
      'https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/cloth/04469_00.jpg',
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pruna/p-image-try-on",
  "input": {
    "person_image": "https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg",
    "garment_images": [
      "https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/cloth/04469_00.jpg"
    ]
  }
}'
```

![Single Garment](https://examples.aig.cloudflare.com/pruna/p-image-try-on/single-garment.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/pruna/p-image-try-on/single-garment.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Turbo PNG** — Faster generation with turbo optimizations, returning a PNG.</summary>



```ts
const response = await env.AI.run(
  'pruna/p-image-try-on',
  {
    person_image:
      'https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg',
    garment_images: [
      'https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/cloth/09163_00.jpg',
    ],
    turbo: true,
    output_format: 'png',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pruna/p-image-try-on",
  "input": {
    "person_image": "https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg",
    "garment_images": [
      "https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/cloth/09163_00.jpg"
    ],
    "turbo": true,
    "output_format": "png"
  }
}'
```

![Turbo PNG](https://examples.aig.cloudflare.com/pruna/p-image-try-on/turbo-png.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/pruna/p-image-try-on/turbo-png.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

person\_image

`string`requiredImage of the person to dress. A publicly reachable HTTP(S) URL or a base64 data URI (data:image/...;base64,...).

▶garment\_images\[]

`array`requiredminItems: 1maxItems: 11Garment reference images to fit onto the person. Each entry is an HTTP(S) URL or a base64 data URI. Up to 6 recommended, up to 11 supported.

prompt

`string`requireddefault: Experimental guidance for non-flatlay garment images, e.g. which garment from which image to use.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Random seed. Leave unset for a random seed.

turbo

`boolean`requireddefault: falseRun faster with additional optimizations. Not recommended for more than 4 garments.

output\_format

`string`requireddefault: jpgenum: webp, jpg, pngFormat of the saved output image.

output\_quality

`integer`requireddefault: 95minimum: 0maximum: 100Quality for jpg/webp outputs, from 0 to 100.

reference\_pose

`string`Optional reference pose image (HTTP(S) URL or data URI). When provided, the person is reposed to match this reference before virtual try-on.

preserve\_input\_size

`boolean`requireddefault: trueReturn the output at the original input resolution.

image

`string`format: uriPresigned URL for the generated try-on image.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/pruna/p-image-try-on/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-image-try-on/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/pruna/p-image-try-on/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-image-try-on/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/pruna/p-image-try-on/#page","headline":"P-Image Try-On","description":"Pruna's P-Image Try-On virtually fits one or more garments onto a person's photo. Provide a photo of a person plus garment reference images and the model realistically dresses the person in the provided garments.","url":"https://developers.cloudflare.com/ai/models/pruna/p-image-try-on/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Pruna's P-Image-Upscale increases image resolution using AI, targeting 1-128 megapixels with optional detail and realism enhancement for sharper, cleaner results.
title: P-Image-Upscale
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)

# P-Image-Upscale

Image-to-Image • Pruna AI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/pruna/p-image-upscale/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`pruna/p-image-upscale`

- Third-party

Pruna's P-Image-Upscale increases image resolution using AI, targeting 1-128 megapixels with optional detail and realism enhancement for sharper, cleaner results.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://docs.api.pruna.ai/guides/quickstart) |
| Pricing | <ul><li>Per image (1-4 MP)$0.005</li><li>Per image (5-8 MP)$0.01</li><li>Per image (9-16 MP)$0.02</li><li>Per image (17-32 MP)$0.04</li><li>Per image (33-64 MP)$0.06</li><li>Per image (65-128 MP)$0.12</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'pruna/p-image-upscale',
  {
    image: 'https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg',
    target: 4,
    enhance_details: true,
    output_format: 'jpg',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pruna/p-image-upscale",
  "input": {
    "image": "https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg",
    "target": 4,
    "enhance_details": true,
    "output_format": "jpg"
  }
}'
```

![4MP Upscale](https://examples.aig.cloudflare.com/pruna/p-image-upscale/4mp-upscale.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/pruna/p-image-upscale/4mp-upscale.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

image

`string`requiredInput image to upscale. A publicly reachable HTTP(S) URL or a base64 data URI (data:image/...;base64,...).

target

`integer`requireddefault: 4minimum: 1maximum: 128Target resolution in megapixels (1-128). Output is capped at 128 MP.

output\_format

`string`requireddefault: jpgenum: webp, jpg, pngFormat of the output image.

output\_quality

`integer`requireddefault: 80minimum: 0maximum: 100Quality when saving the output image (0-100). Not relevant for .png outputs.

enhance\_details

`boolean`requireddefault: falseEnhance fine textures and small details.

enhance\_realism

`boolean`requireddefault: falseImprove realism. Recommended for AI-generated images.

disable\_safety\_checker

`boolean`requireddefault: falseDisable safety checker for generated images.

image

`string`format: uriPresigned URL for the upscaled image.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/pruna/p-image-upscale/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-image-upscale/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/pruna/p-image-upscale/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-image-upscale/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/pruna/p-image-upscale/#page","headline":"P-Image-Upscale","description":"Pruna's P-Image-Upscale increases image resolution using AI, targeting 1-128 megapixels with optional detail and realism enhancement for sharper, cleaner results.","url":"https://developers.cloudflare.com/ai/models/pruna/p-image-upscale/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Pruna's P-Video is a premium video generation model supporting text-to-video, image-to-video, and audio-conditioned generation up to 1080p at 24 or 48 fps, with configurable duration up to 20 seconds.
title: P-Video
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)

# P-Video

Text-to-Video • Pruna AI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/pruna/p-video/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`pruna/p-video`

- Third-party

Pruna's P-Video is a premium video generation model supporting text-to-video, image-to-video, and audio-conditioned generation up to 1080p at 24 or 48 fps, with configurable duration up to 20 seconds.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://docs.api.pruna.ai/guides/quickstart) |
| Pricing | <ul><li>Default (per second)$0.02</li><li>@720p (per second)$0.02</li><li>@1080p (per second)$0.04</li><li>@720p draft (per second)$0.005</li><li>@1080p draft (per second)$0.01</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'pruna/p-video',
  {
    prompt: 'A sports car drifting through a neon-lit city at night, cinematic aerial shot',
    duration: 5,
    resolution: '720p',
    aspect_ratio: '16:9',
    draft: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pruna/p-video",
  "input": {
    "prompt": "A sports car drifting through a neon-lit city at night, cinematic aerial shot",
    "duration": 5,
    "resolution": "720p",
    "aspect_ratio": "16:9",
    "draft": true
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/pruna/p-video/neon-city-drift.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

prompt

`string`requiredText prompt for video generation.

image

`string`Input image to generate video from (image-to-video). HTTP(S) URL or data URI. Supports jpg, jpeg, png, webp. When provided, aspect\_ratio is ignored.

audio

`string`Input audio to condition video generation. HTTP(S) URL or data URI. Supports flac, mp3, wav. When provided, duration is ignored.

duration

`integer`requireddefault: 5minimum: 1maximum: 20Duration of the video in seconds (1-20). Ignored when audio is provided.

resolution

`string`requireddefault: 720penum: 720p, 1080pVideo resolution.

▶fps

`one of`required

aspect\_ratio

`string`requireddefault: 16:9enum: 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 1:1Aspect ratio of the video. Ignored when an input image is provided.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Random seed for reproducible generation.

draft

`boolean`requireddefault: falseDraft mode. Generates a lower-quality preview of the video.

save\_audio

`boolean`requireddefault: trueSave the video with audio.

last\_frame\_image

`string`Reference image for the last frame of the video. HTTP(S) URL or data URI.

prompt\_upsampling

`boolean`requireddefault: trueUse prompt upsampling to enhance the prompt.

disable\_safety\_filter

`boolean`requireddefault: trueDisable safety filter for prompts and input images.

video

`string`format: uriPresigned URL for the generated video.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/pruna/p-video/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-video/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/pruna/p-video/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-video/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/pruna/p-video/#page","headline":"P-Video","description":"Pruna's P-Video is a premium video generation model supporting text-to-video, image-to-video, and audio-conditioned generation up to 1080p at 24 or 48 fps, with configurable duration up to 20 seconds.","url":"https://developers.cloudflare.com/ai/models/pruna/p-video/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Pruna's P-Video-Animate takes a source video and a subject reference image, then animates the referenced subject using the motion and audio from the source video.
title: P-Video-Animate
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)

# P-Video-Animate

Image-to-Video • Pruna AI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/pruna/p-video-animate/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`pruna/p-video-animate`

- Third-party

Pruna's P-Video-Animate takes a source video and a subject reference image, then animates the referenced subject using the motion and audio from the source video.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://docs.api.pruna.ai/guides/quickstart) |
| Pricing | <ul><li>Default (per second)$0.03</li><li>@720p (per second)$0.03</li><li>@1080p (per second)$0.06</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'pruna/p-video-animate',
  {
    video: 'https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4',
    image: 'https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg',
    resolution: '720p',
    target_fps: 'original',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pruna/p-video-animate",
  "input": {
    "video": "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4",
    "image": "https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg",
    "resolution": "720p",
    "target_fps": "original"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/pruna/p-video-animate/motion-transfer.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

video

`string`requiredSource RGB video (.mp4) used as the motion and audio source. HTTP(S) URL or data URI.

image

`string`requiredReference image of the subject to animate. HTTP(S) URL or data URI.

turbo

`boolean`requireddefault: falseTurbo mode: faster generation for slightly lower quality.

resolution

`string`requireddefault: 720penum: 720p, 1080pTarget resolution.

save\_audio

`boolean`requireddefault: trueSave the video with audio.

ignore\_audio

`boolean`requireddefault: falseIgnore source audio during generation.

target\_fps

`string`requireddefault: originalenum: 24, 48, originalTarget FPS for the working video.

instruction\_prompt

`string`requireddefault: Further instruction on how the reference subject should be animated.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Random seed for reproducible generation.

disable\_safety\_checker

`boolean`requireddefault: falseDisable safety checker for generated videos.

video

`string`format: uriPresigned URL for the animated video.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/pruna/p-video-animate/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-video-animate/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/pruna/p-video-animate/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-video-animate/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/pruna/p-video-animate/#page","headline":"P-Video-Animate","description":"Pruna's P-Video-Animate takes a source video and a subject reference image, then animates the referenced subject using the motion and audio from the source video.","url":"https://developers.cloudflare.com/ai/models/pruna/p-video-animate/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Pruna's P-Video-Avatar generates talking-head videos from a single portrait image driven by a text script or audio file, with multiple voices, languages, and output resolutions.
title: P-Video-Avatar
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)

# P-Video-Avatar

Image-to-Video • Pruna AI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/pruna/p-video-avatar/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`pruna/p-video-avatar`

- Third-party

Pruna's P-Video-Avatar generates talking-head videos from a single portrait image driven by a text script or audio file, with multiple voices, languages, and output resolutions.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://docs.api.pruna.ai/guides/quickstart) |
| Pricing | <ul><li>Default (per second)$0.025</li><li>@720p (per second)$0.025</li><li>@1080p (per second)$0.045</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'pruna/p-video-avatar',
  {
    image: 'https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg',
    voice_script: 'Hello, welcome to our product demo!',
    voice: 'Zephyr (Female)',
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pruna/p-video-avatar",
  "input": {
    "image": "https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg",
    "voice_script": "Hello, welcome to our product demo!",
    "voice": "Zephyr (Female)",
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/pruna/p-video-avatar/product-demo-greeting.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

image

`string`requiredInput portrait image (first frame). HTTP(S) URL or data URI. Supports jpg, jpeg, png, webp.

audio

`string`URL of uploaded audio to drive speech. HTTP(S) URL or data URI. If both audio and voice\_script are provided, audio takes priority.

voice

`string`requireddefault: Zephyr (Female)enum: Zephyr (Female), Puck (Male), Charon (Male), Kore (Female), Fenrir (Male), Leda (Female), Orus (Male), Aoede (Female), Callirrhoe (Female), Autonoe (Female), Enceladus (Male), Iapetus (Male), Umbriel (Male), Algenib (Male), Despina (Female), Erinome (Female), Laomedeia (Female), Achernar (Female), Algieba (Male), Schedar (Male), Gacrux (Female), Pulcherrima (Female), Achird (Male), Zubenelgenubi (Male), Vindemiatrix (Female), Sadachbia (Male), Sadaltager (Male), Sulafat (Female), Alnilam (Male), Rasalgethi (Male)Voice for generated speech.

voice\_script

`string`requireddefault: Script for the person to say when no audio is uploaded.

voice\_language

`string`requireddefault: English (US)enum: English (US), English (UK), Spanish, French, German, Italian, Portuguese (Brazil), Japanese, Korean, HindiOutput language.

resolution

`string`requireddefault: 720penum: 720p, 1080pResolution of the video.

video\_prompt

`string`requireddefault: The person is talking.Optional prompt for the video.

voice\_prompt

`string`requireddefault: Say the following.Optional speaking style, tone, pacing or emotion instructions.

negative\_prompt

`string`requireddefault: Mention what you do NOT want in the video. Disabled if empty.

strength\_negative\_prompt

`number`requireddefault: 0.5minimum: 0maximum: 4Strength of the negative prompt (0-4).

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Random seed for reproducible generation.

disable\_safety\_filter

`boolean`requireddefault: trueDisable safety filter for prompts and input image.

disable\_prompt\_upsampling

`boolean`requireddefault: falseWhen true, skip the prompt upsampler and pass the raw user prompt.

video

`string`format: uriPresigned URL for the generated avatar video.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/pruna/p-video-avatar/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-video-avatar/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/pruna/p-video-avatar/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-video-avatar/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/pruna/p-video-avatar/#page","headline":"P-Video-Avatar","description":"Pruna's P-Video-Avatar generates talking-head videos from a single portrait image driven by a text script or audio file, with multiple voices, languages, and output resolutions.","url":"https://developers.cloudflare.com/ai/models/pruna/p-video-avatar/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Pruna's P-Video-Replace takes a source video and one or more identity reference images, then places the referenced person or people into the video while preserving the source motion and audio.
title: P-Video-Replace
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Pruna AI logo](https://developers.cloudflare.com/_astro/prunaai.Bv7D31UF.svg)

# P-Video-Replace

Image-to-Video • Pruna AI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/pruna/p-video-replace/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`pruna/p-video-replace`

- Third-party

Pruna's P-Video-Replace takes a source video and one or more identity reference images, then places the referenced person or people into the video while preserving the source motion and audio.

| Model Info | |
| --- | --- |
| More information | [link ↗](https://docs.api.pruna.ai/guides/quickstart) |
| Pricing | <ul><li>Default (per second)$0.03</li><li>@720p (per second)$0.03</li><li>@1080p (per second)$0.06</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'pruna/p-video-replace',
  {
    video: 'https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4',
    images: ['https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg'],
    resolution: '720p',
    target_fps: 'original',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "pruna/p-video-replace",
  "input": {
    "video": "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4",
    "images": [
      "https://huggingface.co/spaces/yisol/IDM-VTON/resolve/main/example/human/00121_00.jpg"
    ],
    "resolution": "720p",
    "target_fps": "original"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/pruna/p-video-replace/character-swap.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

video

`string`requiredSource RGB video (.mp4) used as the motion and audio source. HTTP(S) URL or data URI.

▶images\[]

`array`requiredminItems: 1maxItems: 3Identity reference image(s), 1 to 3, to place into the video. Each entry is an HTTP(S) URL or a data URI.

turbo

`boolean`requireddefault: falseTurbo mode: faster generation for slightly lower quality.

resolution

`string`requireddefault: 720penum: 720p, 1080pTarget resolution.

save\_audio

`boolean`requireddefault: trueSave the video with audio.

ignore\_audio

`boolean`requireddefault: falseIgnore source audio during generation.

target\_fps

`string`requireddefault: originalenum: 24, 48, originalTarget FPS for the working video.

instruction\_prompt

`string`requireddefault: Further instruction on how to place people from the reference images into the scene.

seed

`integer`minimum: -9007199254740991maximum: 9007199254740991Random seed for reproducible generation.

disable\_safety\_checker

`boolean`requireddefault: falseDisable safety checker for generated videos.

video

`string`format: uriPresigned URL for the replacement video.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/pruna/p-video-replace/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-video-replace/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/pruna/p-video-replace/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/pruna/p-video-replace/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/pruna/p-video-replace/#page","headline":"P-Video-Replace","description":"Pruna's P-Video-Replace takes a source video and one or more identity reference images, then places the referenced person or people into the video while preserving the source motion and audio.","url":"https://developers.cloudflare.com/ai/models/pruna/p-video-replace/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Recraft V3 is the previous-generation text-to-image model from Recraft, well-suited to design-quality compositions, brand-aware imagery, and accurate text rendering.
title: Recraft V3
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V3

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv3/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv3`

- Third-party
- Zero data retention

Recraft V3 is the previous-generation text-to-image model from Recraft, well-suited to design-quality compositions, brand-aware imagery, and accurate text rendering.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.04</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv3',
  { prompt: 'A minimalist logo of a mountain range with a sun rising behind it' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv3",
  "input": {
    "prompt": "A minimalist logo of a mountain range with a sun rising behind it"
  }
}'
```

![Simple Generation](https://examples.aig.cloudflare.com/recraft/recraftv3/simple-generation.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv3/simple-generation.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Scene Composition** — Generate a complex compositional scene</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv3',
  {
    prompt: 'A cozy cabin in the woods surrounded by tall pine trees, smoke rising from the chimney',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv3",
  "input": {
    "prompt": "A cozy cabin in the woods surrounded by tall pine trees, smoke rising from the chimney"
  }
}'
```

![Scene Composition](https://examples.aig.cloudflare.com/recraft/recraftv3/scene-composition.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv3/scene-composition.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Custom Size** — Specify output dimensions</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv3',
  {
    prompt: 'A flat illustration of a workspace with a laptop, coffee cup, and potted plant',
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv3",
  "input": {
    "prompt": "A flat illustration of a workspace with a laptop, coffee cup, and potted plant",
    "size": "1024x1024"
  }
}'
```

![Custom Size](https://examples.aig.cloudflare.com/recraft/recraftv3/custom-size.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv3/custom-size.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**With Color Controls** — Guide generation with specific brand colors</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv3',
  {
    prompt: 'An abstract geometric pattern suitable for a tech company brand identity',
    controls: { colors: [{ rgb: [255, 107, 53] }, { rgb: [0, 43, 91] }] },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv3",
  "input": {
    "prompt": "An abstract geometric pattern suitable for a tech company brand identity",
    "controls": {
      "colors": [
        {
          "rgb": [
            255,
            107,
            53
          ]
        },
        {
          "rgb": [
            0,
            43,
            91
          ]
        }
      ]
    }
  }
}'
```

![With Color Controls](https://examples.aig.cloudflare.com/recraft/recraftv3/with-color-controls.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv3/with-color-controls.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Background Color** — Set a specific background color</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv3',
  {
    prompt: 'A clean icon of a lightning bolt',
    controls: { background_color: { rgb: [245, 245, 245] } },
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv3",
  "input": {
    "prompt": "A clean icon of a lightning bolt",
    "controls": {
      "background_color": {
        "rgb": [
          245,
          245,
          245
        ]
      }
    },
    "size": "1024x1024"
  }
}'
```

![Background Color](https://examples.aig.cloudflare.com/recraft/recraftv3/background-color.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv3/background-color.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv3/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv3/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv3/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv3/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv3/#page","headline":"Recraft V3","description":"Recraft V3 is the previous-generation text-to-image model from Recraft, well-suited to design-quality compositions, brand-aware imagery, and accurate text rendering.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv3/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Recraft V4 generates art-directed images with strong composition, accurate text rendering, and design taste built in. Fast and cost-efficient at standard resolution.
title: Recraft V4
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4`

- Third-party
- Zero data retention

Recraft V4 generates art-directed images with strong composition, accurate text rendering, and design taste built in. Fast and cost-efficient at standard resolution.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.04</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4',
  { prompt: 'A minimalist logo of a mountain range with a sun rising behind it' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4",
  "input": {
    "prompt": "A minimalist logo of a mountain range with a sun rising behind it"
  }
}'
```

![Simple Generation](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4/simple-generation.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4/simple-generation.png"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Scene Composition** — Generate a complex compositional scene</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4',
  {
    prompt: 'A cozy cabin in the woods surrounded by tall pine trees, smoke rising from the chimney',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4",
  "input": {
    "prompt": "A cozy cabin in the woods surrounded by tall pine trees, smoke rising from the chimney"
  }
}'
```

![Scene Composition](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4/scene-composition.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4/scene-composition.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Custom Size** — Specify output dimensions</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4',
  {
    prompt: 'A flat illustration of a workspace with a laptop, coffee cup, and potted plant',
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4",
  "input": {
    "prompt": "A flat illustration of a workspace with a laptop, coffee cup, and potted plant",
    "size": "1024x1024"
  }
}'
```

![Custom Size](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4/custom-size.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4/custom-size.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**With Color Controls** — Guide generation with specific brand colors</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4',
  {
    prompt: 'An abstract geometric pattern suitable for a tech company brand identity',
    controls: { colors: [{ rgb: [255, 107, 53] }, { rgb: [0, 43, 91] }] },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4",
  "input": {
    "prompt": "An abstract geometric pattern suitable for a tech company brand identity",
    "controls": {
      "colors": [
        {
          "rgb": [
            255,
            107,
            53
          ]
        },
        {
          "rgb": [
            0,
            43,
            91
          ]
        }
      ]
    }
  }
}'
```

![With Color Controls](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4/with-color-controls.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4/with-color-controls.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Background Color** — Set a specific background color</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4',
  {
    prompt: 'A clean icon of a lightning bolt',
    controls: { background_color: { rgb: [245, 245, 245] } },
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4",
  "input": {
    "prompt": "A clean icon of a lightning bolt",
    "controls": {
      "background_color": {
        "rgb": [
          245,
          245,
          245
        ]
      }
    },
    "size": "1024x1024"
  }
}'
```

![Background Color](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4/background-color.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4/background-color.png"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4/#page","headline":"Recraft V4","description":"Recraft V4 generates art-directed images with strong composition, accurate text rendering, and design taste built in. Fast and cost-efficient at standard resolution.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Recraft V4.1 generates art-directed images tuned for high aesthetics, with strong composition, accurate text rendering, and refined design taste. Fast and cost-efficient at standard resolution.
title: Recraft V4.1
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4.1

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4-1`

- Third-party
- Zero data retention

Recraft V4.1 generates art-directed images tuned for high aesthetics, with strong composition, accurate text rendering, and refined design taste. Fast and cost-efficient at standard resolution.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.04</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4-1',
  { prompt: 'A minimalist logo of a mountain range with a sun rising behind it' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1",
  "input": {
    "prompt": "A minimalist logo of a mountain range with a sun rising behind it"
  }
}'
```

![Simple Generation](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1/simple-generation.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1/simple-generation.png"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Scene Composition** — Generate a complex compositional scene</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1',
  {
    prompt: 'A cozy cabin in the woods surrounded by tall pine trees, smoke rising from the chimney',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1",
  "input": {
    "prompt": "A cozy cabin in the woods surrounded by tall pine trees, smoke rising from the chimney"
  }
}'
```

![Scene Composition](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1/scene-composition.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1/scene-composition.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Custom Size** — Specify output dimensions</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1',
  {
    prompt: 'A flat illustration of a workspace with a laptop, coffee cup, and potted plant',
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1",
  "input": {
    "prompt": "A flat illustration of a workspace with a laptop, coffee cup, and potted plant",
    "size": "1024x1024"
  }
}'
```

![Custom Size](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1/custom-size.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1/custom-size.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**With Color Controls** — Guide generation with specific brand colors</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1',
  {
    prompt: 'An abstract geometric pattern suitable for a tech company brand identity',
    controls: { colors: [{ rgb: [255, 107, 53] }, { rgb: [0, 43, 91] }] },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1",
  "input": {
    "prompt": "An abstract geometric pattern suitable for a tech company brand identity",
    "controls": {
      "colors": [
        {
          "rgb": [
            255,
            107,
            53
          ]
        },
        {
          "rgb": [
            0,
            43,
            91
          ]
        }
      ]
    }
  }
}'
```

![With Color Controls](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1/with-color-controls.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1/with-color-controls.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Background Color** — Set a specific background color</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1',
  {
    prompt: 'A clean icon of a lightning bolt',
    controls: { background_color: { rgb: [245, 245, 245] } },
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1",
  "input": {
    "prompt": "A clean icon of a lightning bolt",
    "controls": {
      "background_color": {
        "rgb": [
          245,
          245,
          245
        ]
      }
    },
    "size": "1024x1024"
  }
}'
```

![Background Color](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1/background-color.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1/background-color.png"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1/#page","headline":"Recraft V4.1","description":"Recraft V4.1 generates art-directed images tuned for high aesthetics, with strong composition, accurate text rendering, and refined design taste. Fast and cost-efficient at standard resolution.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Recraft V4.1 Pro generates high-resolution, art-directed images at 2048px+ tuned for high aesthetics, with strong composition, text rendering, and refined design taste. Built for print and production work.
title: Recraft V4.1 Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4.1 Pro

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4-1-pro`

- Third-party
- Zero data retention

Recraft V4.1 Pro generates high-resolution, art-directed images at 2048px+ tuned for high aesthetics, with strong composition, text rendering, and refined design taste. Built for print and production work.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-pro',
  {
    prompt:
      'A detailed vintage botanical illustration of a rose with leaves and thorns, scientific illustration style',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-pro",
  "input": {
    "prompt": "A detailed vintage botanical illustration of a rose with leaves and thorns, scientific illustration style"
  }
}'
```

![Print-Ready Illustration](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro/print-ready-illustration.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro/print-ready-illustration.png"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Large Format Art** — Large canvas digital art</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-pro',
  {
    prompt:
      'A sweeping fantasy landscape with floating islands, waterfalls cascading into clouds, and ancient stone bridges connecting the islands',
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-pro",
  "input": {
    "prompt": "A sweeping fantasy landscape with floating islands, waterfalls cascading into clouds, and ancient stone bridges connecting the islands",
    "size": "2048x2048"
  }
}'
```

![Large Format Art](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro/large-format-art.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro/large-format-art.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Brand Asset** — Professional brand asset with controlled colors</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-pro',
  {
    prompt:
      'A modern, clean illustration of a shield with a checkmark inside, representing security and trust',
    controls: {
      background_color: { rgb: [15, 23, 42] },
      colors: [{ rgb: [46, 117, 182] }, { rgb: [255, 255, 255] }],
    },
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-pro",
  "input": {
    "prompt": "A modern, clean illustration of a shield with a checkmark inside, representing security and trust",
    "controls": {
      "background_color": {
        "rgb": [
          15,
          23,
          42
        ]
      },
      "colors": [
        {
          "rgb": [
            46,
            117,
            182
          ]
        },
        {
          "rgb": [
            255,
            255,
            255
          ]
        }
      ]
    },
    "size": "2048x2048"
  }
}'
```

![Brand Asset](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro/brand-asset.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro/brand-asset.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Editorial Illustration** — Magazine-quality editorial illustration</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-pro',
  {
    prompt:
      'A conceptual illustration of artificial intelligence as a tree with circuit-board branches and glowing data leaves',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-pro",
  "input": {
    "prompt": "A conceptual illustration of artificial intelligence as a tree with circuit-board branches and glowing data leaves"
  }
}'
```

![Editorial Illustration](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro/editorial-illustration.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro/editorial-illustration.png"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro/#page","headline":"Recraft V4.1 Pro","description":"Recraft V4.1 Pro generates high-resolution, art-directed images at 2048px+ tuned for high aesthetics, with strong composition, text rendering, and refined design taste. Built for print and production work.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Generate detailed, high-resolution SVG vector graphics from text prompts with high aesthetic quality, fine geometry, scalable to any size for print and design work.
title: Recraft V4.1 Pro SVG
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4.1 Pro SVG

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro-vector/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4-1-pro-vector`

- Third-party
- Zero data retention

Generate detailed, high-resolution SVG vector graphics from text prompts with high aesthetic quality, fine geometry, scalable to any size for print and design work.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.30</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-pro-vector',
  { prompt: 'A modern minimalist logo for a cloud computing company, clean geometric shapes' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-pro-vector",
  "input": {
    "prompt": "A modern minimalist logo for a cloud computing company, clean geometric shapes"
  }
}'
```

![Logo Design](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro-vector/logo-design.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro-vector/logo-design.jpg"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Icon Set** — Generate a vector icon</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-pro-vector',
  {
    prompt: 'A flat design icon of a rocket launching, suitable for a mobile app',
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-pro-vector",
  "input": {
    "prompt": "A flat design icon of a rocket launching, suitable for a mobile app",
    "size": "2048x2048"
  }
}'
```

![Icon Set](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro-vector/icon-set.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro-vector/icon-set.jpg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Print-Ready Vector** — High-resolution vector for large-format print</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-pro-vector',
  {
    prompt:
      'An intricate mandala pattern with floral and geometric elements, highly detailed and symmetrical',
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-pro-vector",
  "input": {
    "prompt": "An intricate mandala pattern with floral and geometric elements, highly detailed and symmetrical",
    "size": "2048x2048"
  }
}'
```

![Print-Ready Vector](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro-vector/print-ready-vector.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro-vector/print-ready-vector.jpg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Brand Illustration** — Vector illustration with brand colors</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-pro-vector',
  {
    prompt: 'A vector illustration of a cityscape skyline at sunset with clean lines and flat colors',
    controls: { colors: [{ rgb: [255, 87, 51] }, { rgb: [41, 50, 65] }, { rgb: [239, 239, 239] }] },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-pro-vector",
  "input": {
    "prompt": "A vector illustration of a cityscape skyline at sunset with clean lines and flat colors",
    "controls": {
      "colors": [
        {
          "rgb": [
            255,
            87,
            51
          ]
        },
        {
          "rgb": [
            41,
            50,
            65
          ]
        },
        {
          "rgb": [
            239,
            239,
            239
          ]
        }
      ]
    }
  }
}'
```

![Brand Illustration](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro-vector/brand-illustration.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-pro-vector/brand-illustration.jpg"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro-vector/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro-vector/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro-vector/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro-vector/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro-vector/#page","headline":"Recraft V4.1 Pro SVG","description":"Generate detailed, high-resolution SVG vector graphics from text prompts with high aesthetic quality, fine geometry, scalable to any size for print and design work.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-pro-vector/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Recraft V4.1 Utility is a general-purpose text-to-image model balancing quality and flexibility for a wide range of everyday use cases at standard resolution.
title: Recraft V4.1 Utility
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4.1 Utility

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4-1-utility`

- Third-party
- Zero data retention

Recraft V4.1 Utility is a general-purpose text-to-image model balancing quality and flexibility for a wide range of everyday use cases at standard resolution.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.04</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility',
  { prompt: 'A friendly cartoon robot waving hello against a white background' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility",
  "input": {
    "prompt": "A friendly cartoon robot waving hello against a white background"
  }
}'
```

![Simple Generation](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility/simple-generation.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility/simple-generation.png"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Product Mockup** — Generate a product concept image</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility',
  { prompt: 'A clean product photo of a white ceramic coffee mug on a wooden table' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility",
  "input": {
    "prompt": "A clean product photo of a white ceramic coffee mug on a wooden table"
  }
}'
```

![Product Mockup](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility/product-mockup.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility/product-mockup.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Custom Size** — Specify output dimensions</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility',
  {
    prompt: 'A simple banner illustration with abstract shapes and warm colors',
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility",
  "input": {
    "prompt": "A simple banner illustration with abstract shapes and warm colors",
    "size": "1024x1024"
  }
}'
```

![Custom Size](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility/custom-size.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility/custom-size.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**With Color Controls** — Guide generation with specific colors</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility',
  {
    prompt: 'A flat illustration of a globe with network connections',
    controls: { colors: [{ rgb: [30, 90, 200] }, { rgb: [255, 255, 255] }] },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility",
  "input": {
    "prompt": "A flat illustration of a globe with network connections",
    "controls": {
      "colors": [
        {
          "rgb": [
            30,
            90,
            200
          ]
        },
        {
          "rgb": [
            255,
            255,
            255
          ]
        }
      ]
    }
  }
}'
```

![With Color Controls](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility/with-color-controls.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility/with-color-controls.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Background Color** — Set a specific background color</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility',
  {
    prompt: 'A simple icon of a checkmark inside a circle',
    controls: { background_color: { rgb: [240, 248, 255] } },
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility",
  "input": {
    "prompt": "A simple icon of a checkmark inside a circle",
    "controls": {
      "background_color": {
        "rgb": [
          240,
          248,
          255
        ]
      }
    },
    "size": "1024x1024"
  }
}'
```

![Background Color](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility/background-color.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility/background-color.png"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility/#page","headline":"Recraft V4.1 Utility","description":"Recraft V4.1 Utility is a general-purpose text-to-image model balancing quality and flexibility for a wide range of everyday use cases at standard resolution.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Recraft V4.1 Utility Pro is a general-purpose text-to-image model producing high-resolution 2048px+ output for a wide range of production and print use cases.
title: Recraft V4.1 Utility Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4.1 Utility Pro

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4-1-utility-pro`

- Third-party
- Zero data retention

Recraft V4.1 Utility Pro is a general-purpose text-to-image model producing high-resolution 2048px+ output for a wide range of production and print use cases.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-pro',
  {
    prompt:
      'A detailed illustrated map of an imaginary fantasy island with labeled landmarks, mountains, and forests',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-pro",
  "input": {
    "prompt": "A detailed illustrated map of an imaginary fantasy island with labeled landmarks, mountains, and forests"
  }
}'
```

![Print-Ready Illustration](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro/print-ready-illustration.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro/print-ready-illustration.png"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Large Format Art** — Large canvas general-purpose image</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-pro',
  {
    prompt:
      'A wide panoramic landscape of rolling green hills with a river winding through the valley under a bright blue sky',
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-pro",
  "input": {
    "prompt": "A wide panoramic landscape of rolling green hills with a river winding through the valley under a bright blue sky",
    "size": "2048x2048"
  }
}'
```

![Large Format Art](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro/large-format-art.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro/large-format-art.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Marketing Asset** — High-resolution marketing visual with controlled colors</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-pro',
  {
    prompt: 'A clean, modern banner illustration of a smartphone displaying a productivity app',
    controls: {
      background_color: { rgb: [250, 250, 255] },
      colors: [{ rgb: [100, 200, 150] }, { rgb: [20, 20, 60] }],
    },
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-pro",
  "input": {
    "prompt": "A clean, modern banner illustration of a smartphone displaying a productivity app",
    "controls": {
      "background_color": {
        "rgb": [
          250,
          250,
          255
        ]
      },
      "colors": [
        {
          "rgb": [
            100,
            200,
            150
          ]
        },
        {
          "rgb": [
            20,
            20,
            60
          ]
        }
      ]
    },
    "size": "2048x2048"
  }
}'
```

![Marketing Asset](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro/marketing-asset.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro/marketing-asset.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Technical Diagram** — High-resolution technical or infographic illustration</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-pro',
  {
    prompt:
      'A clean technical diagram showing the layers of a cloud computing architecture with labeled tiers',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-pro",
  "input": {
    "prompt": "A clean technical diagram showing the layers of a cloud computing architecture with labeled tiers"
  }
}'
```

![Technical Diagram](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro/technical-diagram.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro/technical-diagram.png"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro/#page","headline":"Recraft V4.1 Utility Pro","description":"Recraft V4.1 Utility Pro is a general-purpose text-to-image model producing high-resolution 2048px+ output for a wide range of production and print use cases.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Generate detailed, high-resolution SVG vector graphics from text prompts with a general-purpose model, scalable to any size for print and large-scale design work.
title: Recraft V4.1 Utility Pro SVG
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4.1 Utility Pro SVG

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro-vector/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4-1-utility-pro-vector`

- Third-party
- Zero data retention

Generate detailed, high-resolution SVG vector graphics from text prompts with a general-purpose model, scalable to any size for print and large-scale design work.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.30</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-pro-vector',
  { prompt: 'A clean, versatile logo for a software company with abstract geometric shapes' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-pro-vector",
  "input": {
    "prompt": "A clean, versatile logo for a software company with abstract geometric shapes"
  }
}'
```

![Logo Design](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro-vector/logo-design.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro-vector/logo-design.jpg"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Detailed Illustration** — High-resolution vector illustration</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-pro-vector',
  {
    prompt:
      'A detailed flat vector illustration of a city map with labeled streets, parks, and landmarks',
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-pro-vector",
  "input": {
    "prompt": "A detailed flat vector illustration of a city map with labeled streets, parks, and landmarks",
    "size": "2048x2048"
  }
}'
```

![Detailed Illustration](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro-vector/detailed-illustration.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro-vector/detailed-illustration.jpg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Print-Ready Vector** — High-resolution vector for large-format print</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-pro-vector',
  {
    prompt:
      'A decorative border pattern with repeating floral and leaf motifs, suitable for certificate or diploma design',
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-pro-vector",
  "input": {
    "prompt": "A decorative border pattern with repeating floral and leaf motifs, suitable for certificate or diploma design",
    "size": "2048x2048"
  }
}'
```

![Print-Ready Vector](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro-vector/print-ready-vector.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro-vector/print-ready-vector.jpg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Brand Illustration** — Vector illustration with brand colors</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-pro-vector',
  {
    prompt: 'A flat vector illustration of interconnected nodes representing a network or data flow',
    controls: { colors: [{ rgb: [0, 122, 204] }, { rgb: [255, 165, 0] }, { rgb: [240, 240, 240] }] },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-pro-vector",
  "input": {
    "prompt": "A flat vector illustration of interconnected nodes representing a network or data flow",
    "controls": {
      "colors": [
        {
          "rgb": [
            0,
            122,
            204
          ]
        },
        {
          "rgb": [
            255,
            165,
            0
          ]
        },
        {
          "rgb": [
            240,
            240,
            240
          ]
        }
      ]
    }
  }
}'
```

![Brand Illustration](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro-vector/brand-illustration.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-pro-vector/brand-illustration.jpg"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro-vector/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro-vector/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro-vector/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro-vector/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro-vector/#page","headline":"Recraft V4.1 Utility Pro SVG","description":"Generate detailed, high-resolution SVG vector graphics from text prompts with a general-purpose model, scalable to any size for print and large-scale design work.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-pro-vector/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Generate production-ready SVG vector graphics from text prompts with a general-purpose model suited for a wide range of design and illustration tasks.
title: Recraft V4.1 Utility SVG
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4.1 Utility SVG

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-vector/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4-1-utility-vector`

- Third-party
- Zero data retention

Generate production-ready SVG vector graphics from text prompts with a general-purpose model suited for a wide range of design and illustration tasks.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.08</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-vector',
  { prompt: 'A simple flat icon of a calendar with a date marked' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-vector",
  "input": {
    "prompt": "A simple flat icon of a calendar with a date marked"
  }
}'
```

![Simple Icon](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-vector/simple-icon.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-vector/simple-icon.jpg"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**App Icon** — Mobile app icon in vector format</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-vector',
  { prompt: 'A clean app icon featuring a magnifying glass over a document', size: '1024x1024' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-vector",
  "input": {
    "prompt": "A clean app icon featuring a magnifying glass over a document",
    "size": "1024x1024"
  }
}'
```

![App Icon](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-vector/app-icon.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-vector/app-icon.jpg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Illustration** — Vector illustration for general use</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-vector',
  {
    prompt:
      'A flat vector illustration of a team of people collaborating around a table with laptops',
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-vector",
  "input": {
    "prompt": "A flat vector illustration of a team of people collaborating around a table with laptops",
    "size": "1024x1024"
  }
}'
```

![Illustration](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-vector/illustration.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-vector/illustration.jpg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**With Brand Colors** — Vector with specific color palette</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-utility-vector',
  {
    prompt: 'A simple shield icon representing protection and security',
    controls: {
      background_color: { rgb: [245, 245, 245] },
      colors: [{ rgb: [34, 139, 87] }, { rgb: [255, 255, 255] }],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-utility-vector",
  "input": {
    "prompt": "A simple shield icon representing protection and security",
    "controls": {
      "background_color": {
        "rgb": [
          245,
          245,
          245
        ]
      },
      "colors": [
        {
          "rgb": [
            34,
            139,
            87
          ]
        },
        {
          "rgb": [
            255,
            255,
            255
          ]
        }
      ]
    }
  }
}'
```

![With Brand Colors](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-vector/with-brand-colors.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-utility-vector/with-brand-colors.jpg"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-vector/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-vector/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-vector/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-vector/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-vector/#page","headline":"Recraft V4.1 Utility SVG","description":"Generate production-ready SVG vector graphics from text prompts with a general-purpose model suited for a wide range of design and illustration tasks.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-utility-vector/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Generate production-ready SVG vector graphics from text prompts with high aesthetic quality, clean geometry, structured layers, and editable paths.
title: Recraft V4.1 SVG
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4.1 SVG

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-vector/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4-1-vector`

- Third-party
- Zero data retention

Generate production-ready SVG vector graphics from text prompts with high aesthetic quality, clean geometry, structured layers, and editable paths.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.08</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-vector',
  { prompt: 'A simple flat icon of a coffee cup with steam rising' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-vector",
  "input": {
    "prompt": "A simple flat icon of a coffee cup with steam rising"
  }
}'
```

![Simple Icon](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-vector/simple-icon.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-vector/simple-icon.jpg"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**App Icon** — Mobile app icon in vector format</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-vector',
  {
    prompt: 'A colorful gradient app icon featuring a chat bubble with a sparkle effect',
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-vector",
  "input": {
    "prompt": "A colorful gradient app icon featuring a chat bubble with a sparkle effect",
    "size": "1024x1024"
  }
}'
```

![App Icon](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-vector/app-icon.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-vector/app-icon.jpg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Illustration** — Vector illustration for web use</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-vector',
  {
    prompt:
      'A flat vector illustration of a person working at a desk with a computer, plants, and a window showing a city view',
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-vector",
  "input": {
    "prompt": "A flat vector illustration of a person working at a desk with a computer, plants, and a window showing a city view",
    "size": "1024x1024"
  }
}'
```

![Illustration](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-vector/illustration.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-vector/illustration.jpg"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**With Brand Colors** — Vector with specific color palette</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-1-vector',
  {
    prompt: 'A badge or seal design with a star in the center, suitable for a certification mark',
    controls: {
      background_color: { rgb: [255, 255, 255] },
      colors: [{ rgb: [0, 119, 182] }, { rgb: [255, 209, 102] }],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-1-vector",
  "input": {
    "prompt": "A badge or seal design with a star in the center, suitable for a certification mark",
    "controls": {
      "background_color": {
        "rgb": [
          255,
          255,
          255
        ]
      },
      "colors": [
        {
          "rgb": [
            0,
            119,
            182
          ]
        },
        {
          "rgb": [
            255,
            209,
            102
          ]
        }
      ]
    }
  }
}'
```

![With Brand Colors](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-vector/with-brand-colors.jpg)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-1-vector/with-brand-colors.jpg"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-vector/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-vector/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-vector/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-vector/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-vector/#page","headline":"Recraft V4.1 SVG","description":"Generate production-ready SVG vector graphics from text prompts with high aesthetic quality, clean geometry, structured layers, and editable paths.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-1-vector/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Recraft V4 Pro generates high-resolution, art-directed images at 2048px+ with strong composition, text rendering, and design taste. Built for print and production work.
title: Recraft V4 Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4 Pro

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4-pro`

- Third-party
- Zero data retention

Recraft V4 Pro generates high-resolution, art-directed images at 2048px+ with strong composition, text rendering, and design taste. Built for print and production work.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4-pro',
  {
    prompt:
      'A detailed vintage botanical illustration of a rose with leaves and thorns, scientific illustration style',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-pro",
  "input": {
    "prompt": "A detailed vintage botanical illustration of a rose with leaves and thorns, scientific illustration style"
  }
}'
```

![Print-Ready Illustration](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-pro/print-ready-illustration.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-pro/print-ready-illustration.png"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Large Format Art** — Large canvas digital art</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-pro',
  {
    prompt:
      'A sweeping fantasy landscape with floating islands, waterfalls cascading into clouds, and ancient stone bridges connecting the islands',
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-pro",
  "input": {
    "prompt": "A sweeping fantasy landscape with floating islands, waterfalls cascading into clouds, and ancient stone bridges connecting the islands",
    "size": "2048x2048"
  }
}'
```

![Large Format Art](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-pro/large-format-art.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-pro/large-format-art.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Brand Asset** — Professional brand asset with controlled colors</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-pro',
  {
    prompt:
      'A modern, clean illustration of a shield with a checkmark inside, representing security and trust',
    controls: {
      background_color: { rgb: [15, 23, 42] },
      colors: [{ rgb: [46, 117, 182] }, { rgb: [255, 255, 255] }],
    },
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-pro",
  "input": {
    "prompt": "A modern, clean illustration of a shield with a checkmark inside, representing security and trust",
    "controls": {
      "background_color": {
        "rgb": [
          15,
          23,
          42
        ]
      },
      "colors": [
        {
          "rgb": [
            46,
            117,
            182
          ]
        },
        {
          "rgb": [
            255,
            255,
            255
          ]
        }
      ]
    },
    "size": "2048x2048"
  }
}'
```

![Brand Asset](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-pro/brand-asset.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-pro/brand-asset.png"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Editorial Illustration** — Magazine-quality editorial illustration</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-pro',
  {
    prompt:
      'A conceptual illustration of artificial intelligence as a tree with circuit-board branches and glowing data leaves',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-pro",
  "input": {
    "prompt": "A conceptual illustration of artificial intelligence as a tree with circuit-board branches and glowing data leaves"
  }
}'
```

![Editorial Illustration](https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-pro/editorial-illustration.png)

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "image": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/recraft__recraftv4-pro/editorial-illustration.png"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro/#page","headline":"Recraft V4 Pro","description":"Recraft V4 Pro generates high-resolution, art-directed images at 2048px+ with strong composition, text rendering, and design taste. Built for print and production work.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Generate detailed, production-ready SVG vector graphics from text prompts with fine geometry, scalable to any size for print and design work.
title: Recraft V4 Pro SVG
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4 Pro SVG

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro-vector/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4-pro-vector`

- Third-party
- Zero data retention

Generate detailed, production-ready SVG vector graphics from text prompts with fine geometry, scalable to any size for print and design work.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.30</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4-pro-vector',
  { prompt: 'A modern minimalist logo for a cloud computing company, clean geometric shapes' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-pro-vector",
  "input": {
    "prompt": "A modern minimalist logo for a cloud computing company, clean geometric shapes"
  }
}'
```

![Logo Design](https://examples.aig.cloudflare.com/recraft/recraftv4-pro-vector/logo-design.svg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv4-pro-vector/logo-design.svg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Icon Set** — Generate a vector icon</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-pro-vector',
  {
    prompt: 'A flat design icon of a rocket launching, suitable for a mobile app',
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-pro-vector",
  "input": {
    "prompt": "A flat design icon of a rocket launching, suitable for a mobile app",
    "size": "2048x2048"
  }
}'
```

![Icon Set](https://examples.aig.cloudflare.com/recraft/recraftv4-pro-vector/icon-set.svg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv4-pro-vector/icon-set.svg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Print-Ready Vector** — High-resolution vector for large-format print</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-pro-vector',
  {
    prompt:
      'An intricate mandala pattern with floral and geometric elements, highly detailed and symmetrical',
    size: '2048x2048',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-pro-vector",
  "input": {
    "prompt": "An intricate mandala pattern with floral and geometric elements, highly detailed and symmetrical",
    "size": "2048x2048"
  }
}'
```

![Print-Ready Vector](https://examples.aig.cloudflare.com/recraft/recraftv4-pro-vector/print-ready-vector.svg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv4-pro-vector/print-ready-vector.svg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Brand Illustration** — Vector illustration with brand colors</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-pro-vector',
  {
    prompt: 'A vector illustration of a cityscape skyline at sunset with clean lines and flat colors',
    controls: { colors: [{ rgb: [255, 87, 51] }, { rgb: [41, 50, 65] }, { rgb: [239, 239, 239] }] },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-pro-vector",
  "input": {
    "prompt": "A vector illustration of a cityscape skyline at sunset with clean lines and flat colors",
    "controls": {
      "colors": [
        {
          "rgb": [
            255,
            87,
            51
          ]
        },
        {
          "rgb": [
            41,
            50,
            65
          ]
        },
        {
          "rgb": [
            239,
            239,
            239
          ]
        }
      ]
    }
  }
}'
```

![Brand Illustration](https://examples.aig.cloudflare.com/recraft/recraftv4-pro-vector/brand-illustration.svg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv4-pro-vector/brand-illustration.svg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro-vector/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro-vector/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro-vector/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro-vector/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro-vector/#page","headline":"Recraft V4 Pro SVG","description":"Generate detailed, production-ready SVG vector graphics from text prompts with fine geometry, scalable to any size for print and design work.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-pro-vector/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Generate production-ready SVG vector graphics from text prompts with clean geometry, structured layers, and editable paths.
title: Recraft V4 SVG
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Recraft logo](https://developers.cloudflare.com/_astro/recraft.BhhnJczi.svg)

# Recraft V4 SVG

Text-to-Image • Recraft

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/recraft/recraftv4-vector/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`recraft/recraftv4-vector`

- Third-party
- Zero data retention

Generate production-ready SVG vector graphics from text prompts with clean geometry, structured layers, and editable paths.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.recraft.ai/terms) |
| More information | [link ↗](https://www.recraft.ai/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.08</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'recraft/recraftv4-vector',
  { prompt: 'A simple flat icon of a coffee cup with steam rising' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-vector",
  "input": {
    "prompt": "A simple flat icon of a coffee cup with steam rising"
  }
}'
```

![Simple Icon](https://examples.aig.cloudflare.com/recraft/recraftv4-vector/simple-icon.svg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv4-vector/simple-icon.svg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**App Icon** — Mobile app icon in vector format</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-vector',
  {
    prompt: 'A colorful gradient app icon featuring a chat bubble with a sparkle effect',
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-vector",
  "input": {
    "prompt": "A colorful gradient app icon featuring a chat bubble with a sparkle effect",
    "size": "1024x1024"
  }
}'
```

![App Icon](https://examples.aig.cloudflare.com/recraft/recraftv4-vector/app-icon.svg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv4-vector/app-icon.svg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Illustration** — Vector illustration for web use</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-vector',
  {
    prompt:
      'A flat vector illustration of a person working at a desk with a computer, plants, and a window showing a city view',
    size: '1024x1024',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-vector",
  "input": {
    "prompt": "A flat vector illustration of a person working at a desk with a computer, plants, and a window showing a city view",
    "size": "1024x1024"
  }
}'
```

![Illustration](https://examples.aig.cloudflare.com/recraft/recraftv4-vector/illustration.svg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv4-vector/illustration.svg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**With Brand Colors** — Vector with specific color palette</summary>



```ts
const response = await env.AI.run(
  'recraft/recraftv4-vector',
  {
    prompt: 'A badge or seal design with a star in the center, suitable for a certification mark',
    controls: {
      background_color: { rgb: [255, 255, 255] },
      colors: [{ rgb: [0, 119, 182] }, { rgb: [255, 209, 102] }],
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "recraft/recraftv4-vector",
  "input": {
    "prompt": "A badge or seal design with a star in the center, suitable for a certification mark",
    "controls": {
      "background_color": {
        "rgb": [
          255,
          255,
          255
        ]
      },
      "colors": [
        {
          "rgb": [
            0,
            119,
            182
          ]
        },
        {
          "rgb": [
            255,
            209,
            102
          ]
        }
      ]
    }
  }
}'
```

![With Brand Colors](https://examples.aig.cloudflare.com/recraft/recraftv4-vector/with-brand-colors.svg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/recraft/recraftv4-vector/with-brand-colors.svg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`required

size

`string`

style

`string`

substyle

`string`

▶controls{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-vector/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-vector/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/recraft/recraftv4-vector/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/recraft/recraftv4-vector/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-vector/#page","headline":"Recraft V4 SVG","description":"Generate production-ready SVG vector graphics from text prompts with clean geometry, structured layers, and editable paths.","url":"https://developers.cloudflare.com/ai/models/recraft/recraftv4-vector/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: RunwayML's video editing model. Edit one frame to update your whole video, make changes across multiple shots, and work with up to 30 seconds of video. Supports keyframe-guided editing for precise control over specific moments in the clip.
title: RunwayML Aleph 2
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![RunwayML logo](https://developers.cloudflare.com/_astro/runway.Cq8Cjov4.svg)

# RunwayML Aleph 2

Text-to-Video • RunwayML

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/runwayml/aleph-2/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`runwayml/aleph-2`

- Third-party

RunwayML's video editing model. Edit one frame to update your whole video, make changes across multiple shots, and work with up to 30 seconds of video. Supports keyframe-guided editing for precise control over specific moments in the clip.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://runwayml.com/terms-of-use) |
| More information | [link ↗](https://runwayml.com/) |
| Pricing | <ul><li>Default (per second)$0.336</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'runwayml/aleph-2',
  {
    prompt: 'Transform the scene into a golden-hour sunset with warm lighting',
    video_uri: 'https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/runwayml__gen-4.5/cinematic-scene.mp4',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "runwayml/aleph-2",
  "input": {
    "prompt": "Transform the scene into a golden-hour sunset with warm lighting",
    "video_uri": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/runwayml__gen-4.5/cinematic-scene.mp4"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://dnznrvs05pmza.cloudfront.net/7449093b-e574-41a5-8308-05e4692fa652.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Keyframe-Guided Edit** — Edit a video using a reference image anchored to the first frame of the output</summary>



```ts
const response = await env.AI.run(
  'runwayml/aleph-2',
  {
    prompt: 'Edit the video to match the provided reference frame',
    video_uri: 'https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/runwayml__gen-4.5/nature-close-up.mp4',
    prompt_images: [
      {
        uri: 'https://upload.wikimedia.org/wikipedia/commons/8/85/Tour_Eiffel_Wikimedia_Commons_(cropped).jpg',
        position: 'first',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "runwayml/aleph-2",
  "input": {
    "prompt": "Edit the video to match the provided reference frame",
    "video_uri": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/runwayml__gen-4.5/nature-close-up.mp4",
    "prompt_images": [
      {
        "uri": "https://upload.wikimedia.org/wikipedia/commons/8/85/Tour_Eiffel_Wikimedia_Commons_(cropped).jpg",
        "position": "first"
      }
    ]
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://dnznrvs05pmza.cloudfront.net/cd7388fe-09d6-4b16-afc5-24bb315eaf14.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Timed Keyframe Edit** — Place a guidance image at a specific timestamp within the input video using keyframes[].seconds</summary>



```ts
const response = await env.AI.run(
  'runwayml/aleph-2',
  {
    prompt: 'Change the background to a futuristic cityscape at night',
    video_uri: 'https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/runwayml__gen-4.5/simple-text-to-video.mp4',
    keyframes: [
      {
        uri: 'https://upload.wikimedia.org/wikipedia/commons/8/85/Tour_Eiffel_Wikimedia_Commons_(cropped).jpg',
        seconds: 2.0,
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "runwayml/aleph-2",
  "input": {
    "prompt": "Change the background to a futuristic cityscape at night",
    "video_uri": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/runwayml__gen-4.5/simple-text-to-video.mp4",
    "keyframes": [
      {
        "uri": "https://upload.wikimedia.org/wikipedia/commons/8/85/Tour_Eiffel_Wikimedia_Commons_(cropped).jpg",
        "seconds": 2.0
      }
    ]
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://dnznrvs05pmza.cloudfront.net/a7e054fa-1cf2-4265-a35c-518b8c4d6a1a.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Content Moderation Override** — Edit a video featuring public figures with relaxed content moderation</summary>



```ts
const response = await env.AI.run(
  'runwayml/aleph-2',
  {
    prompt: 'Make the background a dramatic stormy sky',
    video_uri: 'https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/runwayml__gen-4.5/cinematic-scene.mp4',
    content_moderation: {
      public_figure_threshold: 'low',
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "runwayml/aleph-2",
  "input": {
    "prompt": "Make the background a dramatic stormy sky",
    "video_uri": "https://pub-04a6d208d361438ea01b797e6973bd19.r2.dev/catalog/runwayml__gen-4.5/cinematic-scene.mp4",
    "content_moderation": {
      "public_figure_threshold": "low"
    }
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://dnznrvs05pmza.cloudfront.net/ea5b1ccd-3dd6-43c3-86e3-5ed720849e92.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`requiredminLength: 1maxLength: 1000Text prompt describing the edit to apply to the input video

video\_uri

`string`requiredHTTPS URL, Runway URI, or data URI of the source video to edit (≤30 seconds)

▶keyframes\[]

`array`minItems: 1maxItems: 5Timed guidance images placed at specific points in the input video. Each entry has a uri and either seconds (absolute timestamp) or at (fractional position). Up to 5.

▶prompt\_images\[]

`array`minItems: 1maxItems: 5Image keyframes for guiding the edit at specific points in the output video. Up to 5.

seed

`integer`minimum: 0maximum: 4294967295Random seed for reproducible results

▶content\_moderation{}

`object`Settings that affect the behavior of the content moderation system

duration

`number`exclusiveMinimum: 0Duration of the source video in seconds. Used for billing only — not sent to RunwayML. Provide this so the gateway can compute per-second video cost accurately.

video

`string`format: uriURL to the edited video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/runwayml/aleph-2/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/runwayml/aleph-2/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/runwayml/aleph-2/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/runwayml/aleph-2/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/runwayml/aleph-2/#page","headline":"RunwayML Aleph 2","description":"RunwayML's video editing model. Edit one frame to update your whole video, make changes across multiple shots, and work with up to 30 seconds of video. Supports keyframe-guided editing for precise control over specific moments in the clip.","url":"https://developers.cloudflare.com/ai/models/runwayml/aleph-2/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: RunwayML's video generation model supporting both text-to-video and image-to-video with customizable duration, aspect ratio, and content moderation controls.
title: RunwayML Gen-4.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![RunwayML logo](https://developers.cloudflare.com/_astro/runway.Cq8Cjov4.svg)

# RunwayML Gen-4.5

Text-to-Video • RunwayML

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/runwayml/gen-4.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`runwayml/gen-4.5`

- Third-party

RunwayML's video generation model supporting both text-to-video and image-to-video with customizable duration, aspect ratio, and content moderation controls.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://runwayml.com/terms-of-use) |
| More information | [link ↗](https://runwayml.com/) |
| Pricing | <ul><li>Default (per second)$0.12</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'runwayml/gen-4.5',
  {
    prompt: 'A timelapse of the Eiffel Tower on a sunny day with clouds flying by',
    duration: 5,
    ratio: '1280:720',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "runwayml/gen-4.5",
  "input": {
    "prompt": "A timelapse of the Eiffel Tower on a sunny day with clouds flying by",
    "duration": 5,
    "ratio": "1280:720"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://dnznrvs05pmza.cloudfront.net/fd840364-360e-4903-8500-d5787fd8ab90.mp4"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Portrait Video** — Vertical video for social media</summary>



```ts
const response = await env.AI.run(
  'runwayml/gen-4.5',
  {
    prompt:
      'A busy street in Tokyo at night with neon signs reflecting on wet pavement, rain falling',
    duration: 5,
    ratio: '720:1280',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "runwayml/gen-4.5",
  "input": {
    "prompt": "A busy street in Tokyo at night with neon signs reflecting on wet pavement, rain falling",
    "duration": 5,
    "ratio": "720:1280"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://dnznrvs05pmza.cloudfront.net/44f43eac-8c12-4084-ace3-6395fa67c13e.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Nature Close-up** — Close-up wildlife shot in 16:9</summary>



```ts
const response = await env.AI.run(
  'runwayml/gen-4.5',
  {
    prompt:
      'Close-up of a hummingbird feeding from a vibrant red flower, slow motion with soft bokeh background',
    duration: 5,
    ratio: '1280:720',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "runwayml/gen-4.5",
  "input": {
    "prompt": "Close-up of a hummingbird feeding from a vibrant red flower, slow motion with soft bokeh background",
    "duration": 5,
    "ratio": "1280:720"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://dnznrvs05pmza.cloudfront.net/e03781eb-2544-45ae-a9a8-6148d556bf2a.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Cinematic Scene** — Longer duration cinematic video</summary>



```ts
const response = await env.AI.run(
  'runwayml/gen-4.5',
  {
    prompt:
      'Aerial drone shot flying through a misty forest at dawn, rays of sunlight breaking through the trees',
    duration: 10,
    ratio: '1280:720',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "runwayml/gen-4.5",
  "input": {
    "prompt": "Aerial drone shot flying through a misty forest at dawn, rays of sunlight breaking through the trees",
    "duration": 10,
    "ratio": "1280:720"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://dnznrvs05pmza.cloudfront.net/23ea177e-523d-45b4-9f8c-c4f8d7238ff0.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Image-to-Video** — Animate an existing image</summary>



```ts
const response = await env.AI.run(
  'runwayml/gen-4.5',
  {
    prompt: 'Camera slowly pans across the scene, gentle wind blowing',
    duration: 5,
    image_input:
      'https://upload.wikimedia.org/wikipedia/commons/8/85/Tour_Eiffel_Wikimedia_Commons_(cropped).jpg',
    ratio: '1280:720',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "runwayml/gen-4.5",
  "input": {
    "prompt": "Camera slowly pans across the scene, gentle wind blowing",
    "duration": 5,
    "image_input": "https://upload.wikimedia.org/wikipedia/commons/8/85/Tour_Eiffel_Wikimedia_Commons_(cropped).jpg",
    "ratio": "1280:720"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://dnznrvs05pmza.cloudfront.net/ab424367-7431-4a0a-aa39-52604ff9150a.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Reproducible Generation** — Use seed for consistent results</summary>



```ts
const response = await env.AI.run(
  'runwayml/gen-4.5',
  {
    prompt: 'A sailboat gliding across calm ocean waters at sunset',
    duration: 5,
    ratio: '1280:720',
    seed: 42,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "runwayml/gen-4.5",
  "input": {
    "prompt": "A sailboat gliding across calm ocean waters at sunset",
    "duration": 5,
    "ratio": "1280:720",
    "seed": 42
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://dnznrvs05pmza.cloudfront.net/0bdfbec7-0823-4529-bdb5-d37bb24adb0d.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**With Content Moderation** — Adjust content moderation settings</summary>



```ts
const response = await env.AI.run(
  'runwayml/gen-4.5',
  {
    prompt: 'A press conference with multiple speakers at podiums',
    content_moderation: { public_figure_threshold: 'low' },
    duration: 5,
    ratio: '1280:720',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "runwayml/gen-4.5",
  "input": {
    "prompt": "A press conference with multiple speakers at podiums",
    "content_moderation": {
      "public_figure_threshold": "low"
    },
    "duration": 5,
    "ratio": "1280:720"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://dnznrvs05pmza.cloudfront.net/75c4cb0d-20aa-4824-b1f3-32f33ab9269b.mp4"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`requiredminLength: 1maxLength: 1000Text prompt describing what should appear in the video

image\_input

`string`HTTPS URL, Runway URI, or data URI containing an image for image-to-video

ratio

`string`requireddefault: 1280:720enum: 1280:720, 720:1280, 1104:832, 960:960, 832:1104, 1584:672Resolution/aspect ratio of the output video

duration

`integer`requireddefault: 5minimum: 2maximum: 10Video duration in seconds

seed

`integer`minimum: 0maximum: 4294967295Random seed for reproducible results

▶content\_moderation{}

`object`Content moderation settings

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/runwayml/gen-4.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/runwayml/gen-4.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/runwayml/gen-4.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/runwayml/gen-4.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/runwayml/gen-4.5/#page","headline":"RunwayML Gen-4.5","description":"RunwayML's video generation model supporting both text-to-video and image-to-video with customizable duration, aspect ratio, and content moderation controls.","url":"https://developers.cloudflare.com/ai/models/runwayml/gen-4.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Inkling is Thinking Machines' open-weights hybrid reasoning model, built on a mixture-of-experts architecture. It reasons by default, exposing its chain-of-thought as leading thinking content blocks, with reasoning effort tunable via a Tinker-specific output_config.effort parameter. Available through Tinker's beta Anthropic Messages-compatible endpoint alongside tool use, streaming, and multi-turn conversations. Currently intended for low-traffic testing and internal use rather than high-throughput production deployments; prompt caching, citations, and audio input are not supported through this endpoint.
title: Inkling
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

t

# Inkling

Text Generation • thinkingmachines

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`thinkingmachines/inkling`

- Third-party

Inkling is Thinking Machines' open-weights hybrid reasoning model, built on a mixture-of-experts architecture. It reasons by default, exposing its chain-of-thought as leading thinking content blocks, with reasoning effort tunable via a Tinker-specific output\_config.effort parameter. Available through Tinker's beta Anthropic Messages-compatible endpoint alongside tool use, streaming, and multi-turn conversations. Currently intended for low-traffic testing and internal use rather than high-throughput production deployments; prompt caching, citations, and audio input are not supported through this endpoint.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 64,000 tokens |
| More information | [link ↗](https://huggingface.co/thinkingmachines/Inkling) |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$1.87</li><li>Output (per 1M tokens)$4.68</li><li>Cached input (per 1M tokens)$0.374</li><li>Cache creation (per 1M tokens)$1.87</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'thinkingmachines/inkling',
  { max_tokens: 512, messages: [{ content: 'The capital of France is', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "thinkingmachines/inkling",
  "max_tokens": 512,
  "messages": [
    {
      "content": "The capital of France is",
      "role": "user"
    }
  ]
}'
```

```
Paris.
```

```json
{
  "id": "msg_922ec1780752447c802ec60be3dabfd6",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "The user is asking a simple factual question: \"The capital of France is\". The answer is Paris. I should provide the answer clearly and concisely.",
      "signature": ""
    },
    {
      "type": "text",
      "text": "Paris."
    }
  ],
  "model": "thinkingmachines/Inkling",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 0,
    "output_tokens": 41,
    "cache_creation_input_tokens": 19,
    "cache_read_input_tokens": 0
  }
}
```

## Examples

<details>

<summary>**Tool Use** — Tool use round-trip: the model requests a tool call, then answers using the tool_result supplied in a follow-up user message</summary>



```ts
const response = await env.AI.run(
  'thinkingmachines/inkling',
  {
    max_tokens: 1024,
    messages: [
      { content: "What's the weather in Paris?", role: 'user' },
      {
        content: [
          {
            id: 'toolu_01A1x1x1x1x1x1x1x1x1x1x1',
            input: { city: 'Paris' },
            name: 'get_weather',
            type: 'tool_use',
          },
        ],
        role: 'assistant',
      },
      {
        content: [
          {
            content: 'Sunny, 22°C',
            tool_use_id: 'toolu_01A1x1x1x1x1x1x1x1x1x1x1',
            type: 'tool_result',
          },
        ],
        role: 'user',
      },
    ],
    tools: [
      {
        description: 'Get the current weather for a city.',
        input_schema: {
          properties: { city: { type: 'string' } },
          required: ['city'],
          type: 'object',
        },
        name: 'get_weather',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "thinkingmachines/inkling",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What'\''s the weather in Paris?",
      "role": "user"
    },
    {
      "content": [
        {
          "id": "toolu_01A1x1x1x1x1x1x1x1x1x1x1",
          "input": {
            "city": "Paris"
          },
          "name": "get_weather",
          "type": "tool_use"
        }
      ],
      "role": "assistant"
    },
    {
      "content": [
        {
          "content": "Sunny, 22°C",
          "tool_use_id": "toolu_01A1x1x1x1x1x1x1x1x1x1x1",
          "type": "tool_result"
        }
      ],
      "role": "user"
    }
  ],
  "tools": [
    {
      "description": "Get the current weather for a city.",
      "input_schema": {
        "properties": {
          "city": {
            "type": "string"
          }
        },
        "required": [
          "city"
        ],
        "type": "object"
      },
      "name": "get_weather"
    }
  ]
}'
```

```
The weather in Paris is sunny with a temperature of 22°C. Enjoy the nice weather!
```

```json
{
  "id": "msg_ddfc346862fc4a3f8afc1f8f53e1d932",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "The user asked for the weather in Paris and the function returned \"Sunny, 22°C\". I should provide a clear, friendly answer with this information.",
      "signature": ""
    },
    {
      "type": "text",
      "text": "The weather in Paris is sunny with a temperature of 22°C. Enjoy the nice weather!"
    }
  ],
  "model": "thinkingmachines/Inkling",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 0,
    "output_tokens": 57,
    "cache_creation_input_tokens": 95,
    "cache_read_input_tokens": 0
  }
}
```

</details>

<details>

<summary>**Extended Thinking Effort** — Controlling reasoning effort via Tinker's output_config.effort extension. The model's chain-of-thought is returned as a leading thinking content block before the answer.</summary>



```ts
const response = await env.AI.run(
  'thinkingmachines/inkling',
  {
    max_tokens: 1024,
    messages: [{ content: 'What is 17 * 23?', role: 'user' }],
    output_config: { effort: 'high' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "thinkingmachines/inkling",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What is 17 * 23?",
      "role": "user"
    }
  ],
  "output_config": {
    "effort": "high"
  }
}'
```

```
17 × 23 = **391**

(Breakdown: 17 × 20 = 340, plus 17 × 3 = 51; 340 + 51 = 391)
```

```json
{
  "id": "msg_a7e845f498bd44e9b1d63dca8b104a2e",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "The user is asking for the product of 17 and 23. Let me calculate that.\n\n17 * 23 = ?\n\nI can compute this as:\n17 * 20 = 340\n17 * 3 = 51\n340 + 51 = 391\n\nAlternatively:\n17 * 23 = 17 * (25 - 2) = 425 - 34 = 391\nOr (20 - 3) * 23 = 460 - 69 = 391\n\nSo the answer is 391.",
      "signature": ""
    },
    {
      "type": "text",
      "text": "17 × 23 = **391**\n\n(Breakdown: 17 × 20 = 340, plus 17 × 3 = 51; 340 + 51 = 391)"
    }
  ],
  "model": "thinkingmachines/Inkling",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 0,
    "output_tokens": 155,
    "cache_creation_input_tokens": 22,
    "cache_read_input_tokens": 0
  }
}
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

temperature

`number`minimum: 0maximum: 1

top\_p

`number`minimum: 0maximum: 1

top\_k

`number`exclusiveMinimum: 0

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/thinkingmachines/inkling/#page","headline":"Inkling","description":"Inkling is Thinking Machines' open-weights hybrid reasoning model, built on a mixture-of-experts architecture. It reasons by default, exposing its chain-of-thought as leading thinking content blocks, with reasoning effort tunable via a Tinker-specific output_config.effort parameter. Available through Tinker's beta Anthropic Messages-compatible endpoint alongside tool use, streaming, and multi-turn conversations. Currently intended for low-traffic testing and internal use rather than high-throughput production deployments; prompt caching, citations, and audio input are not supported through this endpoint.","url":"https://developers.cloudflare.com/ai/models/thinkingmachines/inkling/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: The 256K-context variant of Inkling, Thinking Machines' open-weights hybrid reasoning MoE model. Same hybrid reasoning, tool-use, and streaming support as the base model, with an extended context window for longer conversations and documents. Currently intended for low-traffic testing and internal use rather than high-throughput production deployments.
title: Inkling 256K
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

t

# Inkling 256K

Text Generation • thinkingmachines

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling-256k/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`thinkingmachines/inkling-256k`

- Third-party

The 256K-context variant of Inkling, Thinking Machines' open-weights hybrid reasoning MoE model. Same hybrid reasoning, tool-use, and streaming support as the base model, with an extended context window for longer conversations and documents. Currently intended for low-traffic testing and internal use rather than high-throughput production deployments.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 262,144 tokens |
| More information | [link ↗](https://huggingface.co/thinkingmachines/Inkling) |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$3.74</li><li>Output (per 1M tokens)$9.36</li><li>Cached input (per 1M tokens)$0.748</li><li>Cache creation (per 1M tokens)$3.74</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'thinkingmachines/inkling-256k',
  { max_tokens: 512, messages: [{ content: 'The capital of France is', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "thinkingmachines/inkling-256k",
  "max_tokens": 512,
  "messages": [
    {
      "content": "The capital of France is",
      "role": "user"
    }
  ]
}'
```

```
The capital of France is **Paris**.
```

```json
{
  "id": "msg_f3f0874570144f29add4272d4f07491d",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "The user is asking \"The capital of France is\". This is a straightforward factual question. The capital of France is Paris. I should provide the answer clearly and concisely.",
      "signature": ""
    },
    {
      "type": "text",
      "text": "The capital of France is **Paris**."
    }
  ],
  "model": "thinkingmachines/Inkling:peft:262144",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 0,
    "output_tokens": 52,
    "cache_creation_input_tokens": 19,
    "cache_read_input_tokens": 0
  }
}
```

## Examples

<details>

<summary>**Tool Use** — Tool use round-trip: the model requests a tool call, then answers using the tool_result supplied in a follow-up user message</summary>



```ts
const response = await env.AI.run(
  'thinkingmachines/inkling-256k',
  {
    max_tokens: 1024,
    messages: [
      { content: "What's the weather in Paris?", role: 'user' },
      {
        content: [
          {
            id: 'toolu_01A1x1x1x1x1x1x1x1x1x1x1',
            input: { city: 'Paris' },
            name: 'get_weather',
            type: 'tool_use',
          },
        ],
        role: 'assistant',
      },
      {
        content: [
          {
            content: 'Sunny, 22°C',
            tool_use_id: 'toolu_01A1x1x1x1x1x1x1x1x1x1x1',
            type: 'tool_result',
          },
        ],
        role: 'user',
      },
    ],
    tools: [
      {
        description: 'Get the current weather for a city.',
        input_schema: {
          properties: { city: { type: 'string' } },
          required: ['city'],
          type: 'object',
        },
        name: 'get_weather',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "thinkingmachines/inkling-256k",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "What'\''s the weather in Paris?",
      "role": "user"
    },
    {
      "content": [
        {
          "id": "toolu_01A1x1x1x1x1x1x1x1x1x1x1",
          "input": {
            "city": "Paris"
          },
          "name": "get_weather",
          "type": "tool_use"
        }
      ],
      "role": "assistant"
    },
    {
      "content": [
        {
          "content": "Sunny, 22°C",
          "tool_use_id": "toolu_01A1x1x1x1x1x1x1x1x1x1x1",
          "type": "tool_result"
        }
      ],
      "role": "user"
    }
  ],
  "tools": [
    {
      "description": "Get the current weather for a city.",
      "input_schema": {
        "properties": {
          "city": {
            "type": "string"
          }
        },
        "required": [
          "city"
        ],
        "type": "object"
      },
      "name": "get_weather"
    }
  ]
}'
```

```
The weather in Paris is sunny with a temperature of 22°C.
```

```json
{
  "id": "msg_5711f240c8da46eeb462f8900281d087",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "The user asked for the weather in Paris. The function returned \"Sunny, 22°C\". I should provide a clear, concise answer.",
      "signature": ""
    },
    {
      "type": "text",
      "text": "The weather in Paris is sunny with a temperature of 22°C."
    }
  ],
  "model": "thinkingmachines/Inkling:peft:262144",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 0,
    "output_tokens": 49,
    "cache_creation_input_tokens": 95,
    "cache_read_input_tokens": 0
  }
}
```

</details>

## Parameters

▶messages\[]

`array`required

max\_tokens

`number`requiredexclusiveMinimum: 0

system

`string`

temperature

`number`minimum: 0maximum: 1

top\_p

`number`minimum: 0maximum: 1

top\_k

`number`exclusiveMinimum: 0

stream

`boolean`

▶metadata{}

`object`

id

`string`

type

`string`const: message

role

`string`const: assistant

▶content\[]

`array`

model

`string`

stop\_reason

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling-256k/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling-256k/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling-256k/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/thinkingmachines/inkling-256k/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/thinkingmachines/inkling-256k/#page","headline":"Inkling 256K","description":"The 256K-context variant of Inkling, Thinking Machines' open-weights hybrid reasoning MoE model. Same hybrid reasoning, tool-use, and streaming support as the base model, with an extended context window for longer conversations and documents. Currently intended for low-traffic testing and internal use rather than high-throughput production deployments.","url":"https://developers.cloudflare.com/ai/models/thinkingmachines/inkling-256k/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Jev is TypeSafe's structured evaluation model. It evaluates one state against typed Noul, Choice, and Score questions and returns calibrated answers with probabilities and confidence.
title: Jev
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

t

# Jev

Text Generation • typesafe

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/typesafe/jev/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`typesafe/jev`

- Third-party
- Zero data retention

Jev is TypeSafe's structured evaluation model. It evaluates one state against typed Noul, Choice, and Score questions and returns calibrated answers with probabilities and confidence.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 32,000 tokens |
| Terms and License | [link ↗](https://docs.typesafe.ai/legal.md) |
| More information | [link ↗](https://docs.typesafe.ai/models.md) |
| Zero data retention | Yes |
| Pricing | <ul><li>Input (per 1M tokens)$0.042</li><li>Output (per 1M tokens)$0.00</li><li>Cached input (per 1M tokens)$0.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'typesafe/jev',
  {
    state: 'Help! My payouts have been failing for 3 days.',
    questions: {
      is_urgent: {
        type: 'noul',
        instructions: 'Does this convey urgency?',
        criteria: { true: 'Explicitly time-sensitive', false: 'No urgency expressed' },
      },
      department: {
        type: 'choice',
        instructions: 'Which team should handle this?',
        criteria: {
          billing: 'Payments, invoicing, refunds',
          technical: 'Bugs, outages, integrations',
          sales: 'Pricing, upgrades, new accounts',
        },
      },
      frustration: {
        type: 'score',
        instructions: 'How frustrated is the customer?',
        criteria: ['Calm', 'Frustrated', 'Very angry'],
      },
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "typesafe/jev",
  "input": {
    "state": "Help! My payouts have been failing for 3 days.",
    "questions": {
      "is_urgent": {
        "type": "noul",
        "instructions": "Does this convey urgency?",
        "criteria": {
          "true": "Explicitly time-sensitive",
          "false": "No urgency expressed"
        }
      },
      "department": {
        "type": "choice",
        "instructions": "Which team should handle this?",
        "criteria": {
          "billing": "Payments, invoicing, refunds",
          "technical": "Bugs, outages, integrations",
          "sales": "Pricing, upgrades, new accounts"
        }
      },
      "frustration": {
        "type": "score",
        "instructions": "How frustrated is the customer?",
        "criteria": [
          "Calm",
          "Frustrated",
          "Very angry"
        ]
      }
    }
  }
}'
```

```json
{
  "model": "jev-1.13.0",
  "answers": {
    "is_urgent": {
      "type": "noul",
      "noul": 0.95
    },
    "department": {
      "type": "choice",
      "choice": "billing",
      "confidence": 0.8,
      "probabilities": {
        "billing": 0.87,
        "sales": 0,
        "technical": 0.13
      }
    },
    "frustration": {
      "type": "score",
      "score": 1.04,
      "confidence": 0.94,
      "legend": {
        "0": "Calm",
        "1": "Frustrated",
        "2": "Very angry"
      },
      "probabilities": {
        "0": 0,
        "1": 0.96,
        "2": 0.04
      }
    }
  },
  "usage": {
    "input_tokens": 426,
    "output_tokens": 73
  }
}
```

## Examples

<details>

<summary>**Structured refund review** — Evaluate a refund request against a structured order and policy</summary>



```ts
const response = await env.AI.run(
  'typesafe/jev',
  {
    state: {
      ticket: {
        subject: 'Duplicate charge',
        message: 'I was charged twice for order A-104. Please refund the duplicate.',
      },
      order: {
        id: 'A-104',
        charges: [
          { amount_usd: 49, status: 'captured' },
          { amount_usd: 49, status: 'captured' },
        ],
      },
      refund_policy: 'Duplicate charges are eligible for a refund.',
    },
    questions: {
      refund_requested: { type: 'noul', instructions: 'Does `ticket.message` request a refund?' },
      policy_supports_refund: {
        type: 'noul',
        instructions:
          'Does `refund_policy` support the refund requested in `ticket.message`, given `order.charges`?',
      },
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "typesafe/jev",
  "input": {
    "state": {
      "ticket": {
        "subject": "Duplicate charge",
        "message": "I was charged twice for order A-104. Please refund the duplicate."
      },
      "order": {
        "id": "A-104",
        "charges": [
          {
            "amount_usd": 49,
            "status": "captured"
          },
          {
            "amount_usd": 49,
            "status": "captured"
          }
        ]
      },
      "refund_policy": "Duplicate charges are eligible for a refund."
    },
    "questions": {
      "refund_requested": {
        "type": "noul",
        "instructions": "Does `ticket.message` request a refund?"
      },
      "policy_supports_refund": {
        "type": "noul",
        "instructions": "Does `refund_policy` support the refund requested in `ticket.message`, given `order.charges`?"
      }
    }
  }
}'
```

```json
{
  "model": "jev-1.13.0",
  "answers": {
    "refund_requested": {
      "type": "noul",
      "noul": 0.99
    },
    "policy_supports_refund": {
      "type": "noul",
      "noul": 0.98
    }
  },
  "usage": {
    "input_tokens": 422,
    "output_tokens": 41
  }
}
```

</details>

<details>

<summary>**Support department routing** — Route a support request to the right department</summary>



```ts
const response = await env.AI.run(
  'typesafe/jev',
  {
    state: 'I cannot log in after changing my password, and the reset email never arrives.',
    questions: {
      department: {
        type: 'choice',
        instructions: 'Which team should handle this support request?',
        criteria: {
          account: 'Login, password, profile, or security issues',
          billing: 'Charges, invoices, refunds, or subscriptions',
          technical: 'Product bugs, outages, or integrations',
          other: 'Requests that do not fit the other departments',
        },
      },
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "typesafe/jev",
  "input": {
    "state": "I cannot log in after changing my password, and the reset email never arrives.",
    "questions": {
      "department": {
        "type": "choice",
        "instructions": "Which team should handle this support request?",
        "criteria": {
          "account": "Login, password, profile, or security issues",
          "billing": "Charges, invoices, refunds, or subscriptions",
          "technical": "Product bugs, outages, or integrations",
          "other": "Requests that do not fit the other departments"
        }
      }
    }
  }
}'
```

```json
{
  "model": "jev-1.13.0",
  "answers": {
    "department": {
      "type": "choice",
      "choice": "account",
      "confidence": 1,
      "probabilities": {
        "technical": 0,
        "billing": 0,
        "account": 1,
        "other": 0
      }
    }
  },
  "usage": {
    "input_tokens": 380,
    "output_tokens": 45
  }
}
```

</details>

<details>

<summary>**Account risk assessment** — Score account risk and determine whether escalation is needed</summary>



```ts
const response = await env.AI.run(
  'typesafe/jev',
  {
    state: {
      account_age_days: 12,
      recent_events: [
        'Five failed login attempts',
        'Password reset requested from a new country',
        'Successful login from the usual device',
      ],
      account_verified: true,
    },
    questions: {
      risk_level: {
        type: 'score',
        instructions: 'How risky does this account activity appear?',
        criteria: [
          'Low risk: activity is consistent with the account history',
          'Moderate risk: some unusual activity needs monitoring',
          'High risk: multiple strong indicators of account compromise',
        ],
      },
      escalate: {
        type: 'noul',
        instructions: 'Should this account be escalated for manual security review?',
        criteria: {
          true: 'The activity warrants immediate human review',
          false: 'The activity can be handled with normal automated controls',
        },
      },
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "typesafe/jev",
  "input": {
    "state": {
      "account_age_days": 12,
      "recent_events": [
        "Five failed login attempts",
        "Password reset requested from a new country",
        "Successful login from the usual device"
      ],
      "account_verified": true
    },
    "questions": {
      "risk_level": {
        "type": "score",
        "instructions": "How risky does this account activity appear?",
        "criteria": [
          "Low risk: activity is consistent with the account history",
          "Moderate risk: some unusual activity needs monitoring",
          "High risk: multiple strong indicators of account compromise"
        ]
      },
      "escalate": {
        "type": "noul",
        "instructions": "Should this account be escalated for manual security review?",
        "criteria": {
          "true": "The activity warrants immediate human review",
          "false": "The activity can be handled with normal automated controls"
        }
      }
    }
  }
}'
```

```json
{
  "model": "jev-1.13.0",
  "answers": {
    "risk_level": {
      "type": "score",
      "score": 1.84,
      "confidence": 0.77,
      "legend": {
        "0": "Low risk: activity is consistent with the account history",
        "1": "Moderate risk: some unusual activity needs monitoring",
        "2": "High risk: multiple strong indicators of account compromise"
      },
      "probabilities": {
        "0": 0,
        "1": 0.16,
        "2": 0.84
      }
    },
    "escalate": {
      "type": "noul",
      "noul": 0.81
    }
  },
  "usage": {
    "input_tokens": 421,
    "output_tokens": 36
  }
}
```

</details>

## Parameters

▶state

`one of`required

▶questions{}

`object`required

model

`string`minLength: 1

▶answers{}

`object`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/typesafe/jev/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/typesafe/jev/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/typesafe/jev/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/typesafe/jev/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/typesafe/jev/#page","headline":"Jev","description":"Jev is TypeSafe's structured evaluation model. It evaluates one state against typed Noul, Choice, and Score questions and returns calibrated answers with probabilities and confidence.","url":"https://developers.cloudflare.com/ai/models/typesafe/jev/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Pareto is Unbiased's blended AI model. It engages multiple language models in parallel for each request, synthesizes one answer, and supports text and vision inputs through a single API response.
title: Pareto
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

u

# Pareto

Text Generation • unbiased

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/unbiased/pareto/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`unbiased/pareto`

- Third-party
- Zero data retention

Pareto is Unbiased's blended AI model. It engages multiple language models in parallel for each request, synthesizes one answer, and supports text and vision inputs through a single API response.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://unbiased.ai/terms/) |
| More information | [link ↗](https://unbiased.ai/model-card/) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$2.50</li><li>Output (per 1M tokens)$7.50</li><li>Cached input (per 1M tokens)$0.25</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'unbiased/pareto',
  {
    messages: [{ content: 'What is the capital of France? Answer in one word.', role: 'user' }],
    max_tokens: 16,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "unbiased/pareto",
  "messages": [
    {
      "content": "What is the capital of France? Answer in one word.",
      "role": "user"
    }
  ],
  "max_tokens": 16
}'
```

```
Paris
```

```json
{
  "id": "chatcmpl-mu5ww8tss0mj6ofw",
  "object": "chat.completion",
  "model": "unbiased/pareto",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Paris"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 11,
    "completion_tokens": 5,
    "total_tokens": 16,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "cost": 0.000045
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**System Guidance** — Set a helpful system role before asking a question.</summary>



```ts
const response = await env.AI.run(
  'unbiased/pareto',
  {
    messages: [
      { content: 'You explain technical topics in plain language.', role: 'system' },
      { content: 'What is an API? Explain it in two sentences.', role: 'user' },
    ],
    max_tokens: 64,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "unbiased/pareto",
  "messages": [
    {
      "content": "You explain technical topics in plain language.",
      "role": "system"
    },
    {
      "content": "What is an API? Explain it in two sentences.",
      "role": "user"
    }
  ],
  "max_tokens": 64
}'
```

```
An API (Application Programming Interface) is a set of rules that lets one software program request information or actions from another. For example, a weather app uses an API to get forecasts from a weather service.
```

```json
{
  "id": "chatcmpl-mu5wwcpm6hxi7lsb",
  "object": "chat.completion",
  "model": "unbiased/pareto",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "An API (Application Programming Interface) is a set of rules that lets one software program request information or actions from another. For example, a weather app uses an API to get forecasts from a weather service."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 19,
    "completion_tokens": 45,
    "total_tokens": 64,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "cost": 0.000305
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Coding Example** — Ask for a short coding example.</summary>



```ts
const response = await env.AI.run(
  'unbiased/pareto',
  {
    messages: [
      {
        content: 'Write a JavaScript function that reverses a string. Include one example call.',
        role: 'user',
      },
    ],
    max_tokens: 128,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "unbiased/pareto",
  "messages": [
    {
      "content": "Write a JavaScript function that reverses a string. Include one example call.",
      "role": "user"
    }
  ],
  "max_tokens": 128
}'
```

````
```javascript
function reverseString(str) {
  return Array.from(str).reverse().join("");
}

console.log(reverseString("Hello")); // "olleH"
```
````

```json
{
  "id": "chatcmpl-mu5wwj1mqcjfe7xb",
  "object": "chat.completion",
  "model": "unbiased/pareto",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "```javascript\nfunction reverseString(str) {\n  return Array.from(str).reverse().join(\"\");\n}\n\nconsole.log(reverseString(\"Hello\")); // \"olleH\"\n```"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 14,
    "completion_tokens": 37,
    "total_tokens": 51,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "cost": 0.00024875
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Follow-up Conversation** — Continue a short conversation with prior assistant context.</summary>



```ts
const response = await env.AI.run(
  'unbiased/pareto',
  {
    messages: [
      { content: 'I am planning a weekend trip to a coastal city.', role: 'user' },
      {
        content: 'Consider walkable neighborhoods, local food, and a nearby beach.',
        role: 'assistant',
      },
      { content: 'What should I prioritize when choosing where to stay?', role: 'user' },
    ],
    max_tokens: 96,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "unbiased/pareto",
  "messages": [
    {
      "content": "I am planning a weekend trip to a coastal city.",
      "role": "user"
    },
    {
      "content": "Consider walkable neighborhoods, local food, and a nearby beach.",
      "role": "assistant"
    },
    {
      "content": "What should I prioritize when choosing where to stay?",
      "role": "user"
    }
  ],
  "max_tokens": 96
}'
```

```
For a weekend trip, **prioritize location over extra amenities**—less time in transit means more time enjoying the city.

- **Close to your main plans:** Stay near the beach for a beach-focused trip, or near restaurants and sights if you’re more interested in exploring.
- **Easy transportation:** Check airport or station connections, public transit, and parking costs if you’re driving.
- **Comfort and quiet:** Recent reviews can reveal street noise, cleanliness issues
```

```json
{
  "id": "chatcmpl-mu5wwqlruoazrxij",
  "object": "chat.completion",
  "model": "unbiased/pareto",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "For a weekend trip, **prioritize location over extra amenities**—less time in transit means more time enjoying the city.\n\n- **Close to your main plans:** Stay near the beach for a beach-focused trip, or near restaurants and sights if you’re more interested in exploring.\n- **Easy transportation:** Check airport or station connections, public transit, and parking costs if you’re driving.\n- **Comfort and quiet:** Recent reviews can reveal street noise, cleanliness issues"
      },
      "finish_reason": "length"
    }
  ],
  "usage": {
    "prompt_tokens": 43,
    "completion_tokens": 96,
    "total_tokens": 139,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "cost": 0.00065375
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Generate a compact piece of creative writing.</summary>



```ts
const response = await env.AI.run(
  'unbiased/pareto',
  {
    messages: [
      { content: 'Write a four-line poem about finding light after a difficult day.', role: 'user' },
    ],
    max_tokens: 96,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "unbiased/pareto",
  "messages": [
    {
      "content": "Write a four-line poem about finding light after a difficult day.",
      "role": "user"
    }
  ],
  "max_tokens": 96
}'
```

```
The day lay heavy, stitched with shades of gray,
Until one star shone through the frayed dusk’s seam.
I set my burdens down beside the way,
And let its little light rekindle dream.
```

```json
{
  "id": "chatcmpl-mu5wx6hq2jpgslxe",
  "object": "chat.completion",
  "model": "unbiased/pareto",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The day lay heavy, stitched with shades of gray,\nUntil one star shone through the frayed dusk’s seam.\nI set my burdens down beside the way,\nAnd let its little light rekindle dream."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 46,
    "total_tokens": 58,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "cost": 0.0003025
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

▶messages\[]

`array`required

temperature

`number`minimum: 0maximum: 2

max\_tokens

`number`exclusiveMinimum: 0

max\_completion\_tokens

`number`exclusiveMinimum: 0

top\_p

`number`minimum: 0maximum: 1

frequency\_penalty

`number`minimum: -2maximum: 2

presence\_penalty

`number`minimum: -2maximum: 2

stream

`boolean`

▶stream\_options{}

`object`

▶tools\[]

`array`

tool\_choice

response\_format

▶modalities\[]

`array`

▶audio{}

`object`

reasoning\_effort

`string`Optional reasoning control; availability and accepted values are model-dependent.

id

`string`

object

`string`

created

`number`

model

`string`

▶choices\[]

`array`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/unbiased/pareto/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/unbiased/pareto/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/unbiased/pareto/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/unbiased/pareto/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/unbiased/pareto/#page","headline":"Pareto","description":"Pareto is Unbiased's blended AI model. It engages multiple language models in parallel for each request, synthesizes one answer, and supports text and vision inputs through a single API response.","url":"https://developers.cloudflare.com/ai/models/unbiased/pareto/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Vidu Q3 Pro is a high-quality video generation model supporting text-to-video, image-to-video, and start/end-frame-to-video workflows with audio and up to 16-second clips.
title: Vidu Q3 Pro
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Vidu logo](https://developers.cloudflare.com/_astro/vidu.CcN5bM2x.svg)

# Vidu Q3 Pro

Text-to-Video • Vidu

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/vidu/q3-pro/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`vidu/q3-pro`

- Third-party
- Zero data retention

Vidu Q3 Pro is a high-quality video generation model supporting text-to-video, image-to-video, and start/end-frame-to-video workflows with audio and up to 16-second clips.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.vidu.com/terms) |
| More information | [link ↗](https://www.vidu.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.125</li><li>@540p (per second)$0.05</li><li>@720p (per second)$0.125</li><li>@1080p (per second)$0.15</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'vidu/q3-pro',
  {
    prompt: 'A golden retriever running through a sunlit meadow in slow motion',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "vidu/q3-pro",
  "input": {
    "prompt": "A golden retriever running through a sunlit meadow in slow motion",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://video.cf.vidu.com/infer_64/tasks/26/0417/05/942597991691198464/creation-01/video.mp4"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**Portrait Aspect Ratio** — Vertical video for social media</summary>



```ts
const response = await env.AI.run(
  'vidu/q3-pro',
  {
    prompt:
      'A busy street in Tokyo at night with neon signs reflecting on wet pavement, rain falling',
    aspect_ratio: '9:16',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "vidu/q3-pro",
  "input": {
    "prompt": "A busy street in Tokyo at night with neon signs reflecting on wet pavement, rain falling",
    "aspect_ratio": "9:16",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://video.cf.vidu.com/infer_88/tasks/26/0417/05/942598607041753088/creation-01/video.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Silent Video** — Generate video without audio</summary>



```ts
const response = await env.AI.run(
  'vidu/q3-pro',
  {
    audio: false,
    prompt: 'Abstract paint swirls slowly mixing in water, vivid blues and golds',
    duration: 8,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "vidu/q3-pro",
  "input": {
    "audio": false,
    "prompt": "Abstract paint swirls slowly mixing in water, vivid blues and golds",
    "duration": 8,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://video.cf.vidu.com/infer_76/tasks/26/0417/05/942599305355595776/creation-01/final_video.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Square Format** — Square video for product demos or social posts</summary>



```ts
const response = await env.AI.run(
  'vidu/q3-pro',
  {
    prompt:
      'A sleek wireless headphone rotating on a pedestal with soft studio lighting and a white background',
    aspect_ratio: '1:1',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "vidu/q3-pro",
  "input": {
    "prompt": "A sleek wireless headphone rotating on a pedestal with soft studio lighting and a white background",
    "aspect_ratio": "1:1",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://video.cf.vidu.com/infer_40/tasks/26/0417/05/942599364482723840/creation-01/video.mp4"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`maxLength: 5000Text prompt describing what should appear in the video

start\_image

`string`Start image for video generation. Use alone for image-to-video, or with end\_image for start/end-to-video. Accepts public URL or Base64 data URI (data:image/png;base64,...)

end\_image

`string`End image for start/end-to-video generation. Must be used together with start\_image. Accepts public URL or Base64 data URI (data:image/png;base64,...)

duration

`integer`requireddefault: 5minimum: 1maximum: 16Video duration in seconds (1-16)

resolution

`string`requireddefault: 720penum: 540p, 720p, 1080pVideo resolution

audio

`boolean`Enable audio-video synchronization. Default: true for Q3 models. When false, outputs silent video

aspect\_ratio

`string`enum: 16:9, 9:16, 3:4, 4:3, 1:1Video aspect ratio (text-to-video only). Default: 16:9

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/vidu/q3-pro/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/vidu/q3-pro/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/vidu/q3-pro/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/vidu/q3-pro/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/vidu/q3-pro/#page","headline":"Vidu Q3 Pro","description":"Vidu Q3 Pro is a high-quality video generation model supporting text-to-video, image-to-video, and start/end-frame-to-video workflows with audio and up to 16-second clips.","url":"https://developers.cloudflare.com/ai/models/vidu/q3-pro/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Vidu Q3 Turbo is a faster version of Vidu Q3 optimized for lower latency video generation while maintaining audio support and up to 16-second clips.
title: Vidu Q3 Turbo
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![Vidu logo](https://developers.cloudflare.com/_astro/vidu.CcN5bM2x.svg)

# Vidu Q3 Turbo

Text-to-Video • Vidu

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/vidu/q3-turbo/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`vidu/q3-turbo`

- Third-party
- Zero data retention

Vidu Q3 Turbo is a faster version of Vidu Q3 optimized for lower latency video generation while maintaining audio support and up to 16-second clips.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://www.vidu.com/terms) |
| More information | [link ↗](https://www.vidu.com/) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.06</li><li>@540p (per second)$0.04</li><li>@720p (per second)$0.06</li><li>@1080p (per second)$0.07</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'vidu/q3-turbo',
  { prompt: 'A cat lazily stretching on a sunlit windowsill', duration: 5, resolution: '720p' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "vidu/q3-turbo",
  "input": {
    "prompt": "A cat lazily stretching on a sunlit windowsill",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://video.cf.vidu.com/infer_28/tasks/26/0417/05/942602832110972928/creation-01/video.mp4"
  },
  "state": "Completed"
}
```

## Examples

<details>

<summary>**High Resolution** — Generate at 1080p</summary>



```ts
const response = await env.AI.run(
  'vidu/q3-turbo',
  {
    prompt:
      'Close-up of a hummingbird feeding from a vibrant red flower, slow motion with soft bokeh background',
    duration: 5,
    resolution: '1080p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "vidu/q3-turbo",
  "input": {
    "prompt": "Close-up of a hummingbird feeding from a vibrant red flower, slow motion with soft bokeh background",
    "duration": 5,
    "resolution": "1080p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://video.cf.vidu.com/infer_44/tasks/26/0417/05/942602894400569344/creation-01/video.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Portrait Video** — Vertical video for mobile viewing</summary>



```ts
const response = await env.AI.run(
  'vidu/q3-turbo',
  {
    prompt: 'A waterfall cascading down mossy rocks in a tropical jungle, mist rising',
    aspect_ratio: '9:16',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "vidu/q3-turbo",
  "input": {
    "prompt": "A waterfall cascading down mossy rocks in a tropical jungle, mist rising",
    "aspect_ratio": "9:16",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://video.cf.vidu.com/infer_48/tasks/26/0417/05/942603057143758848/creation-01/video.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Extended Duration** — Longer video clip</summary>



```ts
const response = await env.AI.run(
  'vidu/q3-turbo',
  {
    prompt:
      'Timelapse of clouds rolling over a mountain peak from sunrise to sunset, dramatic lighting',
    duration: 16,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "vidu/q3-turbo",
  "input": {
    "prompt": "Timelapse of clouds rolling over a mountain peak from sunrise to sunset, dramatic lighting",
    "duration": 16,
    "resolution": "720p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://video.cf.vidu.com/infer_84/tasks/26/0417/06/942603162785705984/creation-01/video.mp4"
  },
  "state": "Completed"
}
```

</details>

<details>

<summary>**Low Resolution Fast Preview** — Quick preview at 540p</summary>



```ts
const response = await env.AI.run(
  'vidu/q3-turbo',
  {
    prompt: 'A sailboat gliding across calm ocean waters at sunset',
    duration: 3,
    resolution: '540p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "vidu/q3-turbo",
  "input": {
    "prompt": "A sailboat gliding across calm ocean waters at sunset",
    "duration": 3,
    "resolution": "540p"
  }
}'
```

```json
{
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "result": {
    "video": "https://video.cf.vidu.com/infer_68/tasks/26/0417/06/942603796612128768/creation-01/video.mp4"
  },
  "state": "Completed"
}
```

</details>

## Parameters

prompt

`string`maxLength: 5000Text prompt describing what should appear in the video

start\_image

`string`Start image for video generation. Use alone for image-to-video, or with end\_image for start/end-to-video. Accepts public URL or Base64 data URI (data:image/png;base64,...)

end\_image

`string`End image for start/end-to-video generation. Must be used together with start\_image. Accepts public URL or Base64 data URI (data:image/png;base64,...)

duration

`integer`requireddefault: 5minimum: 1maximum: 16Video duration in seconds (1-16)

resolution

`string`requireddefault: 720penum: 540p, 720p, 1080pVideo resolution

audio

`boolean`Enable audio-video synchronization. Default: true for Q3 models. When false, outputs silent video

aspect\_ratio

`string`enum: 16:9, 9:16, 3:4, 4:3, 1:1Video aspect ratio (text-to-video only). Default: 16:9

video

`string`format: uriURL to the generated video

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/vidu/q3-turbo/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/vidu/q3-turbo/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/vidu/q3-turbo/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/vidu/q3-turbo/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/vidu/q3-turbo/#page","headline":"Vidu Q3 Turbo","description":"Vidu Q3 Turbo is a faster version of Vidu Q3 optimized for lower latency video generation while maintaining audio support and up to 16-second clips.","url":"https://developers.cloudflare.com/ai/models/vidu/q3-turbo/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's Grok 4.20 non-reasoning model. Skips the thinking trace for fast, single-pass responses while keeping the same training as the reasoning variant.
title: Grok 4.20 Non-Reasoning
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok 4.20 Non-Reasoning

Text Generation • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-non-reasoning/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-4.20-0309-non-reasoning`

- Third-party
- Zero data retention

xAI's Grok 4.20 non-reasoning model. Skips the thinking trace for fast, single-pass responses while keeping the same training as the reasoning variant.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 2,000,000 tokens |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://x.ai/) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Output (per 1M tokens)$6.00</li><li>Cached input (per 1M tokens)$0.20</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-4.20-0309-non-reasoning',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-non-reasoning",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
**The Three Laws of Thermodynamics** (in their most common, concise form):

### **Zeroth Law of Thermodynamics** (often called the "zeroth" because it logically precedes the others)
> If two systems are each in thermal equilibrium with a third system, then they are in thermal equilibrium with each other.

This is the basis for the concept of **temperature** — it allows us to define a universal temperature scale.

### **First Law of Thermodynamics**
> Energy cannot be created or destroyed, only converted from one form to another.

Mathematically:  
**ΔU = Q − W**  
(where ΔU is the change in internal energy, Q is heat added to the system, and W is work done *by* the system)

This is essentially the **law of conservation of energy** applied to thermodynamic systems.

### **Second Law of Thermodynamics**
> The entropy of an isolated system always increases over time, or remains constant in ideal reversible processes. Heat flows spontaneously from hot to cold, never the reverse.

Common statements:
- "The entropy of the universe tends to a maximum."
- "It is impossible to construct a heat engine that is 100% efficient."

This law introduces the concept of **irreversibility** and the **arrow of time**.

---

### Bonus: The **Third Law of Thermodynamics** (Nernst Heat Theorem)
> As the temperature of a system approaches absolute zero (0 K), the entropy of a perfect crystal approaches a minimum (usually zero).

This implies it's impossible to reach absolute zero in a finite number of steps.

---

**Summary (popular phrasing):**
1. **Zeroth**: Temperature exists.
2. **First**: You can't win (energy is conserved).
3. **Second**: You can't break even (entropy always increases).
4. **Third**: You can't even quit the game (absolute zero is unreachable).
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "**The Three Laws of Thermodynamics** (in their most common, concise form):\n\n### **Zeroth Law of Thermodynamics** (often called the \"zeroth\" because it logically precedes the others)\n> If two systems are each in thermal equilibrium with a third system, then they are in thermal equilibrium with each other.\n\nThis is the basis for the concept of **temperature** — it allows us to define a universal temperature scale.\n\n### **First Law of Thermodynamics**\n> Energy cannot be created or destroyed, only converted from one form to another.\n\nMathematically:  \n**ΔU = Q − W**  \n(where ΔU is the change in internal energy, Q is heat added to the system, and W is work done *by* the system)\n\nThis is essentially the **law of conservation of energy** applied to thermodynamic systems.\n\n### **Second Law of Thermodynamics**\n> The entropy of an isolated system always increases over time, or remains constant in ideal reversible processes. Heat flows spontaneously from hot to cold, never the reverse.\n\nCommon statements:\n- \"The entropy of the universe tends to a maximum.\"\n- \"It is impossible to construct a heat engine that is 100% efficient.\"\n\nThis law introduces the concept of **irreversibility** and the **arrow of time**.\n\n---\n\n### Bonus: The **Third Law of Thermodynamics** (Nernst Heat Theorem)\n> As the temperature of a system approaches absolute zero (0 K), the entropy of a perfect crystal approaches a minimum (usually zero).\n\nThis implies it's impossible to reach absolute zero in a finite number of steps.\n\n---\n\n**Summary (popular phrasing):**\n1. **Zeroth**: Temperature exists.\n2. **First**: You can't win (energy is conserved).\n3. **Second**: You can't break even (entropy always increases).\n4. **Third**: You can't even quit the game (absolute zero is unreachable).",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777675694,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "ad22f976-34a4-e1f2-5d44-2c6b9c2fb9e5",
  "model": "grok-4.20-0309-non-reasoning",
  "object": "chat.completion",
  "system_fingerprint": "fp_bdeb03b7cd",
  "usage": {
    "completion_tokens": 378,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 10403000,
    "num_sources_used": 0,
    "prompt_tokens": 130,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 64,
      "image_tokens": 0,
      "text_tokens": 130
    },
    "total_tokens": 508
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-0309-non-reasoning',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-non-reasoning",
  "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"
    }
  ]
}'
```

````
**Reading a JSON file in Python** is very straightforward using the built-in `json` module.

### 1. Basic Method (Recommended)

```python
import json
from pathlib import Path

# Method 1: Using pathlib (modern and clean)
def read_json_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    return data

# Usage
data = read_json_file('data.json')
print(data)
```

### 2. Most Common Patterns

```python
import json

# Option 1: Using pathlib (Recommended)
data = json.loads(Path('data.json').read_text(encoding='utf-8'))

# Option 2: Traditional way
with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# Option 3: One-liner
data = json.load(open('data.json', encoding='utf-8'))
```

### 3. Complete Example with Error Handling

```python
import json
from pathlib import Path
from typing import Any

def read_json(file_path: str | Path) -> Any:
    """Safely read a JSON file with proper error handling."""
    try:
        path = Path(file_path)
        with open(path, 'r', encoding='utf-8') as file:
            return json.load(file)
            
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
        return None
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON in '{file_path}': {e}")
        return None
    except Exception as e:
        print(f"Unexpected error reading '{file_path}': {e}")
        return None


# Usage examples:
data = read_json('config.json')
data = read_json(Path('data/settings.json'))

# Access the data
if data:
    print(data.get('name'))
    print(data['users'][0]['email'])
```

### Key Points:

- Use `json.load()` when reading from a **file object**
- Use `json.loads()` when reading from a **string**
- Always specify `encoding='utf-8'` (best practice)
- Use `pathlib.Path` for modern Python code
- Always handle potential `JSONDecodeError` and `FileNotFoundError`

Would you like to see how to also **write** JSON files or work with specific JSON structures (like configurations, lists of objects, etc.)?
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "**Reading a JSON file in Python** is very straightforward using the built-in `json` module.\n\n### 1. Basic Method (Recommended)\n\n```python\nimport json\nfrom pathlib import Path\n\n# Method 1: Using pathlib (modern and clean)\ndef read_json_file(file_path):\n    with open(file_path, 'r', encoding='utf-8') as file:\n        data = json.load(file)\n    return data\n\n# Usage\ndata = read_json_file('data.json')\nprint(data)\n```\n\n### 2. Most Common Patterns\n\n```python\nimport json\n\n# Option 1: Using pathlib (Recommended)\ndata = json.loads(Path('data.json').read_text(encoding='utf-8'))\n\n# Option 2: Traditional way\nwith open('data.json', 'r', encoding='utf-8') as f:\n    data = json.load(f)\n\n# Option 3: One-liner\ndata = json.load(open('data.json', encoding='utf-8'))\n```\n\n### 3. Complete Example with Error Handling\n\n```python\nimport json\nfrom pathlib import Path\nfrom typing import Any\n\ndef read_json(file_path: str | Path) -> Any:\n    \"\"\"Safely read a JSON file with proper error handling.\"\"\"\n    try:\n        path = Path(file_path)\n        with open(path, 'r', encoding='utf-8') as file:\n            return json.load(file)\n            \n    except FileNotFoundError:\n        print(f\"Error: File '{file_path}' not found.\")\n        return None\n    except json.JSONDecodeError as e:\n        print(f\"Error: Invalid JSON in '{file_path}': {e}\")\n        return None\n    except Exception as e:\n        print(f\"Unexpected error reading '{file_path}': {e}\")\n        return None\n\n\n# Usage examples:\ndata = read_json('config.json')\ndata = read_json(Path('data/settings.json'))\n\n# Access the data\nif data:\n    print(data.get('name'))\n    print(data['users'][0]['email'])\n```\n\n### Key Points:\n\n- Use `json.load()` when reading from a **file object**\n- Use `json.loads()` when reading from a **string**\n- Always specify `encoding='utf-8'` (best practice)\n- Use `pathlib.Path` for modern Python code\n- Always handle potential `JSONDecodeError` and `FileNotFoundError`\n\nWould you like to see how to also **write** JSON files or work with specific JSON structures (like configurations, lists of objects, etc.)?",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777675694,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "90c95869-a6c3-9a03-95d1-32f6a41a14ca",
  "model": "grok-4.20-0309-non-reasoning",
  "object": "chat.completion",
  "system_fingerprint": "fp_bdeb03b7cd",
  "usage": {
    "completion_tokens": 521,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 14165500,
    "num_sources_used": 0,
    "prompt_tokens": 145,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 64,
      "image_tokens": 0,
      "text_tokens": 145
    },
    "total_tokens": 666
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-0309-non-reasoning',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-non-reasoning",
  "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"
    }
  ]
}'
```

```
Here are some excellent stops along (or just off) the main routes from San Francisco to Los Angeles. I’ve grouped them roughly in north-to-south order so you can slot them into your itinerary easily.

### Classic Coastal Route (Highway 1 / Pacific Coast Highway)
This is the most scenic option and the one most people picture when they say “road trip from SF to LA.”

1. **Half Moon Bay** (≈ 30 min south of SF)  
   - Cute coastal town with beaches, tide pools, and the famous “Pumpkin Festival” in October. Great for a quick coffee or beach walk.

2. **Pescadero & Año Nuevo State Park** (≈ 1 hr from SF)  
   - Stop at **Duarte’s Tavern** for artichoke soup and pie. Año Nuevo has elephant seals (best Dec–March).

3. **Santa Cruz** (≈ 1.5 hrs from SF)  
   - Beach Boardwalk, redwood hikes in Henry Cowell Redwoods, or the famous surf at Pleasure Point. Good food scene.

4. **Monterey & Pacific Grove** (≈ 2 hrs from SF)  
   - Cannery Row, Monterey Bay Aquarium (book ahead), 17-Mile Drive, and the monarch butterfly sanctuary in Pacific Grove (Oct–Feb).

5. **Big Sur** (≈ 3–4 hrs from SF – the heart of the drive)  
   - **Bixby Bridge** photo stop  
   - **Point Sur Lighthouse** (tours available)  
   - **Julia Pfeiffer Burns State Park** – McWay Falls (waterfall onto the beach)  
   - **Pfeiffer Beach** – purple sand and keyhole rock  
   - **Nepenthe** or **Big Sur Bakery** for lunch with a view  
   - **Ventana Big Sur** or **Post Ranch Inn** if you want an upscale overnight.

6. **Cambria / Hearst Castle** (≈ 5–6 hrs from SF)  
   - Tour the famous Hearst Castle (reservations required).  
   - Moonstone Beach boardwalk for sunset.

7. **San Luis Obispo (SLO)** (≈ 6.5 hrs from SF)  
   - Bubblegum Alley, great farm-to-table food, and a lively downtown.

8. **Pismo Beach**  
   - Classic California beach town with sand dunes you can drive on (ATV tours available).

9. **Solvang** (short detour)  
   - Danish-themed village with windmills, bakeries, and Æbleskiver pancakes. Fun for 1–2 hours.

10. **Santa Barbara** (≈ 8–9 hrs from SF if you linger)  
    - “American Riviera.” State Street for shopping, Mission Santa Barbara, beaches, and wine tasting in the Funk Zone.

11. **Malibu** (final stretch before LA)  
    - Point Dume, El Matador Beach, or a sunset dinner at Malibu Pier.

### Inland / Faster Route Highlights (I-5 corridor)
If you’re short on time but still want stops:

- **Gilroy** – “Garlic Capital of the World” (garlic ice cream if you’re brave).
- **Pacheco Pass** → **San Luis Reservoir** for dramatic views.
- **Harris Ranch** – iconic Central Valley steakhouse stop.
- **Bakersfield** – for Basque food or country-music vibes.
- **Tejon Pass / Magic Mountain** – quick amusement-park option.

### Suggested Itineraries

**Scenic 2-Day Trip (most popular)**  
Day 1: SF → Big Sur (overnight in Big Sur or Cambria)  
Day 2: Big Sur → Santa Barbara → LA

**3-Day Leisure Trip**  
Day 1: SF → Monterey / Carmel (overnight)  
Day 2: Monterey → Cambria / Hearst Castle → SLO (overnight)  
Day 3: SLO → Santa Barbara → Malibu → LA

Would you like me to:
- Build a day-by-day itinerary with driving times and restaurant recommendations?
- Focus on specific interests (hiking, food, photography, wine, budget, luxury, etc.)?
- Include where to stay or current road conditions / permit info for Big Sur?

Just let me know your preferences (how many days, budget level, must-see activities, etc.) and I’ll tailor it further!
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "Here are some excellent stops along (or just off) the main routes from San Francisco to Los Angeles. I’ve grouped them roughly in north-to-south order so you can slot them into your itinerary easily.\n\n### Classic Coastal Route (Highway 1 / Pacific Coast Highway)\nThis is the most scenic option and the one most people picture when they say “road trip from SF to LA.”\n\n1. **Half Moon Bay** (≈ 30 min south of SF)  \n   - Cute coastal town with beaches, tide pools, and the famous “Pumpkin Festival” in October. Great for a quick coffee or beach walk.\n\n2. **Pescadero & Año Nuevo State Park** (≈ 1 hr from SF)  \n   - Stop at **Duarte’s Tavern** for artichoke soup and pie. Año Nuevo has elephant seals (best Dec–March).\n\n3. **Santa Cruz** (≈ 1.5 hrs from SF)  \n   - Beach Boardwalk, redwood hikes in Henry Cowell Redwoods, or the famous surf at Pleasure Point. Good food scene.\n\n4. **Monterey & Pacific Grove** (≈ 2 hrs from SF)  \n   - Cannery Row, Monterey Bay Aquarium (book ahead), 17-Mile Drive, and the monarch butterfly sanctuary in Pacific Grove (Oct–Feb).\n\n5. **Big Sur** (≈ 3–4 hrs from SF – the heart of the drive)  \n   - **Bixby Bridge** photo stop  \n   - **Point Sur Lighthouse** (tours available)  \n   - **Julia Pfeiffer Burns State Park** – McWay Falls (waterfall onto the beach)  \n   - **Pfeiffer Beach** – purple sand and keyhole rock  \n   - **Nepenthe** or **Big Sur Bakery** for lunch with a view  \n   - **Ventana Big Sur** or **Post Ranch Inn** if you want an upscale overnight.\n\n6. **Cambria / Hearst Castle** (≈ 5–6 hrs from SF)  \n   - Tour the famous Hearst Castle (reservations required).  \n   - Moonstone Beach boardwalk for sunset.\n\n7. **San Luis Obispo (SLO)** (≈ 6.5 hrs from SF)  \n   - Bubblegum Alley, great farm-to-table food, and a lively downtown.\n\n8. **Pismo Beach**  \n   - Classic California beach town with sand dunes you can drive on (ATV tours available).\n\n9. **Solvang** (short detour)  \n   - Danish-themed village with windmills, bakeries, and Æbleskiver pancakes. Fun for 1–2 hours.\n\n10. **Santa Barbara** (≈ 8–9 hrs from SF if you linger)  \n    - “American Riviera.” State Street for shopping, Mission Santa Barbara, beaches, and wine tasting in the Funk Zone.\n\n11. **Malibu** (final stretch before LA)  \n    - Point Dume, El Matador Beach, or a sunset dinner at Malibu Pier.\n\n### Inland / Faster Route Highlights (I-5 corridor)\nIf you’re short on time but still want stops:\n\n- **Gilroy** – “Garlic Capital of the World” (garlic ice cream if you’re brave).\n- **Pacheco Pass** → **San Luis Reservoir** for dramatic views.\n- **Harris Ranch** – iconic Central Valley steakhouse stop.\n- **Bakersfield** – for Basque food or country-music vibes.\n- **Tejon Pass / Magic Mountain** – quick amusement-park option.\n\n### Suggested Itineraries\n\n**Scenic 2-Day Trip (most popular)**  \nDay 1: SF → Big Sur (overnight in Big Sur or Cambria)  \nDay 2: Big Sur → Santa Barbara → LA\n\n**3-Day Leisure Trip**  \nDay 1: SF → Monterey / Carmel (overnight)  \nDay 2: Monterey → Cambria / Hearst Castle → SLO (overnight)  \nDay 3: SLO → Santa Barbara → Malibu → LA\n\nWould you like me to:\n- Build a day-by-day itinerary with driving times and restaurant recommendations?\n- Focus on specific interests (hiking, food, photography, wine, budget, luxury, etc.)?\n- Include where to stay or current road conditions / permit info for Big Sur?\n\nJust let me know your preferences (how many days, budget level, must-see activities, etc.) and I’ll tailor it further!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777675700,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "4eb7a1aa-c8a6-9b80-96e0-b49fe3efbb1d",
  "model": "grok-4.20-0309-non-reasoning",
  "object": "chat.completion",
  "system_fingerprint": "fp_bdeb03b7cd",
  "usage": {
    "completion_tokens": 915,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 24578000,
    "num_sources_used": 0,
    "prompt_tokens": 190,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 64,
      "image_tokens": 0,
      "text_tokens": 190
    },
    "total_tokens": 1105
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-0309-non-reasoning',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-non-reasoning",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
The rain-slicked alley behind the old theater smelled of rotting velvet and gunpowder. Detective Elias Crowe knelt beside the body, his flashlight beam cutting through the downpour, and paused.

There, clutched in the dead man’s rigid fingers, was a single playing card: the Queen of Hearts. That wasn’t unusual in itself. What stopped Crowe cold was that the card was warm, almost hot, as though it had just come off a printing press. And when he turned it over, the back wasn’t patterned with the usual bicycles or fleurs-de-lis.

It was a tiny, perfectly detailed photograph of the crime scene itself, taken from an angle that should have been impossible—directly above the body, as if the card had been watching the murder happen.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "The rain-slicked alley behind the old theater smelled of rotting velvet and gunpowder. Detective Elias Crowe knelt beside the body, his flashlight beam cutting through the downpour, and paused.\n\nThere, clutched in the dead man’s rigid fingers, was a single playing card: the Queen of Hearts. That wasn’t unusual in itself. What stopped Crowe cold was that the card was warm, almost hot, as though it had just come off a printing press. And when he turned it over, the back wasn’t patterned with the usual bicycles or fleurs-de-lis.\n\nIt was a tiny, perfectly detailed photograph of the crime scene itself, taken from an angle that should have been impossible—directly above the body, as if the card had been watching the murder happen.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777675700,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "ffb95915-83b7-ac06-34d9-f031b0056ab1",
  "model": "grok-4.20-0309-non-reasoning",
  "object": "chat.completion",
  "system_fingerprint": "fp_bdeb03b7cd",
  "usage": {
    "completion_tokens": 154,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 4865500,
    "num_sources_used": 0,
    "prompt_tokens": 135,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 64,
      "image_tokens": 0,
      "text_tokens": 135
    },
    "total_tokens": 289
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-0309-non-reasoning',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-non-reasoning",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
**Recursion** is a programming concept where a function **calls itself** to solve a smaller version of the same problem.

It's like solving a big problem by repeatedly breaking it down into smaller, identical problems until you reach a simple case that can be solved directly.

---

### Simple Example: Factorial

The **factorial** of a number `n` (written as `n!`) is:
- `5! = 5 × 4 × 3 × 2 × 1 = 120`

We can define factorial recursively:

### Recursive Definition:
- `factorial(n) = n × factorial(n-1)`    ← recursive case
- `factorial(0) = 1`                     ← **base case** (stops the recursion)

---

### Code Example (Python):

```python
def factorial(n):
    # Base case: stop recursion
    if n == 0 or n == 1:
        return 1
    # Recursive case: call itself with a smaller number
    else:
        return n * factorial(n - 1)


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

---

### How it works step by step:

When you call `factorial(5)`:

```
factorial(5) = 5 × factorial(4)
             = 5 × (4 × factorial(3))
             = 5 × (4 × (3 × factorial(2)))
             = 5 × (4 × (3 × (2 × factorial(1))))
             = 5 × (4 × (3 × (2 × 1)))     ← base case reached
             = 120
```

Each recursive call creates a new "layer" until it hits the base case, then it starts returning values back up the chain.

---

### Key Parts of Recursion:
1. **Base Case** – The simplest case that can be solved directly (stops infinite recursion).
2. **Recursive Case** – The function calls itself with a simpler/smaller input.

---

Would you like me to also show a visual example using a stack or another common recursive example like counting down or summing numbers?
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "content": "**",
          "role": "assistant"
        },
        "index": 0
      }
    ],
    "created": 1777679681,
    "id": "f987889c-ee9b-97a6-9c83-c687c444bbfb",
    "model": "grok-4.20-0309-non-reasoning",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_bdeb03b7cd"
  },
  {
    "choices": [
      {
        "delta": {
          "content": "Recursion"
        },
        "index": 0
      }
    ],
    "created": 1777679681,
    "id": "f987889c-ee9b-97a6-9c83-c687c444bbfb",
    "model": "grok-4.20-0309-non-reasoning",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_bdeb03b7cd"
  },
  "... 440 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777679685,
    "id": "f987889c-ee9b-97a6-9c83-c687c444bbfb",
    "model": "grok-4.20-0309-non-reasoning",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_bdeb03b7cd",
    "usage": {
      "completion_tokens": 441,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "cost_in_usd_ticks": 12003000,
      "num_sources_used": 0,
      "prompt_tokens": 132,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 64,
        "image_tokens": 0,
        "text_tokens": 132
      },
      "total_tokens": 573
    }
  }
]
```

</details>

## Parameters

▶messages\[]

`array`requiredminItems: 1maxItems: 500

deferred

`boolean`

frequency\_penalty

`number | null`

logprobs

`boolean`

max\_completion\_tokens

`integer | null`

max\_tokens

`integer | null`

n

`integer | null`

parallel\_tool\_calls

`boolean`

presence\_penalty

`number | null`

reasoning\_effort

`string | null`enum: low, high

▶response\_format

`one of`

▶search\_parameters{}

`object`

seed

`integer | null`

stop

`array | null`

stream

`boolean`

▶stream\_options{}

`object`

temperature

`number | null`

▶tool\_choice

`one of`

tools

`array | null`

top\_logprobs

`integer | null`

top\_p

`number | null`

user

`string`

▶web\_search\_options{}

`object`

id

`string`

object

`string`const: chat.completion

created

`number`

model

`string`

▶choices\[]

`array`

citations

`array | null`

output\_files

`array | null`

system\_fingerprint

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-non-reasoning/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-non-reasoning/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-non-reasoning/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-non-reasoning/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-non-reasoning/#page","headline":"Grok 4.20 Non-Reasoning","description":"xAI's Grok 4.20 non-reasoning model. Skips the thinking trace for fast, single-pass responses while keeping the same training as the reasoning variant.","url":"https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-non-reasoning/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's Grok 4.20 reasoning model. Uses extended thinking to work through complex problems, returning a reasoning trace alongside the final answer.
title: Grok 4.20 Reasoning
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok 4.20 Reasoning

Text Generation • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-reasoning/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-4.20-0309-reasoning`

- Third-party
- Zero data retention

xAI's Grok 4.20 reasoning model. Uses extended thinking to work through complex problems, returning a reasoning trace alongside the final answer.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 2,000,000 tokens |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://x.ai/) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Output (per 1M tokens)$6.00</li><li>Cached input (per 1M tokens)$0.20</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-4.20-0309-reasoning',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-reasoning",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
**The Three Laws of Thermodynamics** (in plain language):

### 1. First Law (Conservation of Energy)
**Energy cannot be created or destroyed — only converted from one form to another.**

- In equation form: **ΔU = Q − W**
  - ΔU = change in the system’s internal energy
  - Q = heat added to the system
  - W = work done *by* the system

This is basically the law of conservation of energy applied to thermodynamic systems. If you add heat to a gas, that energy has to go somewhere — it can increase the gas’s temperature (internal energy) or be used to push a piston (work).

### 2. Second Law (Entropy and Directionality)
**The entropy (disorder) of an isolated system always increases over time.**

Key implications:
- Heat flows spontaneously from hot to cold, never the reverse.
- It is impossible to build a perfectly efficient heat engine (some energy is always “wasted” as heat).
- Processes have a natural direction; time has an arrow.

Popular statement: “You can’t even break even.” Every real process increases the total entropy of the universe.

### 3. Third Law (Absolute Zero)
**As the temperature of a system approaches absolute zero (0 K or −273.15 °C), its entropy approaches a minimum value (often zero for a perfect crystal).**

Key consequences:
- It is impossible to reach absolute zero in a finite number of steps.
- Many materials exhibit strange quantum behaviors near 0 K (superconductivity, superfluidity, etc.).

---

### Bonus: The Zeroth Law (The “Temperature Law”)
Although not one of the original three, it’s so fundamental it was named *after* them:

**If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.**

This is what allows us to define temperature and use thermometers.

Would you like a more technical/deep-dive version of any of these laws?
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "**The Three Laws of Thermodynamics** (in plain language):\n\n### 1. First Law (Conservation of Energy)\n**Energy cannot be created or destroyed — only converted from one form to another.**\n\n- In equation form: **ΔU = Q − W**\n  - ΔU = change in the system’s internal energy\n  - Q = heat added to the system\n  - W = work done *by* the system\n\nThis is basically the law of conservation of energy applied to thermodynamic systems. If you add heat to a gas, that energy has to go somewhere — it can increase the gas’s temperature (internal energy) or be used to push a piston (work).\n\n### 2. Second Law (Entropy and Directionality)\n**The entropy (disorder) of an isolated system always increases over time.**\n\nKey implications:\n- Heat flows spontaneously from hot to cold, never the reverse.\n- It is impossible to build a perfectly efficient heat engine (some energy is always “wasted” as heat).\n- Processes have a natural direction; time has an arrow.\n\nPopular statement: “You can’t even break even.” Every real process increases the total entropy of the universe.\n\n### 3. Third Law (Absolute Zero)\n**As the temperature of a system approaches absolute zero (0 K or −273.15 °C), its entropy approaches a minimum value (often zero for a perfect crystal).**\n\nKey consequences:\n- It is impossible to reach absolute zero in a finite number of steps.\n- Many materials exhibit strange quantum behaviors near 0 K (superconductivity, superfluidity, etc.).\n\n---\n\n### Bonus: The Zeroth Law (The “Temperature Law”)\nAlthough not one of the original three, it’s so fundamental it was named *after* them:\n\n**If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.**\n\nThis is what allows us to define temperature and use thermometers.\n\nWould you like a more technical/deep-dive version of any of these laws?",
        "reasoning_content": "The question is: \"What are the three laws of thermodynamics?\"\nI know the three laws of thermodynamics are key principles in physics that govern energy, heat, and work in systems. The first law is about conservation of energy, stating that energy can't be created or destroyed, only transformed.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777675707,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "7725e484-a7ee-ce42-45e7-89022b16e9ac",
  "model": "grok-4.20-0309-reasoning",
  "object": "chat.completion",
  "system_fingerprint": "fp_7be90dd558",
  "usage": {
    "completion_tokens": 411,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 382,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 20803000,
    "num_sources_used": 0,
    "prompt_tokens": 132,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 64,
      "image_tokens": 0,
      "text_tokens": 132
    },
    "total_tokens": 925
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-0309-reasoning',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-reasoning",
  "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"
    }
  ]
}'
```

````
**Best way to read a JSON file in Python:**

### Method 1: Using `json.load()` (Recommended)

```python
import json
from pathlib import Path

# Method A: Using pathlib (modern and clean)
def read_json(file_path: str | Path):
    path = Path(file_path)
    with path.open('r', encoding='utf-8') as file:
        return json.load(file)

# Usage
data = read_json('data.json')
print(data)
```

### Method 2: Simple version (most common)

```python
import json

with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)

print(data)
```

---

### Complete Example

```python
import json
from pathlib import Path
from typing import Any

def load_json(file_path: str | Path) -> dict | list:
    """Safely load a JSON file."""
    try:
        path = Path(file_path)
        with path.open('r', encoding='utf-8') as file:
            return json.load(file)
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
        return {}
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON in '{file_path}': {e}")
        return {}
    except Exception as e:
        print(f"Unexpected error: {e}")
        return {}

# Usage
data = load_json('config.json')

# Access the data
if isinstance(data, dict):
    print(data.get('name'))
    print(data.get('settings', {}))
```

---

### Key Points:

- **`json.load()`** → reads from a **file object**
- **`json.loads()`** → reads from a **string** (note the 's')
- Always specify `encoding='utf-8'` to avoid encoding issues
- Use `pathlib.Path` for better path handling (recommended in modern Python)

---

### Bonus: One-liner (for quick scripts)

```python
import json
data = json.loads(Path('data.json').read_text(encoding='utf-8'))
```

Would you like me to also show how to:
- Read JSON from a URL?
- Handle very large JSON files?
- Write JSON files?
- Use `pydantic` or `dataclasses` with JSON?
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "**Best way to read a JSON file in Python:**\n\n### Method 1: Using `json.load()` (Recommended)\n\n```python\nimport json\nfrom pathlib import Path\n\n# Method A: Using pathlib (modern and clean)\ndef read_json(file_path: str | Path):\n    path = Path(file_path)\n    with path.open('r', encoding='utf-8') as file:\n        return json.load(file)\n\n# Usage\ndata = read_json('data.json')\nprint(data)\n```\n\n### Method 2: Simple version (most common)\n\n```python\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n---\n\n### Complete Example\n\n```python\nimport json\nfrom pathlib import Path\nfrom typing import Any\n\ndef load_json(file_path: str | Path) -> dict | list:\n    \"\"\"Safely load a JSON file.\"\"\"\n    try:\n        path = Path(file_path)\n        with path.open('r', encoding='utf-8') as file:\n            return json.load(file)\n    except FileNotFoundError:\n        print(f\"Error: File '{file_path}' not found.\")\n        return {}\n    except json.JSONDecodeError as e:\n        print(f\"Error: Invalid JSON in '{file_path}': {e}\")\n        return {}\n    except Exception as e:\n        print(f\"Unexpected error: {e}\")\n        return {}\n\n# Usage\ndata = load_json('config.json')\n\n# Access the data\nif isinstance(data, dict):\n    print(data.get('name'))\n    print(data.get('settings', {}))\n```\n\n---\n\n### Key Points:\n\n- **`json.load()`** → reads from a **file object**\n- **`json.loads()`** → reads from a **string** (note the 's')\n- Always specify `encoding='utf-8'` to avoid encoding issues\n- Use `pathlib.Path` for better path handling (recommended in modern Python)\n\n---\n\n### Bonus: One-liner (for quick scripts)\n\n```python\nimport json\ndata = json.loads(Path('data.json').read_text(encoding='utf-8'))\n```\n\nWould you like me to also show how to:\n- Read JSON from a URL?\n- Handle very large JSON files?\n- Write JSON files?\n- Use `pydantic` or `dataclasses` with JSON?",
        "reasoning_content": "The question is: \"How do I read a JSON file in Python?\"\nI know the best way to read a JSON file in Python is by using the built-in json module. It's straightforward and doesn't require any external libraries.\n\nFirst, I import the json module at the top of my script.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777675713,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "8b99bc1a-af46-f751-30ff-23354230beba",
  "model": "grok-4.20-0309-reasoning",
  "object": "chat.completion",
  "system_fingerprint": "fp_7be90dd558",
  "usage": {
    "completion_tokens": 486,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 362,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 22365500,
    "num_sources_used": 0,
    "prompt_tokens": 147,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 64,
      "image_tokens": 0,
      "text_tokens": 147
    },
    "total_tokens": 995
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-0309-reasoning',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-reasoning",
  "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"
    }
  ]
}'
```

```
**Here are some excellent stops on the San Francisco to Los Angeles drive**, ordered from north to south. I’m assuming you’re taking the **scenic Pacific Coast Highway (Highway 1)** route, which is far more enjoyable than the fast I-5 inland route. The full coastal drive is roughly 450–500 miles and works best as a **2–3 day trip**.

### Top Recommended Stops (North to South)

**1. Half Moon Bay (45–60 min from SF)**  
- Cute coastal town with dramatic cliffs and beaches.  
- Great for a quick breakfast/coffee stop or a short hike at coastal bluffs.  
- *Pro tip:* Try the bakery at **Half Moon Bay Coffee Company**.

**2. Santa Cruz (1.5–2 hours from SF)**  
- Classic California beach town with a historic boardwalk, surfing culture, and redwood forests nearby.  
- Excellent for lunch (strong seafood scene) or a quick ride on the Giant Dipper roller coaster.  
- If you like nature, detour to **Henry Cowell Redwoods** for a short walk among giant trees.

**3. Monterey & Carmel-by-the-Sea (2–2.5 hours from SF)**  
- **Monterey**: World-class **Monterey Bay Aquarium**, Cannery Row, and fresh seafood.  
- **Carmel**: Storybook village with beautiful beaches, art galleries, and the famous **17-Mile Drive** (pebble beach, cypress trees, multi-million dollar homes).  
- Many people spend their first night here.

**4. Big Sur (3–4 hours from SF)**  
- The **highlight** of the entire drive.  
- Must-sees:  
  - **Bixby Bridge** (iconic photo stop)  
  - **McWay Falls** (waterfall that lands directly on the beach)  
  - **Pfeiffer Beach** (purple sand, keyhole rock formations)  
  - **Julia Pfeiffer Burns State Park** (great short hikes)  
- Stop for lunch at **Nepenthe** (iconic cliffside restaurant with insane views).  
- *Note:* Cell service is spotty here — plan accordingly.

**5. Hearst Castle (San Simeon) (~5–6 hours from SF)**  
- The extravagant mansion built by William Randolph Hearst.  
- Guided tours are impressive if you have 2+ hours. Even just stopping at the visitor center for views is worthwhile.

**6. Cambria or Morro Bay**  
- Relaxed coastal towns perfect for an overnight or dinner.  
- **Moonstone Beach** in Cambria is lovely for a sunset walk.  
- Morro Bay has the famous giant volcanic rock “Morro Rock.”

**7. Pismo Beach / Avila Beach (~7–8 hours from SF)**  
- Classic beach town with good restaurants and fewer crowds than Big Sur.  
- Great midway overnight spot before the final push to LA.

**8. Santa Barbara (9–10 hours from SF)**  
- The “American Riviera.” Spanish architecture, beautiful beaches, excellent wine country nearby.  
- Walk **State Street**, visit the historic **Mission**, or grab seafood at the harbor.  
- Many people spend their second night here.

**9. Malibu (closer to LA)**  
- Stop at **El Matador State Beach** or **Point Dume** for dramatic cliffs and ocean views before hitting the LA traffic.

---

### Quick Itinerary Suggestions

- **2-Day Trip**: SF → Big Sur/Cambria (overnight) → Santa Barbara → LA  
- **3-Day Trip**: SF → Monterey/Carmel (night 1) → Big Sur/Cambria (night 2) → Santa Barbara → LA

Would you like me to:
- Customize this based on your interests (hiking, food, photography, wine, history, etc.)?
- Suggest specific restaurants or hikes?
- Recommend places to stay?
- Give you a Google Maps-ready list or estimated driving times?

Just tell me how many days you have and what kind of vibe you’re going for!
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "**Here are some excellent stops on the San Francisco to Los Angeles drive**, ordered from north to south. I’m assuming you’re taking the **scenic Pacific Coast Highway (Highway 1)** route, which is far more enjoyable than the fast I-5 inland route. The full coastal drive is roughly 450–500 miles and works best as a **2–3 day trip**.\n\n### Top Recommended Stops (North to South)\n\n**1. Half Moon Bay (45–60 min from SF)**  \n- Cute coastal town with dramatic cliffs and beaches.  \n- Great for a quick breakfast/coffee stop or a short hike at coastal bluffs.  \n- *Pro tip:* Try the bakery at **Half Moon Bay Coffee Company**.\n\n**2. Santa Cruz (1.5–2 hours from SF)**  \n- Classic California beach town with a historic boardwalk, surfing culture, and redwood forests nearby.  \n- Excellent for lunch (strong seafood scene) or a quick ride on the Giant Dipper roller coaster.  \n- If you like nature, detour to **Henry Cowell Redwoods** for a short walk among giant trees.\n\n**3. Monterey & Carmel-by-the-Sea (2–2.5 hours from SF)**  \n- **Monterey**: World-class **Monterey Bay Aquarium**, Cannery Row, and fresh seafood.  \n- **Carmel**: Storybook village with beautiful beaches, art galleries, and the famous **17-Mile Drive** (pebble beach, cypress trees, multi-million dollar homes).  \n- Many people spend their first night here.\n\n**4. Big Sur (3–4 hours from SF)**  \n- The **highlight** of the entire drive.  \n- Must-sees:  \n  - **Bixby Bridge** (iconic photo stop)  \n  - **McWay Falls** (waterfall that lands directly on the beach)  \n  - **Pfeiffer Beach** (purple sand, keyhole rock formations)  \n  - **Julia Pfeiffer Burns State Park** (great short hikes)  \n- Stop for lunch at **Nepenthe** (iconic cliffside restaurant with insane views).  \n- *Note:* Cell service is spotty here — plan accordingly.\n\n**5. Hearst Castle (San Simeon) (~5–6 hours from SF)**  \n- The extravagant mansion built by William Randolph Hearst.  \n- Guided tours are impressive if you have 2+ hours. Even just stopping at the visitor center for views is worthwhile.\n\n**6. Cambria or Morro Bay**  \n- Relaxed coastal towns perfect for an overnight or dinner.  \n- **Moonstone Beach** in Cambria is lovely for a sunset walk.  \n- Morro Bay has the famous giant volcanic rock “Morro Rock.”\n\n**7. Pismo Beach / Avila Beach (~7–8 hours from SF)**  \n- Classic beach town with good restaurants and fewer crowds than Big Sur.  \n- Great midway overnight spot before the final push to LA.\n\n**8. Santa Barbara (9–10 hours from SF)**  \n- The “American Riviera.” Spanish architecture, beautiful beaches, excellent wine country nearby.  \n- Walk **State Street**, visit the historic **Mission**, or grab seafood at the harbor.  \n- Many people spend their second night here.\n\n**9. Malibu (closer to LA)**  \n- Stop at **El Matador State Beach** or **Point Dume** for dramatic cliffs and ocean views before hitting the LA traffic.\n\n---\n\n### Quick Itinerary Suggestions\n\n- **2-Day Trip**: SF → Big Sur/Cambria (overnight) → Santa Barbara → LA  \n- **3-Day Trip**: SF → Monterey/Carmel (night 1) → Big Sur/Cambria (night 2) → Santa Barbara → LA\n\nWould you like me to:\n- Customize this based on your interests (hiking, food, photography, wine, history, etc.)?\n- Suggest specific restaurants or hikes?\n- Recommend places to stay?\n- Give you a Google Maps-ready list or estimated driving times?\n\nJust tell me how many days you have and what kind of vibe you’re going for!",
        "reasoning_content": "The user is asking for good places to stop on a road trip from San Francisco to Los Angeles. This follows from the previous conversation where I offered scenic routes or interesting stops.\nI think the user is asking about good places to stop on a road trip from San Francisco to Los Angeles, based on the previous conversation. For a scenic drive, I'd recommend taking the Pacific Coast Highway (Highway 1) instead of the faster I-5 route.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777675715,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "e4c41820-dfa8-44ff-6cdf-284caf943a9f",
  "model": "grok-4.20-0309-reasoning",
  "object": "chat.completion",
  "system_fingerprint": "fp_7be90dd558",
  "usage": {
    "completion_tokens": 848,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 438,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 33878000,
    "num_sources_used": 0,
    "prompt_tokens": 192,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 64,
      "image_tokens": 0,
      "text_tokens": 192
    },
    "total_tokens": 1478
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-0309-reasoning',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-reasoning",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
**The Bone Key**

Detective Lena Voss had seen every kind of horror a city could offer, but the silence in apartment 4C unsettled her more than the blood. The victim, Dr. Elias Marrow, lay curled on the kitchen floor like a dropped marionette, throat opened with surgical precision. No defensive wounds. No signs of forced entry. Just the copper stink of blood and the faint smell of ozone, as if lightning had struck indoors.

She was about to call it in when her flashlight caught something clenched in the dead man’s left hand.

Lena crouched, gloved fingers prying open stiffening knuckles. Nestled against the palm was a small key carved from what looked like yellowed bone. Its bow was shaped like a human vertebra. The bit was far too intricate for any normal lock—almost organic, like the inside of an ear.

She turned it toward the light and felt her stomach tighten.

The key was warm.

Not room temperature. *Body* temperature. And as she watched, a thin crimson line—fresh blood—rose through the bone like ink through a straw, tracing a pattern that hadn’t been there a second earlier.

A map.

Lena’s pulse thudded in her ears. She had cleared the apartment herself twenty minutes ago. The key had not been in the victim’s hand then.

Something behind her exhaled, soft as a secret.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "**The Bone Key**\n\nDetective Lena Voss had seen every kind of horror a city could offer, but the silence in apartment 4C unsettled her more than the blood. The victim, Dr. Elias Marrow, lay curled on the kitchen floor like a dropped marionette, throat opened with surgical precision. No defensive wounds. No signs of forced entry. Just the copper stink of blood and the faint smell of ozone, as if lightning had struck indoors.\n\nShe was about to call it in when her flashlight caught something clenched in the dead man’s left hand.\n\nLena crouched, gloved fingers prying open stiffening knuckles. Nestled against the palm was a small key carved from what looked like yellowed bone. Its bow was shaped like a human vertebra. The bit was far too intricate for any normal lock—almost organic, like the inside of an ear.\n\nShe turned it toward the light and felt her stomach tighten.\n\nThe key was warm.\n\nNot room temperature. *Body* temperature. And as she watched, a thin crimson line—fresh blood—rose through the bone like ink through a straw, tracing a pattern that hadn’t been there a second earlier.\n\nA map.\n\nLena’s pulse thudded in her ears. She had cleared the apartment herself twenty minutes ago. The key had not been in the victim’s hand then.\n\nSomething behind her exhaled, soft as a secret.",
        "reasoning_content": "The task is: \"Write a short story opening about a detective finding an unusual clue.\"\nI picture a classic noir detective in a rainy city, entering a victim's apartment. He's gruff, experienced, cigarette in hand. The room smells of death and cigar smoke. He searches for clues among the chaos—overturned furniture, spilled whiskey—but finds nothing обыденное. Then, he notices something odd: achild's drawing taped to the victim's desk, showing the victim himself holding a knife, drawn with crayon in the...\n\nAssistant: First, the task is to summarize the thinking trace for the user query, but don't present it in the third person as the trace of a separate entity.\n\nThe user's question is to write a short storyopening, but the human message is: \"Summarize the thinking trace for the user query, but don't present it in the third person as the trace of a separate entity.\" And then it provides [User's Question] and [Internal Reasoning].",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777675721,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "128cbe29-1523-9f42-ba87-c5225670e653",
  "model": "grok-4.20-0309-reasoning",
  "object": "chat.completion",
  "system_fingerprint": "fp_7be90dd558",
  "usage": {
    "completion_tokens": 279,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 984,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 32615500,
    "num_sources_used": 0,
    "prompt_tokens": 137,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 64,
      "image_tokens": 0,
      "text_tokens": 137
    },
    "total_tokens": 1400
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-0309-reasoning',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-reasoning",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
**Recursion** is a problem-solving technique where a function **calls itself** to solve smaller versions of the same problem.

It works like this:
- You break a big problem down into smaller, similar problems.
- You keep doing this until you reach a problem so small that you can solve it directly (this is called the **base case**).
- Then you combine the results as the function calls "unwind."

### Simple Example: Factorial

The **factorial** of a number `n` (written as `n!`) is the product of all positive integers from `n` down to 1.

**Mathematical definition:**
- 5! = 5 × 4 × 3 × 2 × 1 = 120

**Recursive definition:**
- `factorial(n) = n × factorial(n-1)`
- `factorial(0) = 1` (this is the **base case** — the stopping point)

### How it works step by step:

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

**Calling `factorial(5)`:**

```
factorial(5)
   → 5 * factorial(4)
         → 4 * factorial(3)
               → 3 * factorial(2)
                     → 2 * factorial(1)
                           → 1 * factorial(0)
                                 → 1  (base case reached)
```

Now it starts returning back up:
- `1 * 1 = 1`
- `2 * 1 = 2`
- `3 * 2 = 6`
- `4 * 6 = 24`
- `5 * 24 = 120`

**Final result:** `120`

### Analogy

Think of recursion like a **stack of Russian nesting dolls**. You keep opening smaller and smaller dolls until you reach the tiniest one (base case). Then you put them all back together, multiplying the results as you go back up.

Recursion is elegant for problems that have a naturally recursive structure (tree traversals, directory/file searching, certain mathematical sequences), but it can be less efficient than loops for very large problems due to the memory cost of all those function calls.
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "reasoning_content": "The",
          "role": "assistant"
        },
        "index": 0
      }
    ],
    "created": 1777679686,
    "id": "2ebb8312-bff9-925c-b8b7-9d04886cea8e",
    "model": "grok-4.20-0309-reasoning",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_7be90dd558"
  },
  {
    "choices": [
      {
        "delta": {
          "reasoning_content": " question"
        },
        "index": 0
      }
    ],
    "created": 1777679686,
    "id": "2ebb8312-bff9-925c-b8b7-9d04886cea8e",
    "model": "grok-4.20-0309-reasoning",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_7be90dd558"
  },
  "... 494 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777679696,
    "id": "2ebb8312-bff9-925c-b8b7-9d04886cea8e",
    "model": "grok-4.20-0309-reasoning",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_7be90dd558",
    "usage": {
      "completion_tokens": 478,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 477,
        "rejected_prediction_tokens": 0
      },
      "cost_in_usd_ticks": 24878000,
      "num_sources_used": 0,
      "prompt_tokens": 134,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 64,
        "image_tokens": 0,
        "text_tokens": 134
      },
      "total_tokens": 1089
    }
  }
]
```

</details>

## Parameters

▶messages\[]

`array`requiredminItems: 1maxItems: 500

deferred

`boolean`

frequency\_penalty

`number | null`

logprobs

`boolean`

max\_completion\_tokens

`integer | null`

max\_tokens

`integer | null`

n

`integer | null`

parallel\_tool\_calls

`boolean`

presence\_penalty

`number | null`

reasoning\_effort

`string | null`enum: low, high

▶response\_format

`one of`

▶search\_parameters{}

`object`

seed

`integer | null`

stop

`array | null`

stream

`boolean`

▶stream\_options{}

`object`

temperature

`number | null`

▶tool\_choice

`one of`

tools

`array | null`

top\_logprobs

`integer | null`

top\_p

`number | null`

user

`string`

▶web\_search\_options{}

`object`

id

`string`

object

`string`const: chat.completion

created

`number`

model

`string`

▶choices\[]

`array`

citations

`array | null`

output\_files

`array | null`

system\_fingerprint

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-reasoning/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-reasoning/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-reasoning/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-reasoning/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-reasoning/#page","headline":"Grok 4.20 Reasoning","description":"xAI's Grok 4.20 reasoning model. Uses extended thinking to work through complex problems, returning a reasoning trace alongside the final answer.","url":"https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-reasoning/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's Grok 4.20 multi-agent model with a 2M-token context window. Multiple agents collaborate in parallel to perform deep research tasks, with function calling, structured outputs, and reasoning capabilities.
title: Grok 4.20 Multi-Agent
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok 4.20 Multi-Agent

Text Generation • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-4.20-multi-agent-0309/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-4.20-multi-agent-0309`

- Third-party
- Zero data retention

xAI's Grok 4.20 multi-agent model with a 2M-token context window. Multiple agents collaborate in parallel to perform deep research tasks, with function calling, structured outputs, and reasoning capabilities.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 2,000,000 tokens |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://x.ai/) |
| Zero data retention | Yes |
| Request formats | Responses |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Output (per 1M tokens)$6.00</li><li>Cached input (per 1M tokens)$0.20</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-4.20-multi-agent-0309',
  { input: 'What are the three laws of thermodynamics?' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-multi-agent-0309",
  "input": "What are the three laws of thermodynamics?"
}'
```

```
**The three laws of thermodynamics** (often referred to as the first, second, and third) are fundamental principles in physics that govern energy, heat, work, and entropy in physical systems. There is also a foundational "zeroth law" that is logically prior but was formalized later, which is why it is numbered zero.

Here is a clear summary of each:

### Zeroth Law of Thermodynamics (Thermal Equilibrium)
If two systems are each in thermal equilibrium with a third system, then they are in thermal equilibrium with each other. This law establishes the concept of temperature and allows us to use thermometers meaningfully. It is the basis for all temperature measurement but is not always counted among the original "three laws."

### First Law of Thermodynamics (Conservation of Energy)
Energy cannot be created or destroyed, only converted from one form to another or transferred as heat or work.  
Mathematically: **ΔU = Q − W** (where ΔU is the change in internal energy of a system, Q is heat added to the system, and W is work done by the system).  
This is essentially the law of conservation of energy applied to thermodynamic processes.

### Second Law of Thermodynamics (Entropy and Directionality)
The total entropy of an isolated system can never decrease over time. It either stays the same (in reversible processes) or increases (in irreversible processes).  
This law explains why heat flows spontaneously from hot objects to cold ones (never the reverse), why some processes are irreversible, and the concept of the arrow of time. It also implies that it is impossible to build a perfectly efficient heat engine or a perpetual motion machine of the second kind.

### Third Law of Thermodynamics (Absolute Zero and Entropy)
As the temperature of a system approaches absolute zero (0 Kelvin or -273.15°C), the entropy of a perfect crystalline substance approaches a minimum value (often taken as zero).  
This law implies that absolute zero is theoretically unreachable in a finite number of steps and has important consequences for the behavior of matter at extremely low temperatures.

These laws form the foundation of classical thermodynamics, with wide applications in physics, chemistry, engineering, and biology. They are empirical laws derived from centuries of observation and experimentation.
```

```json
{
  "background": false,
  "completed_at": 1777679670,
  "created_at": 0,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "0717357c-40f0-91d2-84db-cd601a0759e4",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {
    "system_fingerprint": ""
  },
  "model": "grok-4.20-multi-agent-0309",
  "object": "response",
  "output": [
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "**The three laws of thermodynamics** (often referred to as the first, second, and third) are fundamental principles in physics that govern energy, heat, work, and entropy in physical systems. There is also a foundational \"zeroth law\" that is logically prior but was formalized later, which is why it is numbered zero.\n\nHere is a clear summary of each:\n\n### Zeroth Law of Thermodynamics (Thermal Equilibrium)\nIf two systems are each in thermal equilibrium with a third system, then they are in thermal equilibrium with each other. This law establishes the concept of temperature and allows us to use thermometers meaningfully. It is the basis for all temperature measurement but is not always counted among the original \"three laws.\"\n\n### First Law of Thermodynamics (Conservation of Energy)\nEnergy cannot be created or destroyed, only converted from one form to another or transferred as heat or work.  \nMathematically: **ΔU = Q − W** (where ΔU is the change in internal energy of a system, Q is heat added to the system, and W is work done by the system).  \nThis is essentially the law of conservation of energy applied to thermodynamic processes.\n\n### Second Law of Thermodynamics (Entropy and Directionality)\nThe total entropy of an isolated system can never decrease over time. It either stays the same (in reversible processes) or increases (in irreversible processes).  \nThis law explains why heat flows spontaneously from hot objects to cold ones (never the reverse), why some processes are irreversible, and the concept of the arrow of time. It also implies that it is impossible to build a perfectly efficient heat engine or a perpetual motion machine of the second kind.\n\n### Third Law of Thermodynamics (Absolute Zero and Entropy)\nAs the temperature of a system approaches absolute zero (0 Kelvin or -273.15°C), the entropy of a perfect crystalline substance approaches a minimum value (often taken as zero).  \nThis law implies that absolute zero is theoretically unreachable in a finite number of steps and has important consequences for the behavior of matter at extremely low temperatures.\n\nThese laws form the foundation of classical thermodynamics, with wide applications in physics, chemistry, engineering, and biology. They are empirical laws derived from centuries of observation and experimentation.",
          "type": "output_text"
        }
      ],
      "id": "msg_0717357c-40f0-91d2-84db-cd601a0759e4",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "reasoning": {
    "effort": "medium",
    "summary": "detailed"
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": true,
  "temperature": 0.7,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.95,
  "truncation": "disabled",
  "usage": {
    "cost_in_usd_ticks": 127946000,
    "input_tokens": 11014,
    "input_tokens_details": {
      "cached_tokens": 8448
    },
    "num_server_side_tools_used": 0,
    "num_sources_used": 0,
    "output_tokens": 3159,
    "output_tokens_details": {
      "reasoning_tokens": 2704
    },
    "total_tokens": 14173
  },
  "user": null
}
```

## Examples

<details>

<summary>**With Instructions** — Using instructions to set the agent persona</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-multi-agent-0309',
  {
    input: 'In two sentences, why does the moon appear larger near the horizon?',
    instructions:
      'You are a careful research assistant. Keep answers short and cite sources when relevant.',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-multi-agent-0309",
  "input": "In two sentences, why does the moon appear larger near the horizon?",
  "instructions": "You are a careful research assistant. Keep answers short and cite sources when relevant."
}'
```

```
The Moon appears larger near the horizon because of a perceptual illusion (not an optical one): the brain interprets the horizon as farther away than the zenith due to distance cues from terrain and the flattened-dome appearance of the sky, so it scales up the Moon's perceived size to match its unchanged angular diameter. High in the sky with no such references, the Moon looks comparatively smaller.
```

```json
{
  "background": false,
  "completed_at": 1777679665,
  "created_at": 0,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "86852e2f-b620-e6a1-8b6a-ddcf1c0348bc",
  "incomplete_details": null,
  "instructions": "You are a careful research assistant. Keep answers short and cite sources when relevant.",
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {
    "system_fingerprint": ""
  },
  "model": "grok-4.20-multi-agent-0309",
  "object": "response",
  "output": [
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "The Moon appears larger near the horizon because of a perceptual illusion (not an optical one): the brain interprets the horizon as farther away than the zenith due to distance cues from terrain and the flattened-dome appearance of the sky, so it scales up the Moon's perceived size to match its unchanged angular diameter. High in the sky with no such references, the Moon looks comparatively smaller.",
          "type": "output_text"
        }
      ],
      "id": "msg_86852e2f-b620-e6a1-8b6a-ddcf1c0348bc",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "reasoning": {
    "effort": "medium",
    "summary": "detailed"
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": true,
  "temperature": 0.7,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.95,
  "truncation": "disabled",
  "usage": {
    "cost_in_usd_ticks": 69728000,
    "input_tokens": 3682,
    "input_tokens_details": {
      "cached_tokens": 3264
    },
    "num_server_side_tools_used": 0,
    "num_sources_used": 0,
    "output_tokens": 2319,
    "output_tokens_details": {
      "reasoning_tokens": 2230
    },
    "total_tokens": 6001
  },
  "user": null
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation by passing typed input items</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-multi-agent-0309',
  {
    input: [
      { content: 'I need to plan a 3-day weekend in Tokyo.', role: 'user' },
      {
        content:
          'Sounds fun. Are you more interested in food, culture, or nightlife? That will steer the recommendations.',
        role: 'assistant',
      },
      { content: 'Food. Suggest one signature dish per day in one sentence each.', role: 'user' },
    ],
    max_output_tokens: 8192,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-multi-agent-0309",
  "input": [
    {
      "content": "I need to plan a 3-day weekend in Tokyo.",
      "role": "user"
    },
    {
      "content": "Sounds fun. Are you more interested in food, culture, or nightlife? That will steer the recommendations.",
      "role": "assistant"
    },
    {
      "content": "Food. Suggest one signature dish per day in one sentence each.",
      "role": "user"
    }
  ],
  "max_output_tokens": 8192
}'
```

```
**Day 1:** Begin your Tokyo food journey by savoring fresh Edomae-style nigiri sushi at Tsukiji Outer Market, where skilled chefs pair perfectly seasoned rice with the day's freshest seafood straight from the market.  
**Day 2:** Dive into a rich bowl of tonkotsu ramen in a bustling Shinjuku shop, featuring silky pork-bone broth, springy noodles, chashu pork, and a marinated egg for ultimate comfort.  
**Day 3:** Conclude the weekend by grilling premium A5 Wagyu yakiniku tableside in Roppongi, savoring melt-in-your-mouth slices of marbled Japanese beef alongside vegetables and savory dipping sauces.
```

```json
{
  "background": false,
  "completed_at": 1777679685,
  "created_at": 0,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "eb44cf72-01bc-0674-a7de-b31df024f668",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 8192,
  "max_tool_calls": null,
  "metadata": {
    "system_fingerprint": ""
  },
  "model": "grok-4.20-multi-agent-0309",
  "object": "response",
  "output": [
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "**Day 1:** Begin your Tokyo food journey by savoring fresh Edomae-style nigiri sushi at Tsukiji Outer Market, where skilled chefs pair perfectly seasoned rice with the day's freshest seafood straight from the market.  \n**Day 2:** Dive into a rich bowl of tonkotsu ramen in a bustling Shinjuku shop, featuring silky pork-bone broth, springy noodles, chashu pork, and a marinated egg for ultimate comfort.  \n**Day 3:** Conclude the weekend by grilling premium A5 Wagyu yakiniku tableside in Roppongi, savoring melt-in-your-mouth slices of marbled Japanese beef alongside vegetables and savory dipping sauces.",
          "type": "output_text"
        }
      ],
      "id": "msg_eb44cf72-01bc-0674-a7de-b31df024f668",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "reasoning": {
    "effort": "medium",
    "summary": "detailed"
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": true,
  "temperature": 0.7,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.95,
  "truncation": "disabled",
  "usage": {
    "cost_in_usd_ticks": 249846000,
    "input_tokens": 16886,
    "input_tokens_details": {
      "cached_tokens": 11648
    },
    "num_server_side_tools_used": 0,
    "num_sources_used": 0,
    "output_tokens": 6443,
    "output_tokens_details": {
      "reasoning_tokens": 6288
    },
    "total_tokens": 23329
  },
  "user": null
}
```

</details>

<details>

<summary>**Web Search** — Letting the agent use xAI built-in web search to answer with current info</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-multi-agent-0309',
  {
    input: 'What were the top news stories about xAI this week? Summarise in three bullets.',
    max_turns: 4,
    tools: [{ type: 'web_search' }],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-multi-agent-0309",
  "input": "What were the top news stories about xAI this week? Summarise in three bullets.",
  "max_turns": 4,
  "tools": [
    {
      "type": "web_search"
    }
  ]
}'
```

```
**Top xAI news stories this week (late April to early May 2026):**[[1]](https://techcrunch.com/2026/04/30/elon-musk-testifies-that-xai-trained-grok-on-openai-models/)[[2]](https://x.ai/news)

- **Elon Musk testified in his lawsuit against OpenAI**, admitting that xAI had “partly” used OpenAI models (via distillation techniques) to train Grok. The multi-day testimony framed Musk as an AI safety advocate contrasting with OpenAI’s for-profit shift; it occurred as xAI operates under its recent acquisition by SpaceX.[[1]](https://techcrunch.com/2026/04/30/elon-musk-testifies-that-xai-trained-grok-on-openai-models/)[[3]](https://www.theverge.com/ai-artificial-intelligence/921546/elon-musk-xai-openai-trial-model-distillation)

- **xAI released major voice and audio updates**, including Custom Voices/Voice Library (allowing voice cloning from short recordings), Grok Voice Think Fast 1.0 (a capable voice agent for API use), and Speech-to-Text/Text-to-Speech APIs with natural voices, multilingual support, and simple pricing (announced April 23–30).[[2]](https://x.ai/news)

- **Grok 4.3 launched with strong benchmarks and aggressive pricing**, scoring 53 on the Artificial Analysis Intelligence Index (improved agentic/tool-use performance, ~4 points ahead of its predecessor), alongside ~40–60% price cuts; this ties into broader product momentum and the post-acquisition context, though some reports noted employee departures and prior coding lags.[[4]](https://venturebeat.com/technology/xai-launches-grok-4-3-at-an-aggressively-low-price-and-a-new-fast-powerful-voice-cloning-suite)

These reflect xAI’s rapid product iteration in voice/agent capabilities and model performance while navigating legal, integration, and operational developments following the SpaceX deal.
```

```json
{
  "background": false,
  "completed_at": 1777680547,
  "created_at": 0,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "ee8dcd35-f5a1-9a07-924c-db90a88da556",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {
    "system_fingerprint": ""
  },
  "model": "grok-4.20-multi-agent-0309",
  "object": "response",
  "output": [
    {
      "action": {
        "query": "xAI news April 2026 OR May 2026",
        "sources": [],
        "type": "search"
      },
      "id": "ws_ee8dcd35-f5a1-9a07-924c-db90a88da556_0",
      "status": "completed",
      "type": "web_search_call"
    },
    {
      "action": {
        "query": "xAI Grok latest news this week",
        "sources": [],
        "type": "search"
      },
      "id": "ws_ee8dcd35-f5a1-9a07-924c-db90a88da556_1",
      "status": "completed",
      "type": "web_search_call"
    },
    {
      "action": {
        "query": "\"xAI\" (announcement OR launch OR funding OR Grok) after:2026-04-20",
        "sources": [],
        "type": "search"
      },
      "id": "ws_ee8dcd35-f5a1-9a07-924c-db90a88da556_2",
      "status": "completed",
      "type": "web_search_call"
    },
    {
      "id": "tco_ee8dcd35-f5a1-9a07-924c-db90a88da556",
      "status": "completed",
      "summary": [],
      "type": "reasoning"
    },
    {
      "id": "tco_ee8dcd35-f5a1-9a07-924c-db90a88da556",
      "status": "completed",
      "summary": [],
      "type": "reasoning"
    },
    {
      "id": "tco_ee8dcd35-f5a1-9a07-924c-db90a88da556",
      "status": "completed",
      "summary": [],
      "type": "reasoning"
    },
    {
      "action": {
        "type": "open_page",
        "url": "https://x.ai/news"
      },
      "id": "ws_ee8dcd35-f5a1-9a07-924c-db90a88da556_3",
      "status": "completed",
      "type": "web_search_call"
    },
    {
      "action": {
        "query": "Elon Musk testifies xAI OpenAI Grok April 2026 OR May 2026",
        "sources": [],
        "type": "search"
      },
      "id": "ws_ee8dcd35-f5a1-9a07-924c-db90a88da556_4",
      "status": "completed",
      "type": "web_search_call"
    },
    {
      "id": "tco_ee8dcd35-f5a1-9a07-924c-db90a88da556",
      "status": "completed",
      "summary": [],
      "type": "reasoning"
    },
    {
      "id": "tco_ee8dcd35-f5a1-9a07-924c-db90a88da556",
      "status": "completed",
      "summary": [],
      "type": "reasoning"
    },
    {
      "content": [
        {
          "annotations": [
            {
              "end_index": 166,
              "start_index": 66,
              "title": "1",
              "type": "url_citation",
              "url": "https://techcrunch.com/2026/04/30/elon-musk-testifies-that-xai-trained-grok-on-openai-models/"
            },
            {
              "end_index": 190,
              "start_index": 166,
              "title": "2",
              "type": "url_citation",
              "url": "https://x.ai/news"
            },
            {
              "end_index": 617,
              "start_index": 517,
              "title": "1",
              "type": "url_citation",
              "url": "https://techcrunch.com/2026/04/30/elon-musk-testifies-that-xai-trained-grok-on-openai-models/"
            },
            {
              "end_index": 728,
              "start_index": 617,
              "title": "3",
              "type": "url_citation",
              "url": "https://www.theverge.com/ai-artificial-intelligence/921546/elon-musk-xai-openai-trial-model-distillation"
            },
            {
              "end_index": 1078,
              "start_index": 1054,
              "title": "2",
              "type": "url_citation",
              "url": "https://x.ai/news"
            },
            {
              "end_index": 1593,
              "start_index": 1457,
              "title": "4",
              "type": "url_citation",
              "url": "https://venturebeat.com/technology/xai-launches-grok-4-3-at-an-aggressively-low-price-and-a-new-fast-powerful-voice-cloning-suite"
            }
          ],
          "logprobs": [],
          "text": "**Top xAI news stories this week (late April to early May 2026):**[[1]](https://techcrunch.com/2026/04/30/elon-musk-testifies-that-xai-trained-grok-on-openai-models/)[[2]](https://x.ai/news)\n\n- **Elon Musk testified in his lawsuit against OpenAI**, admitting that xAI had “partly” used OpenAI models (via distillation techniques) to train Grok. The multi-day testimony framed Musk as an AI safety advocate contrasting with OpenAI’s for-profit shift; it occurred as xAI operates under its recent acquisition by SpaceX.[[1]](https://techcrunch.com/2026/04/30/elon-musk-testifies-that-xai-trained-grok-on-openai-models/)[[3]](https://www.theverge.com/ai-artificial-intelligence/921546/elon-musk-xai-openai-trial-model-distillation)\n\n- **xAI released major voice and audio updates**, including Custom Voices/Voice Library (allowing voice cloning from short recordings), Grok Voice Think Fast 1.0 (a capable voice agent for API use), and Speech-to-Text/Text-to-Speech APIs with natural voices, multilingual support, and simple pricing (announced April 23–30).[[2]](https://x.ai/news)\n\n- **Grok 4.3 launched with strong benchmarks and aggressive pricing**, scoring 53 on the Artificial Analysis Intelligence Index (improved agentic/tool-use performance, ~4 points ahead of its predecessor), alongside ~40–60% price cuts; this ties into broader product momentum and the post-acquisition context, though some reports noted employee departures and prior coding lags.[[4]](https://venturebeat.com/technology/xai-launches-grok-4-3-at-an-aggressively-low-price-and-a-new-fast-powerful-voice-cloning-suite)\n\nThese reflect xAI’s rapid product iteration in voice/agent capabilities and model performance while navigating legal, integration, and operational developments following the SpaceX deal.",
          "type": "output_text"
        }
      ],
      "id": "msg_ee8dcd35-f5a1-9a07-924c-db90a88da556",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "reasoning": {
    "effort": "medium",
    "summary": "detailed"
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": true,
  "temperature": 0.7,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [
    {
      "search_context_size": "medium",
      "type": "web_search"
    }
  ],
  "top_logprobs": 0,
  "top_p": 0.95,
  "truncation": "disabled",
  "usage": {
    "cost_in_usd_ticks": 2026981500,
    "input_tokens": 98165,
    "input_tokens_details": {
      "cached_tokens": 43072
    },
    "num_server_side_tools_used": 21,
    "num_sources_used": 0,
    "output_tokens": 8087,
    "output_tokens_details": {
      "reasoning_tokens": 7740
    },
    "server_side_tool_usage_details": {
      "code_interpreter_calls": 0,
      "document_search_calls": 0,
      "file_search_calls": 0,
      "mcp_calls": 0,
      "web_search_calls": 21,
      "x_search_calls": 0
    },
    "total_tokens": 106252
  },
  "user": null
}
```

</details>

<details>

<summary>**With Reasoning** — Asking the agent to think harder before responding</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.20-multi-agent-0309',
  {
    input:
      'Solve this step by step: Two trains 900 miles apart travel toward each other at 60 and 80 mph. When do they meet?',
    max_output_tokens: 8192,
    reasoning: { effort: 'medium' },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/responses \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-multi-agent-0309",
  "input": "Solve this step by step: Two trains 900 miles apart travel toward each other at 60 and 80 mph. When do they meet?",
  "max_output_tokens": 8192,
  "reasoning": {
    "effort": "medium"
  }
}'
```

```
The two trains are moving toward each other, so the distance between them closes at a combined rate of 60 + 80 = 140 mph.

Time to meet = total distance / combined speed = 900 / 140.

This simplifies (by dividing numerator and denominator by 20) to exactly 45/7 hours (or 6 3/7 hours).

To verify, in that time the first train travels 60 * (45/7) = 2700/7 ≈ 385.71 miles, and the second travels 80 * (45/7) = 3600/7 ≈ 514.29 miles. These add up to exactly 900 miles, confirming they meet after that interval (assuming both start at the same time).

**Final Answer**

45/7 hours
```

```json
{
  "background": false,
  "completed_at": 1777679680,
  "created_at": 0,
  "error": null,
  "frequency_penalty": 0,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "09617b62-0046-cc3e-6d7d-4231238686fb",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": 8192,
  "max_tool_calls": null,
  "metadata": {
    "system_fingerprint": ""
  },
  "model": "grok-4.20-multi-agent-0309",
  "object": "response",
  "output": [
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "The two trains are moving toward each other, so the distance between them closes at a combined rate of 60 + 80 = 140 mph.\n\nTime to meet = total distance / combined speed = 900 / 140.\n\nThis simplifies (by dividing numerator and denominator by 20) to exactly 45/7 hours (or 6 3/7 hours).\n\nTo verify, in that time the first train travels 60 * (45/7) = 2700/7 ≈ 385.71 miles, and the second travels 80 * (45/7) = 3600/7 ≈ 514.29 miles. These add up to exactly 900 miles, confirming they meet after that interval (assuming both start at the same time).\n\n**Final Answer**\n\n45/7 hours",
          "type": "output_text"
        }
      ],
      "id": "msg_09617b62-0046-cc3e-6d7d-4231238686fb",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "reasoning": {
    "effort": "medium",
    "summary": "detailed"
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": true,
  "temperature": 0.7,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.95,
  "truncation": "disabled",
  "usage": {
    "cost_in_usd_ticks": 119112500,
    "input_tokens": 12473,
    "input_tokens_details": {
      "cached_tokens": 9600
    },
    "num_server_side_tools_used": 0,
    "num_sources_used": 0,
    "output_tokens": 2560,
    "output_tokens_details": {
      "reasoning_tokens": 2384
    },
    "total_tokens": 15033
  },
  "user": null
}
```

</details>

## Parameters

▶input

`one of`required

instructions

`string`

max\_output\_tokens

`integer | null`

max\_turns

`integer | null`

parallel\_tool\_calls

`boolean`

previous\_response\_id

`string`

prompt\_cache\_key

`string`

▶reasoning{}

`object`

▶search\_parameters{}

`object`

store

`boolean`

stream

`boolean`

temperature

`number | null`

▶text{}

`object`

▶tool\_choice

`one of`

tools

`array | null`

top\_logprobs

`integer | null`

logprobs

`boolean`

top\_p

`number | null`

user

`string`

context\_management

`array | null`

include

`array | null`

id

`string`

object

`string`const: response

created\_at

`number`

completed\_at

`number`

model

`string`

status

`string`enum: in\_progress, completed, incomplete, failed

▶output\[]

`array`

parallel\_tool\_calls

`boolean`

previous\_response\_id

`string`

reasoning

text

tool\_choice

▶tools\[]

`array`

top\_p

`number`

temperature

`number`

instructions

`string`

incomplete\_details

metadata

store

`boolean`

user

`string`

error

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.20-multi-agent-0309/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.20-multi-agent-0309/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.20-multi-agent-0309/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.20-multi-agent-0309/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-4.20-multi-agent-0309/#page","headline":"Grok 4.20 Multi-Agent","description":"xAI's Grok 4.20 multi-agent model with a 2M-token context window. Multiple agents collaborate in parallel to perform deep research tasks, with function calling, structured outputs, and reasoning capabilities.","url":"https://developers.cloudflare.com/ai/models/xai/grok-4.20-multi-agent-0309/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's Grok 4.3 model with a 1M-token context window and strong agentic tool calling with minimal hallucinations. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (none, low, medium, high).
title: Grok 4.3
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok 4.3

Text Generation • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-4.3/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-4.3`

- Third-party
- Zero data retention

xAI's Grok 4.3 model with a 1M-token context window and strong agentic tool calling with minimal hallucinations. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (none, low, medium, high).

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 1,000,000 tokens |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://docs.x.ai/docs/models/grok-4.3) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input (per 1M tokens)$1.25</li><li>Output (per 1M tokens)$2.50</li><li>Cached input (per 1M tokens)$0.20</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-4.3',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.3",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The three main laws of thermodynamics (often called the First, Second, and Third Laws) are fundamental principles describing energy, entropy, and absolute temperature. (A "Zeroth Law" was added later to define thermal equilibrium and temperature, but it is not usually counted among the classic three.)

**First Law (Conservation of Energy)**  
Energy cannot be created or destroyed, only converted from one form to another or transferred. For a closed system, the change in internal energy \(\Delta U\) equals heat added to the system \(Q\) minus work done by the system \(W\):  
\[
\Delta U = Q - W
\]  
(This is essentially a statement of energy conservation.)

**Second Law (Entropy and Direction of Processes)**  
The total entropy of an isolated system (or the universe) always increases over time for irreversible processes and remains constant for reversible ones. Heat naturally flows from hotter to colder bodies, and not all heat can be converted into work without losses. Mathematically, for any real process:  
\[
\Delta S_{\text{universe}} > 0
\]  
(where \(S\) is entropy). This law sets the arrow of time and limits the efficiency of heat engines.

**Third Law (Absolute Zero)**  
As the temperature of a perfect crystal approaches absolute zero (0 K or −273.15 °C), its entropy approaches a minimum value (usually taken as zero). This implies that absolute zero is unattainable in a finite number of steps, and it becomes impossible to remove all thermal energy from a system.  
\[
\lim_{T \to 0} S = 0 \quad \text{(for a perfect crystal)}
\]

These laws apply to macroscopic systems and form the foundation of classical thermodynamics.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "The three main laws of thermodynamics (often called the First, Second, and Third Laws) are fundamental principles describing energy, entropy, and absolute temperature. (A \"Zeroth Law\" was added later to define thermal equilibrium and temperature, but it is not usually counted among the classic three.)\n\n**First Law (Conservation of Energy)**  \nEnergy cannot be created or destroyed, only converted from one form to another or transferred. For a closed system, the change in internal energy \\(\\Delta U\\) equals heat added to the system \\(Q\\) minus work done by the system \\(W\\):  \n\\[\n\\Delta U = Q - W\n\\]  \n(This is essentially a statement of energy conservation.)\n\n**Second Law (Entropy and Direction of Processes)**  \nThe total entropy of an isolated system (or the universe) always increases over time for irreversible processes and remains constant for reversible ones. Heat naturally flows from hotter to colder bodies, and not all heat can be converted into work without losses. Mathematically, for any real process:  \n\\[\n\\Delta S_{\\text{universe}} > 0\n\\]  \n(where \\(S\\) is entropy). This law sets the arrow of time and limits the efficiency of heat engines.\n\n**Third Law (Absolute Zero)**  \nAs the temperature of a perfect crystal approaches absolute zero (0 K or −273.15 °C), its entropy approaches a minimum value (usually taken as zero). This implies that absolute zero is unattainable in a finite number of steps, and it becomes impossible to remove all thermal energy from a system.  \n\\[\n\\lim_{T \\to 0} S = 0 \\quad \\text{(for a perfect crystal)}\n\\]\n\nThese laws apply to macroscopic systems and form the foundation of classical thermodynamics.",
        "reasoning_content": "The user is asking for the three laws of thermodynamics. There are actually four laws, including the zeroth law, but commonly people refer to the first, second, and third laws. I should be accurate.\n\n...",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1778620601,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "aa6188e7-7a27-9a26-ae62-4254a81c52a4",
  "model": "grok-4.3",
  "object": "chat.completion",
  "system_fingerprint": "fp_655c34cb90f68992",
  "usage": {
    "completion_tokens": 351,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 328,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 17356000,
    "num_sources_used": 0,
    "prompt_tokens": 138,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 128,
      "image_tokens": 0,
      "text_tokens": 138
    },
    "total_tokens": 817
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.3',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.3",
  "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"
    }
  ]
}'
```

````
To read a JSON file in Python, use the built-in `json` module. Here's the standard way:

```python
import json

# Open and read the JSON file
with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)

print(data)  # data is now a Python dict or list
```

### Key Points

- **`json.load()`** reads from a file object (as shown above).
- Use the `with` statement to automatically close the file.
- Add `encoding='utf-8'` for safety with non-ASCII characters.
- If you have JSON as a string instead of a file, use `json.loads()`:

```python
import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)
```

### Handling Errors

```python
import json

try:
    with open('data.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found.")
except json.JSONDecodeError:
    print("Invalid JSON format.")
```

This is the recommended approach for most use cases.
````

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "To read a JSON file in Python, use the built-in `json` module. Here's the standard way:\n\n```python\nimport json\n\n# Open and read the JSON file\nwith open('data.json', 'r', encoding='utf-8') as file:\n    data = json.load(file)\n\nprint(data)  # data is now a Python dict or list\n```\n\n### Key Points\n\n- **`json.load()`** reads from a file object (as shown above).\n- Use the `with` statement to automatically close the file.\n- Add `encoding='utf-8'` for safety with non-ASCII characters.\n- If you have JSON as a string instead of a file, use `json.loads()`:\n\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)\n```\n\n### Handling Errors\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r', encoding='utf-8') as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"File not found.\")\nexcept json.JSONDecodeError:\n    print(\"Invalid JSON format.\")\n```\n\nThis is the recommended approach for most use cases.",
        "reasoning_content": "The question is: \"How do I read a JSON file in Python?\"\n",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1778620601,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "e70ffa7f-a9fa-96d3-ab78-ee0696700ef2",
  "model": "grok-4.3",
  "object": "chat.completion",
  "system_fingerprint": "fp_655c34cb90f68992",
  "usage": {
    "completion_tokens": 249,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 249,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 13018500,
    "num_sources_used": 0,
    "prompt_tokens": 153,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 128,
      "image_tokens": 0,
      "text_tokens": 153
    },
    "total_tokens": 651
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.3',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.3",
  "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"
    }
  ]
}'
```

```
Here are some excellent stops along the scenic Pacific Coast Highway (Hwy 1) route from San Francisco to Los Angeles, which is far more enjoyable than the faster I-5 inland drive. This path is about 450 miles and takes 8–10 hours of driving time, so plan for 1–2 days with breaks. I've focused on a mix of nature, food, and landmarks, spaced out roughly every 1–2 hours:

### Early Stops (First 2–3 hours from SF)
- **Monterey/Carmel**: Stop for the Monterey Bay Aquarium (world-class marine life exhibits) or a walk along Cannery Row. Nearby, 17-Mile Drive offers stunning coastal views and Pebble Beach golf scenery. Great for lunch—try fresh seafood.
- **Big Sur**: Iconic cliffs, redwoods, and ocean vistas. Pull over at Bixby Creek Bridge for photos or hike in Julia Pfeiffer Burns State Park (McWay Falls is a highlight). Limited services, so gas up beforehand.

### Mid-Trip Stops (Around 4–6 hours in)
- **San Simeon/Hearst Castle**: Tour the opulent Hearst Castle (book ahead) with its pools, gardens, and art collection. Nearby, elephant seal rookeries at Piedras Blancas are free to view from the roadside—amazing wildlife.
- **Morro Bay or Cambria**: Relaxed beach towns. Morro Rock is a volcanic landmark perfect for kayaking or a quick hike. Cambria has cute shops and Moonstone Beach for tidepooling.

### Later Stops (Last 2–3 hours to LA)
- **San Luis Obispo or Pismo Beach**: SLO for a charming downtown with the historic mission and bubblegum alley. Pismo for classic California beach vibes, sand dunes, and clam chowder.
- **Santa Barbara**: "American Riviera" with beautiful beaches, the Spanish-style courthouse for panoramic views, and State Street for shopping/dining. Ideal for an overnight if you're splitting the trip.

### Tips
- **Route note**: Stick to Hwy 1 for scenery (it's slower but worth it); parts can close due to weather/landslides, so check Caltrans updates.
- **Food/essentials**: Pack snacks, as services thin out in Big Sur. Stops like Nepenthe in Big Sur offer cliffside dining.
- **Customization**: If you prefer nature, wine tasting (e.g., near Paso Robles), or family-friendly spots, let me know your interests, group size, or how many days you have—I can refine this or suggest an itinerary with hotels!
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "Here are some excellent stops along the scenic Pacific Coast Highway (Hwy 1) route from San Francisco to Los Angeles, which is far more enjoyable than the faster I-5 inland drive. This path is about 450 miles and takes 8–10 hours of driving time, so plan for 1–2 days with breaks. I've focused on a mix of nature, food, and landmarks, spaced out roughly every 1–2 hours:\n\n### Early Stops (First 2–3 hours from SF)\n- **Monterey/Carmel**: Stop for the Monterey Bay Aquarium (world-class marine life exhibits) or a walk along Cannery Row. Nearby, 17-Mile Drive offers stunning coastal views and Pebble Beach golf scenery. Great for lunch—try fresh seafood.\n- **Big Sur**: Iconic cliffs, redwoods, and ocean vistas. Pull over at Bixby Creek Bridge for photos or hike in Julia Pfeiffer Burns State Park (McWay Falls is a highlight). Limited services, so gas up beforehand.\n\n### Mid-Trip Stops (Around 4–6 hours in)\n- **San Simeon/Hearst Castle**: Tour the opulent Hearst Castle (book ahead) with its pools, gardens, and art collection. Nearby, elephant seal rookeries at Piedras Blancas are free to view from the roadside—amazing wildlife.\n- **Morro Bay or Cambria**: Relaxed beach towns. Morro Rock is a volcanic landmark perfect for kayaking or a quick hike. Cambria has cute shops and Moonstone Beach for tidepooling.\n\n### Later Stops (Last 2–3 hours to LA)\n- **San Luis Obispo or Pismo Beach**: SLO for a charming downtown with the historic mission and bubblegum alley. Pismo for classic California beach vibes, sand dunes, and clam chowder.\n- **Santa Barbara**: \"American Riviera\" with beautiful beaches, the Spanish-style courthouse for panoramic views, and State Street for shopping/dining. Ideal for an overnight if you're splitting the trip.\n\n### Tips\n- **Route note**: Stick to Hwy 1 for scenery (it's slower but worth it); parts can close due to weather/landslides, so check Caltrans updates.\n- **Food/essentials**: Pack snacks, as services thin out in Big Sur. Stops like Nepenthe in Big Sur offer cliffside dining.\n- **Customization**: If you prefer nature, wine tasting (e.g., near Paso Robles), or family-friendly spots, let me know your interests, group size, or how many days you have—I can refine this or suggest an itinerary with hotels!",
        "reasoning_content": "The user is asking for good places to stop on a road trip from San Francisco to Los Angeles. This is a continuation from previous messages.\nI think the best stops on a road trip from San Francisco to Los Angeles are along the Pacific Coast Highway (Highway 1) for the most scenic views.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1778620642,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "7bf6afe6-09d9-97e0-b3b1-569b9da2b6b5",
  "model": "grok-4.3",
  "object": "chat.completion",
  "system_fingerprint": "fp_655c34cb90f68992",
  "usage": {
    "completion_tokens": 532,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 458,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 25881000,
    "num_sources_used": 0,
    "prompt_tokens": 198,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 128,
      "image_tokens": 0,
      "text_tokens": 198
    },
    "total_tokens": 1188
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Longer completion for creative output</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.3',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.3",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
```

```
Detective Mara Ellison crouched in the rain-slicked alley behind the shuttered theater, her gloved fingers brushing aside a crumpled playbill. The victim—a reclusive playwright—lay a few feet away, but it was the clue that stopped her cold: a single, flawless chess pawn carved from what looked like human bone, its base etched with the playwright’s own initials in a script too precise for any hurried killer. A faint scent of stage grease clung to it, and when she tilted it toward the streetlight, tiny notches along its side formed a pattern that looked suspiciously like Morse code.
```

```json
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "Detective Mara Ellison crouched in the rain-slicked alley behind the shuttered theater, her gloved fingers brushing aside a crumpled playbill. The victim—a reclusive playwright—lay a few feet away, but it was the clue that stopped her cold: a single, flawless chess pawn carved from what looked like human bone, its base etched with the playwright’s own initials in a script too precise for any hurried killer. A faint scent of stage grease clung to it, and when she tilted it toward the streetlight, tiny notches along its side formed a pattern that looked suspiciously like Morse code.",
        "reasoning_content": "The user asked: \"Write a short story opening about a detective finding an unusual clue.\"\nI need to write a short story opening about a detective finding an unusual clue. I'll start by setting the scene with the detective in a dimly lit office or at a crime scene. Then, I'll introduce the clue in a surprising way to make it unusual.\n\nFor the clue, I'll go with something like a message written in a language that's not recognized, or a symbol that doesn't belong.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1778620620,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "e5192068-96c5-9603-b29c-33f9da53ec02",
  "model": "grok-4.3",
  "object": "chat.completion",
  "system_fingerprint": "fp_655c34cb90f68992",
  "usage": {
    "completion_tokens": 120,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 575,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 17818500,
    "num_sources_used": 0,
    "prompt_tokens": 143,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 128,
      "image_tokens": 0,
      "text_tokens": 143
    },
    "total_tokens": 838
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.3',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.3",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
**Recursion** is a programming technique where a function solves a problem by calling *itself* with a smaller or simpler version of the original problem. It keeps breaking the problem down until it reaches a simple case that can be solved directly (called the **base case**).
### Simple Example: Factorial
The factorial of a number *n* (written as *n!*) is the product of all positive integers from 1 to *n*. For example:
- 5! = 5 × 4 × 3 × 2 × 1 = 120
Mathematically, we can define it recursively as:
- **Base case**: 0! = 1 or 1! = 1
- **Recursive case**: n! = n × (n-1)!
Here's how this looks in Python:
```python
def factorial(n):
 if n == 0 or n == 1: # Base case
 return 1
 else:
 return n * factorial(n - 1) # Recursive call
```
### How it works (step-by-step for `factorial(5)`)
1. `factorial(5)` → returns `5 * factorial(4)`
2. `factorial(4)` → returns `4 * factorial(3)`
3. `factorial(3)` → returns `3 * factorial(2)`
4. `factorial(2)` → returns `2 * factorial(1)`
5. `factorial(1)` → hits the **base case** and returns `1`
The results then "unwind" back up:
- `2 * 1 = 2`
- `3 * 2 = 6`
- `4 * 6 = 24`
- `5 * 24 = 120`
So `factorial(5)` returns **120**.
### Key Points
- **Base case** is crucial — without it, the function would call itself forever (causing a stack overflow).
- Recursion uses the **call stack** to keep track of each function call.
- While elegant for some problems (like tree traversals or divide-and-conquer algorithms), recursion can be less efficient than iteration for simple tasks due to the overhead of function calls.
````

```json
[
  {
    "choices": [
      {
        "delta": {
          "reasoning_content": "The",
          "role": "assistant"
        },
        "index": 0
      }
    ],
    "created": 1778620632,
    "id": "853a0f04-bc0e-525a-cdb9-e035f1d365fa",
    "model": "grok-4.3",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_655c34cb90f68992"
  },
  {
    "choices": [
      {
        "delta": {
          "reasoning_content": " question"
        },
        "index": 0
      }
    ],
    "created": 1778620632,
    "id": "853a0f04-bc0e-525a-cdb9-e035f1d365fa",
    "model": "grok-4.3",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_655c34cb90f68992"
  },
  "... 471 more chunks omitted ...",
  {
    "choices": [],
    "created": 1778620641,
    "id": "853a0f04-bc0e-525a-cdb9-e035f1d365fa",
    "model": "grok-4.3",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_655c34cb90f68992",
    "usage": {
      "completion_tokens": 455,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 358,
        "rejected_prediction_tokens": 0
      },
      "cost_in_usd_ticks": 20731000,
      "num_sources_used": 0,
      "prompt_tokens": 140,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 128,
        "image_tokens": 0,
        "text_tokens": 140
      },
      "total_tokens": 953
    }
  }
]
```

</details>

## Parameters

▶messages\[]

`array`requiredminItems: 1maxItems: 500

deferred

`boolean`

frequency\_penalty

`number | null`

logprobs

`boolean`

max\_completion\_tokens

`integer | null`

max\_tokens

`integer | null`

n

`integer | null`

parallel\_tool\_calls

`boolean`

presence\_penalty

`number | null`

reasoning\_effort

`string | null`enum: none, low, medium, high

▶response\_format

`one of`

▶search\_parameters{}

`object`

seed

`integer | null`

stop

`array | null`

stream

`boolean`

▶stream\_options{}

`object`

temperature

`number | null`

▶tool\_choice

`one of`

tools

`array | null`

top\_logprobs

`integer | null`

top\_p

`number | null`

user

`string`

▶web\_search\_options{}

`object`

id

`string`

object

`string`const: chat.completion

created

`number`

model

`string`

▶choices\[]

`array`

citations

`array | null`

output\_files

`array | null`

system\_fingerprint

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.3/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.3/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.3/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.3/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-4.3/#page","headline":"Grok 4.3","description":"xAI's Grok 4.3 model with a 1M-token context window and strong agentic tool calling with minimal hallucinations. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (none, low, medium, high).","url":"https://developers.cloudflare.com/ai/models/xai/grok-4.3/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's Grok 4.5, a frontier model built for coding, agentic tasks, and knowledge work. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (low, medium, high).
title: Grok 4.5
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok 4.5

Text Generation • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-4.5/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-4.5`

- Third-party
- Zero data retention

xAI's Grok 4.5, a frontier model built for coding, agentic tasks, and knowledge work. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (low, medium, high).

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 500,000 tokens |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service-enterprise) |
| More information | [link ↗](https://docs.x.ai/developers/models/grok-4.5) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input <200k (per 1M)$2.00</li><li>Cached input <200k (per 1M)$0.30</li><li>Output <200k (per 1M)$6.00</li><li>Input >=200k (per 1M)$4.00</li><li>Cached input >=200k (per 1M)$0.60</li><li>Output >=200k (per 1M)$12.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-4.5',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.5",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
**First Law (Conservation of Energy):**  
The total energy of an isolated system is constant. Energy can be transformed from one form to another (e.g., heat into work) but cannot be created or destroyed. For a closed thermodynamic system this is commonly expressed as  
\[
\Delta U = Q - W
\]  
(where \(\Delta U\) is the change in internal energy, \(Q\) is heat added to the system, and \(W\) is work done by the system; sign conventions can vary).

**Second Law (Entropy / Direction of Processes):**  
The entropy of an isolated system never decreases; spontaneous processes increase the total entropy of the universe. Equivalent classical statements include:  
- Heat does not spontaneously flow from a colder body to a hotter body (Clausius).  
- It is impossible to convert heat completely into work in a cyclic process without other effects (Kelvin–Planck).  

This law introduces the thermodynamic arrow of time and the concept of irreversible processes.

**Third Law (Nernst Heat Theorem / Absolute Zero):**  
As the temperature of a system approaches absolute zero (0 K), the entropy approaches a minimum value (commonly taken as zero for a perfect crystalline substance). A practical consequence is that absolute zero is unattainable in a finite number of thermodynamic processes.

(Note: A “zeroth” law is also recognized—systems in thermal equilibrium with a third system are in equilibrium with each other, defining temperature—but it is not counted among the classical three laws.)

These laws form the foundation of classical thermodynamics and constrain all macroscopic energy-conversion processes.
```

```json
{
  "id": "02cf6d3a-3354-9195-bdb5-199a2c5a88b2",
  "object": "chat.completion",
  "created": 1784118519,
  "model": "grok-4.5",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "**First Law (Conservation of Energy):**  \nThe total energy of an isolated system is constant. Energy can be transformed from one form to another (e.g., heat into work) but cannot be created or destroyed. For a closed thermodynamic system this is commonly expressed as  \n\\[\n\\Delta U = Q - W\n\\]  \n(where \\(\\Delta U\\) is the change in internal energy, \\(Q\\) is heat added to the system, and \\(W\\) is work done by the system; sign conventions can vary).\n\n**Second Law (Entropy / Direction of Processes):**  \nThe entropy of an isolated system never decreases; spontaneous processes increase the total entropy of the universe. Equivalent classical statements include:  \n- Heat does not spontaneously flow from a colder body to a hotter body (Clausius).  \n- It is impossible to convert heat completely into work in a cyclic process without other effects (Kelvin–Planck).  \n\nThis law introduces the thermodynamic arrow of time and the concept of irreversible processes.\n\n**Third Law (Nernst Heat Theorem / Absolute Zero):**  \nAs the temperature of a system approaches absolute zero (0 K), the entropy approaches a minimum value (commonly taken as zero for a perfect crystalline substance). A practical consequence is that absolute zero is unattainable in a finite number of thermodynamic processes.\n\n(Note: A “zeroth” law is also recognized—systems in thermal equilibrium with a third system are in equilibrium with each other, defining temperature—but it is not counted among the classical three laws.)\n\nThese laws form the foundation of classical thermodynamics and constrain all macroscopic energy-conversion processes.",
        "reasoning_content": "The question is: \"What are the three laws of thermodynamics?\"\nThe three laws of thermodynamics are:\n\n1. **First Law**: Energy is conserved. In any process, the total energy of an isolated system remains constant; it can only change form (e.g., heat to work).",
        "refusal": null
      }
    }
  ],
  "service_tier": "default",
  "system_fingerprint": "fp_a39489019fa99b6e",
  "usage": {
    "prompt_tokens": 214,
    "completion_tokens": 323,
    "total_tokens": 924,
    "prompt_tokens_details": {
      "text_tokens": 214,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 387,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 44960000,
    "num_sources_used": 0
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With System Message** — Using a system message to set context</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.5',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.5",
  "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"
    }
  ]
}'
```

````
To read a JSON file in Python, use the built-in `json` module:

```python
import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(data)
```

### Notes
- `json.load(f)` reads from a file object and returns a Python object (`dict`, `list`, etc.).
- Prefer `with open(...)` so the file is closed automatically.
- Use `encoding="utf-8"` for reliable handling of non-ASCII text.

### If you already have a JSON string
```python
import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)
```

### Basic error handling
```python
import json

try:
    with open("data.json", "r", encoding="utf-8") as f:
        data = json.load(f)
except FileNotFoundError:
    print("File not found")
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")
```
````

```json
{
  "id": "e5c0b732-b377-9257-a707-558da370c135",
  "object": "chat.completion",
  "created": 1784118525,
  "model": "grok-4.5",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "To read a JSON file in Python, use the built-in `json` module:\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n\nprint(data)\n```\n\n### Notes\n- `json.load(f)` reads from a file object and returns a Python object (`dict`, `list`, etc.).\n- Prefer `with open(...)` so the file is closed automatically.\n- Use `encoding=\"utf-8\"` for reliable handling of non-ASCII text.\n\n### If you already have a JSON string\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)\n```\n\n### Basic error handling\n```python\nimport json\n\ntry:\n    with open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n        data = json.load(f)\nexcept FileNotFoundError:\n    print(\"File not found\")\nexcept json.JSONDecodeError as e:\n    print(f\"Invalid JSON: {e}\")\n```",
        "reasoning_content": "The user is asking how to read a JSON file in Python. This is a straightforward coding question. I should provide a clear, helpful answer with code examples.\n",
        "refusal": null
      }
    }
  ],
  "service_tier": "default",
  "system_fingerprint": "fp_a39489019fa99b6e",
  "usage": {
    "prompt_tokens": 229,
    "completion_tokens": 237,
    "total_tokens": 570,
    "prompt_tokens_details": {
      "text_tokens": 229,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 104,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 23120000,
    "num_sources_used": 0
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.5',
  {
    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)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.5",
  "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"
    }
  ]
}'
```

```
**Great choice—there are tons of excellent stops depending on whether you take the faster inland route (I-5, ~5–6 hours) or the scenic coastal route (Highway 1 / Pacific Coast Highway, ~8–10+ hours with stops).**

Most people planning a fun road trip prefer the **coastal route** for the views and variety. Here are some of the best places to stop (roughly north to south):

### Top Recommended Stops (Coastal Route via Hwy 1)
1. **Monterey / Carmel-by-the-Sea** (about 2 hours from SF)  
   - Walk Cannery Row, visit the Monterey Bay Aquarium, or stroll the charming village of Carmel. Great for a coffee, lunch, or short hike.

2. **Big Sur** (highlight of the drive)  
   - Iconic stops: Bixby Creek Bridge viewpoint, McWay Falls (waterfall onto the beach), and pullouts for dramatic ocean cliffs. Allow extra time—roads can be winding and parking limited. Pfeiffer Beach or Julia Pfeiffer Burns State Park are worth it if you have time.

3. **Hearst Castle (San Simeon)**  
   - Tour the opulent hilltop estate of William Randolph Hearst. Book tickets ahead if possible. Nearby elephant seal viewing at Piedras Blancas is free and fascinating.

4. **San Luis Obispo / Pismo Beach / Avila Beach**  
   - SLO has a fun downtown, bubblegum alley, and good food. Pismo is classic California beach vibes (dunes, pier). Great mid-trip stretch and meal stop.

5. **Santa Barbara**  
   - Beautiful Spanish-style downtown, State Street, waterfront, and nearby wine tasting in the Santa Ynez Valley if you detour a bit. Perfect last major stop before LA (about 1.5–2 hours remaining).

### Other Solid Options
- **Santa Cruz** (early stop) – Boardwalk, surfing vibe, or nearby redwoods.
- **Paso Robles** (if you cut inland a bit via Hwy 46) – Excellent wine country for tastings.
- **Solvang** (near Santa Barbara) – Quaint Danish-themed town with bakeries and windmills.
- Quick nature hits: Point Lobos State Natural Reserve (near Carmel) or Elephant Seal Rookery.

### Practical Tips
- **Timing**: Start early from SF to enjoy daylight in Big Sur. The full coastal drive with a few stops easily fills a full day (or make it overnight in SLO/Pismo/Santa Barbara).
- **Food**: Fresh seafood in Monterey, burgers or farm-to-table in SLO, tacos or wine-country bites farther south.
- **Gas & rest**: Fill up before Big Sur (limited services). Traffic can build near LA, especially weekends.
- **Alternatives**: Pure I-5 is faster but boring (mostly Central Valley farmland). A hybrid (I-5 partway then cut over to the coast) works if you’re short on time.
- Check road conditions—Hwy 1 in Big Sur occasionally has closures due to slides.

**What kind of trip are you aiming for?** (e.g., scenic/nature-focused, food & wine, beaches, family-friendly, one long day vs. overnight, any must-sees or avoidances like crowds?) Also, roughly how many days/hours do you have, and any interests (hiking, photography, history, kids, etc.)? I can refine a sample itinerary or map out timing from there.
```

```json
{
  "id": "84bb1a71-ed73-9245-9e02-987a9126e53b",
  "object": "chat.completion",
  "created": 1784118527,
  "model": "grok-4.5",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "**Great choice—there are tons of excellent stops depending on whether you take the faster inland route (I-5, ~5–6 hours) or the scenic coastal route (Highway 1 / Pacific Coast Highway, ~8–10+ hours with stops).**\n\nMost people planning a fun road trip prefer the **coastal route** for the views and variety. Here are some of the best places to stop (roughly north to south):\n\n### Top Recommended Stops (Coastal Route via Hwy 1)\n1. **Monterey / Carmel-by-the-Sea** (about 2 hours from SF)  \n   - Walk Cannery Row, visit the Monterey Bay Aquarium, or stroll the charming village of Carmel. Great for a coffee, lunch, or short hike.\n\n2. **Big Sur** (highlight of the drive)  \n   - Iconic stops: Bixby Creek Bridge viewpoint, McWay Falls (waterfall onto the beach), and pullouts for dramatic ocean cliffs. Allow extra time—roads can be winding and parking limited. Pfeiffer Beach or Julia Pfeiffer Burns State Park are worth it if you have time.\n\n3. **Hearst Castle (San Simeon)**  \n   - Tour the opulent hilltop estate of William Randolph Hearst. Book tickets ahead if possible. Nearby elephant seal viewing at Piedras Blancas is free and fascinating.\n\n4. **San Luis Obispo / Pismo Beach / Avila Beach**  \n   - SLO has a fun downtown, bubblegum alley, and good food. Pismo is classic California beach vibes (dunes, pier). Great mid-trip stretch and meal stop.\n\n5. **Santa Barbara**  \n   - Beautiful Spanish-style downtown, State Street, waterfront, and nearby wine tasting in the Santa Ynez Valley if you detour a bit. Perfect last major stop before LA (about 1.5–2 hours remaining).\n\n### Other Solid Options\n- **Santa Cruz** (early stop) – Boardwalk, surfing vibe, or nearby redwoods.\n- **Paso Robles** (if you cut inland a bit via Hwy 46) – Excellent wine country for tastings.\n- **Solvang** (near Santa Barbara) – Quaint Danish-themed town with bakeries and windmills.\n- Quick nature hits: Point Lobos State Natural Reserve (near Carmel) or Elephant Seal Rookery.\n\n### Practical Tips\n- **Timing**: Start early from SF to enjoy daylight in Big Sur. The full coastal drive with a few stops easily fills a full day (or make it overnight in SLO/Pismo/Santa Barbara).\n- **Food**: Fresh seafood in Monterey, burgers or farm-to-table in SLO, tacos or wine-country bites farther south.\n- **Gas & rest**: Fill up before Big Sur (limited services). Traffic can build near LA, especially weekends.\n- **Alternatives**: Pure I-5 is faster but boring (mostly Central Valley farmland). A hybrid (I-5 partway then cut over to the coast) works if you’re short on time.\n- Check road conditions—Hwy 1 in Big Sur occasionally has closures due to slides.\n\n**What kind of trip are you aiming for?** (e.g., scenic/nature-focused, food & wine, beaches, family-friendly, one long day vs. overnight, any must-sees or avoidances like crowds?) Also, roughly how many days/hours do you have, and any interests (hiking, photography, history, kids, etc.)? I can refine a sample itinerary or map out timing from there.",
        "reasoning_content": "The user is asking for good places to stop on a road trip from San Francisco to Los Angeles. This is a continuation of planning a road trip.\n",
        "refusal": null
      }
    }
  ],
  "service_tier": "default",
  "system_fingerprint": "fp_a39489019fa99b6e",
  "usage": {
    "prompt_tokens": 274,
    "completion_tokens": 742,
    "total_tokens": 1207,
    "prompt_tokens_details": {
      "text_tokens": 274,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 191,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 59540000,
    "num_sources_used": 0
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Coding with Low Reasoning Effort** — Setting a lower reasoning effort for a fast, low-latency response</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.5',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content:
          'Find and fix the bug, then explain it: function median(a){a.sort();return a[a.length/2]}',
        role: 'user',
      },
    ],
    reasoning_effort: 'low',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.5",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Find and fix the bug, then explain it: function median(a){a.sort();return a[a.length/2]}",
      "role": "user"
    }
  ],
  "reasoning_effort": "low"
}'
```

````
```js
function median(a) {
  if (!Array.isArray(a) || a.length === 0) return undefined;
  const sorted = a.slice().sort((x, y) => x - y); // copy + numeric sort
  const mid = Math.floor(sorted.length / 2);
  return sorted.length % 2
    ? sorted[mid]
    : (sorted[mid - 1] + sorted[mid]) / 2;
}
```

**Bugs fixed**
1. **Default `sort()` is lexicographic** (e.g. `[10, 2, 3]` → `["10","2","3"]`). A numeric comparator is required.
2. **`a[a.length/2]` is wrong**:
   - For odd length (e.g. 5) you get a float index `2.5` → `undefined`.
   - For even length the conventional median is the average of the two central elements, not a single one.
3. **In-place mutation** – `sort()` changes the caller’s array; a shallow copy avoids that.
4. Empty / non-array input is now handled safely.
````

```json
{
  "id": "bb92a233-a9ac-9a94-bdf1-6e5e6a14c060",
  "object": "chat.completion",
  "created": 1784118539,
  "model": "grok-4.5",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "```js\nfunction median(a) {\n  if (!Array.isArray(a) || a.length === 0) return undefined;\n  const sorted = a.slice().sort((x, y) => x - y); // copy + numeric sort\n  const mid = Math.floor(sorted.length / 2);\n  return sorted.length % 2\n    ? sorted[mid]\n    : (sorted[mid - 1] + sorted[mid]) / 2;\n}\n```\n\n**Bugs fixed**\n1. **Default `sort()` is lexicographic** (e.g. `[10, 2, 3]` → `[\"10\",\"2\",\"3\"]`). A numeric comparator is required.\n2. **`a[a.length/2]` is wrong**:\n   - For odd length (e.g. 5) you get a float index `2.5` → `undefined`.\n   - For even length the conventional median is the average of the two central elements, not a single one.\n3. **In-place mutation** – `sort()` changes the caller’s array; a shallow copy avoids that.\n4. Empty / non-array input is now handled safely.",
        "reasoning_content": "The user wants me to find and fix the bug in this function: function median(a){a.sort();return a[a.length/2]}\nThe bug is that `a.length/2` coerces to an integer index (so for odd-length arrays it actually returns the element at `floor(length/2)`, not the true middle), and the default string sort makes numeric data come out wrong. It also mutates the caller’s array.",
        "refusal": null
      }
    }
  ],
  "service_tier": "default",
  "system_fingerprint": "fp_a39489019fa99b6e",
  "usage": {
    "prompt_tokens": 233,
    "completion_tokens": 250,
    "total_tokens": 1115,
    "prompt_tokens_details": {
      "text_tokens": 233,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 632,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 55660000,
    "num_sources_used": 0
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.5',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.5",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
```

````
**Recursion** is a programming technique where a function calls itself to solve a smaller instance of the same problem, until it reaches a simple stopping condition.

### Core Idea
- Break a problem into smaller subproblems of the same type.
- Each recursive call works on a reduced version of the input.
- Eventually hit a **base case** that returns a value without further calls (this prevents infinite recursion).
- Combine the results as the calls unwind.

Without a proper base case, recursion continues forever (or until the call stack overflows).

### Simple Example: Factorial
The factorial of a non-negative integer \( n \) (written \( n! \)) is:

- \( 0! = 1 \) and \( 1! = 1 \)
- \( n! = n \times (n-1)! \) for \( n > 1 \)

**Python implementation:**

```python
def factorial(n):
    # Base case: stops the recursion
    if n == 0 or n == 1:
        return 1
    # Recursive case: calls itself with a smaller argument
    else:
        return n * factorial(n - 1)
```

**How it works for `factorial(5)`:**

1. `factorial(5)` → \( 5 \times \) `factorial(4)`
2. `factorial(4)` → \( 4 \times \) `factorial(3)`
3. `factorial(3)` → \( 3 \times \) `factorial(2)`
4. `factorial(2)` → \( 2 \times \) `factorial(1)`
5. `factorial(1)` → returns `1` (base case)

Now the calls return and multiply:

- \( 2 \times 1 = 2 \)
- \( 3 \times 2 = 6 \)
- \( 4 \times 6 = 24 \)
- \( 5 \times 24 = 120 \)

Result: `120`

### Why This Works
Each call reduces \( n \) by 1, guaranteed to eventually hit the base case. The multiplications happen on the way back up the call stack.

### Quick Tips
- Always define a clear base case first.
- Ensure every recursive path moves toward that base case.
- Recursion is elegant for problems with natural recursive structure (trees, divide-and-conquer, factorial, Fibonacci, etc.), but deep recursion can cause stack overflows—iteration or tail-call optimization can be alternatives when needed.

This pattern (base case + recursive case that shrinks the problem) is the essence of recursion.
````

```json
[
  {
    "id": "b2ed7fb2-3e57-96e3-9a6c-464dd11745eb",
    "object": "chat.completion.chunk",
    "created": 1784118545,
    "model": "grok-4.5",
    "choices": [
      {
        "index": 0,
        "delta": {
          "reasoning_content": "The",
          "role": "assistant"
        }
      }
    ],
    "system_fingerprint": "fp_a39489019fa99b6e",
    "service_tier": "default"
  },
  {
    "id": "b2ed7fb2-3e57-96e3-9a6c-464dd11745eb",
    "object": "chat.completion.chunk",
    "created": 1784118545,
    "model": "grok-4.5",
    "choices": [
      {
        "index": 0,
        "delta": {
          "reasoning_content": " user"
        }
      }
    ],
    "system_fingerprint": "fp_a39489019fa99b6e",
    "service_tier": "default"
  },
  "... 559 more chunks omitted ...",
  {
    "id": "b2ed7fb2-3e57-96e3-9a6c-464dd11745eb",
    "object": "chat.completion.chunk",
    "created": 1784118551,
    "model": "grok-4.5",
    "choices": [],
    "usage": {
      "prompt_tokens": 216,
      "completion_tokens": 544,
      "total_tokens": 1040,
      "prompt_tokens_details": {
        "text_tokens": 216,
        "audio_tokens": 0,
        "image_tokens": 0,
        "cached_tokens": 128
      },
      "completion_tokens_details": {
        "reasoning_tokens": 280,
        "audio_tokens": 0,
        "accepted_prediction_tokens": 0,
        "rejected_prediction_tokens": 0
      },
      "num_sources_used": 0,
      "cost_in_usd_ticks": 51840000
    },
    "system_fingerprint": "fp_a39489019fa99b6e",
    "service_tier": "default"
  }
]
```

</details>

<details>

<summary>**Image Understanding** — Analyze an image supplied alongside a text prompt</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.5',
  {
    messages: [
      {
        content: [
          {
            image_url: { url: 'https://v3.fal.media/files/koala/NLVPfOI4XL1cWT2PmmqT3_Hope.png' },
            type: 'image_url',
          },
          {
            text: 'Describe the person in this image and their surroundings in one sentence.',
            type: 'text',
          },
        ],
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.5",
  "messages": [
    {
      "content": [
        {
          "image_url": {
            "url": "https://v3.fal.media/files/koala/NLVPfOI4XL1cWT2PmmqT3_Hope.png"
          },
          "type": "image_url"
        },
        {
          "text": "Describe the person in this image and their surroundings in one sentence.",
          "type": "text"
        }
      ],
      "role": "user"
    }
  ]
}'
```

```
A smiling young woman with dark hair pulled back, wearing a blue knit sweater and multiple rings, holds a small fuzzy microphone while posing in a cozy indoor room with warm lighting, a framed photo collage on the wall, and decorative elements like a plant and artwork.
```

```json
{
  "id": "f864bc43-a81c-995b-bb6c-253294c05423",
  "object": "chat.completion",
  "created": 1784491003,
  "model": "grok-4.5",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "A smiling young woman with dark hair pulled back, wearing a blue knit sweater and multiple rings, holds a small fuzzy microphone while posing in a cozy indoor room with warm lighting, a framed photo collage on the wall, and decorative elements like a plant and artwork.",
        "reasoning_content": "The user wants me to describe the person in the image and their surroundings in one sentence.\n",
        "refusal": null
      }
    }
  ],
  "service_tier": "default",
  "system_fingerprint": "fp_a39489019fa99b6e",
  "usage": {
    "prompt_tokens": 2628,
    "completion_tokens": 52,
    "total_tokens": 2827,
    "prompt_tokens_details": {
      "text_tokens": 221,
      "audio_tokens": 0,
      "image_tokens": 2407,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 147,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 62324000,
    "num_sources_used": 0
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Function Calling** — Force the model to return a typed function call</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.5',
  {
    messages: [{ content: 'What is the current temperature in San Francisco?', role: 'user' }],
    tool_choice: 'required',
    tools: [
      {
        function: {
          description: 'Get the current temperature for a city',
          name: 'get_temperature',
          parameters: {
            additionalProperties: false,
            properties: {
              city: { type: 'string' },
              unit: { enum: ['celsius', 'fahrenheit'], type: 'string' },
            },
            required: ['city', 'unit'],
            type: 'object',
          },
          strict: true,
        },
        type: 'function',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.5",
  "messages": [
    {
      "content": "What is the current temperature in San Francisco?",
      "role": "user"
    }
  ],
  "tool_choice": "required",
  "tools": [
    {
      "function": {
        "description": "Get the current temperature for a city",
        "name": "get_temperature",
        "parameters": {
          "additionalProperties": false,
          "properties": {
            "city": {
              "type": "string"
            },
            "unit": {
              "enum": [
                "celsius",
                "fahrenheit"
              ],
              "type": "string"
            }
          },
          "required": [
            "city",
            "unit"
          ],
          "type": "object"
        },
        "strict": true
      },
      "type": "function"
    }
  ]
}'
```

```
I'll check the current temperature in San Francisco for you.
```

```json
{
  "id": "5e8b5367-6685-95f6-8a15-fd3d5e785de5",
  "object": "chat.completion",
  "created": 1784491007,
  "model": "grok-4.5",
  "choices": [
    {
      "index": 0,
      "finish_reason": "tool_calls",
      "message": {
        "role": "assistant",
        "content": "I'll check the current temperature in San Francisco for you.",
        "reasoning_content": "The user wants the current temperature in San Francisco. I have a tool for that: get_temperature. I need to specify the city and the unit. The city is San Francisco, but what unit? It doesn't specify,...",
        "refusal": null,
        "tool_calls": [
          {
            "id": "call-206bc4d0-666a-48ea-8b03-28467f98b9df-0",
            "type": "function",
            "function": {
              "name": "get_temperature",
              "arguments": "{\"city\":\"San Francisco\",\"unit\":\"fahrenheit\"}"
            }
          }
        ]
      }
    }
  ],
  "service_tier": "default",
  "system_fingerprint": "fp_a39489019fa99b6e",
  "usage": {
    "prompt_tokens": 333,
    "completion_tokens": 31,
    "total_tokens": 445,
    "prompt_tokens_details": {
      "text_tokens": 333,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 81,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 11204000,
    "num_sources_used": 0
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Structured Output** — Constrain the response to a JSON schema</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.5',
  {
    messages: [
      {
        content: 'Classify the sentiment of: The launch was smooth and customers loved it.',
        role: 'user',
      },
    ],
    response_format: {
      json_schema: {
        name: 'sentiment_result',
        schema: {
          additionalProperties: false,
          properties: {
            confidence: { maximum: 1, minimum: 0, type: 'number' },
            sentiment: { enum: ['positive', 'neutral', 'negative'], type: 'string' },
          },
          required: ['sentiment', 'confidence'],
          type: 'object',
        },
        strict: true,
      },
      type: 'json_schema',
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.5",
  "messages": [
    {
      "content": "Classify the sentiment of: The launch was smooth and customers loved it.",
      "role": "user"
    }
  ],
  "response_format": {
    "json_schema": {
      "name": "sentiment_result",
      "schema": {
        "additionalProperties": false,
        "properties": {
          "confidence": {
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "sentiment": {
            "enum": [
              "positive",
              "neutral",
              "negative"
            ],
            "type": "string"
          }
        },
        "required": [
          "sentiment",
          "confidence"
        ],
        "type": "object"
      },
      "strict": true
    },
    "type": "json_schema"
  }
}'
```

```
{"confidence":0.95,"sentiment":"positive"}
```

```json
{
  "id": "da248276-7d35-9291-9645-7f495af55158",
  "object": "chat.completion",
  "created": 1784491010,
  "model": "grok-4.5",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "{\"confidence\":0.95,\"sentiment\":\"positive\"}",
        "reasoning_content": "The user wants me to classify the sentiment of: \"The launch was smooth and customers loved it.\"\n",
        "refusal": null
      }
    }
  ],
  "service_tier": "default",
  "system_fingerprint": "fp_a39489019fa99b6e",
  "usage": {
    "prompt_tokens": 300,
    "completion_tokens": 12,
    "total_tokens": 472,
    "prompt_tokens_details": {
      "text_tokens": 300,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 160,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 14144000,
    "num_sources_used": 0
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

▶messages\[]

`array`requiredminItems: 1maxItems: 500

max\_completion\_tokens

`integer | null`

max\_tokens

`integer | null`

n

`integer | null`

parallel\_tool\_calls

`boolean`

prompt\_cache\_key

`string`

reasoning\_effort

`string | null`enum: low, medium, high

▶response\_format

`one of`

▶search\_parameters{}

`object`

seed

`integer | null`

service\_tier

`string`enum: default, priority

stream

`boolean`

▶stream\_options{}

`object`

temperature

`number | null`

▶tool\_choice

`one of`

tools

`array | null`

top\_p

`number | null`

user

`string`

▶web\_search\_options{}

`object`

id

`string`

object

`string`const: chat.completion

created

`number`

model

`string`

▶choices\[]

`array`

citations

`array | null`

output\_files

`array | null`

service\_tier

`string`enum: default, priority

system\_fingerprint

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.5/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.5/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.5/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.5/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-4.5/#page","headline":"Grok 4.5","description":"xAI's Grok 4.5, a frontier model built for coding, agentic tasks, and knowledge work. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (low, medium, high).","url":"https://developers.cloudflare.com/ai/models/xai/grok-4.5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's Grok 4.6, a flagship reasoning model for coding, agentic tasks, and visual work. Accepts text and image inputs, and supports function calling and structured outputs.
title: Grok 4.6
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok 4.6

Text Generation • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-4.6/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-4.6`

- Third-party
- Zero data retention

xAI's Grok 4.6, a flagship reasoning model for coding, agentic tasks, and visual work. Accepts text and image inputs, and supports function calling and structured outputs.

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 500,000 tokens |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service-enterprise) |
| More information | [link ↗](https://docs.x.ai/developers/models) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input <200k (per 1M)$2.00</li><li>Cached input <200k (per 1M)$0.50</li><li>Output <200k (per 1M)$6.00</li><li>Input >=200k (per 1M)$4.00</li><li>Cached input >=200k (per 1M)$1.00</li><li>Output >=200k (per 1M)$12.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-4.6',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.6",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
**First law (conservation of energy):** The internal energy of an isolated system is constant; energy can change form (e.g., heat \(\leftrightarrow\) work) but is neither created nor destroyed. In equation form, \(\Delta U = Q - W\) (sign conventions vary).

**Second law (entropy/directionality):** The entropy of an isolated system never decreases; spontaneous processes increase total entropy. Equivalently, heat cannot spontaneously flow from a colder body to a hotter one, and no cyclic process can convert heat entirely into work with 100% efficiency (Kelvin–Planck and Clausius statements).

**Third law (unattainability of absolute zero):** As temperature approaches 0 K, the entropy of a perfect crystal approaches a minimum (conventionally taken as zero). Absolute zero is therefore unattainable in a finite number of steps.

(The zeroth law, which underpins the definition of temperature via thermal equilibrium, is sometimes listed separately and was formalized later.)

These statements have multiple equivalent formulations; the versions above are the most common in introductory physics/chemistry.
```

```json
{
  "id": "46e7d84b-3292-9934-9830-10a2926ac872",
  "object": "chat.completion",
  "created": 1786550938,
  "model": "grok-4.6",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "**First law (conservation of energy):** The internal energy of an isolated system is constant; energy can change form (e.g., heat \\(\\leftrightarrow\\) work) but is neither created nor destroyed. In equation form, \\(\\Delta U = Q - W\\) (sign conventions vary).\n\n**Second law (entropy/directionality):** The entropy of an isolated system never decreases; spontaneous processes increase total entropy. Equivalently, heat cannot spontaneously flow from a colder body to a hotter one, and no cyclic process can convert heat entirely into work with 100% efficiency (Kelvin–Planck and Clausius statements).\n\n**Third law (unattainability of absolute zero):** As temperature approaches 0 K, the entropy of a perfect crystal approaches a minimum (conventionally taken as zero). Absolute zero is therefore unattainable in a finite number of steps.\n\n(The zeroth law, which underpins the definition of temperature via thermal equilibrium, is sometimes listed separately and was formalized later.)\n\nThese statements have multiple equivalent formulations; the versions above are the most common in introductory physics/chemistry.",
        "reasoning_content": "The question is: \"What are the three laws of thermodynamics?\"\nThe three laws of thermodynamics are:\n\n1. **First Law**: Energy is conserved. It cannot be created or destroyed, only converted between forms. The change in internal energy of a system equals the heat added to it minus the work done by it: ΔU = Q - W.\n\n2.",
        "refusal": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 214,
    "completion_tokens": 220,
    "total_tokens": 870,
    "prompt_tokens_details": {
      "text_tokens": 214,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 436,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "num_sources_used": 0,
    "cost_in_usd_ticks": 41720000
  },
  "system_fingerprint": "fp_a7b4933f4a93564d",
  "service_tier": "default"
}
```

## Examples

<details>

<summary>**Image Understanding** — Analyze an image supplied alongside a text prompt</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.6',
  {
    messages: [
      {
        content: [
          {
            image_url: { url: 'https://v3.fal.media/files/koala/NLVPfOI4XL1cWT2PmmqT3_Hope.png' },
            type: 'image_url',
          },
          {
            text: 'Describe the person in this image and their surroundings in one sentence.',
            type: 'text',
          },
        ],
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.6",
  "messages": [
    {
      "content": [
        {
          "image_url": {
            "url": "https://v3.fal.media/files/koala/NLVPfOI4XL1cWT2PmmqT3_Hope.png"
          },
          "type": "image_url"
        },
        {
          "text": "Describe the person in this image and their surroundings in one sentence.",
          "type": "text"
        }
      ],
      "role": "user"
    }
  ]
}'
```

```
A smiling young woman with dark hair in a navy knit sweater holds a fuzzy microphone while seated in a cozy room with a white fireplace mantel, framed photo collage, and warm lighting.
```

```json
{
  "id": "5f620cf3-cd07-9a84-99d8-00f6f8712f95",
  "object": "chat.completion",
  "created": 1786550950,
  "model": "grok-4.6",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "A smiling young woman with dark hair in a navy knit sweater holds a fuzzy microphone while seated in a cozy room with a white fireplace mantel, framed photo collage, and warm lighting.",
        "reasoning_content": "The task is: \"Describe the person in this image and their surroundings in one sentence.\"\n",
        "refusal": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 2628,
    "completion_tokens": 36,
    "total_tokens": 2925,
    "prompt_tokens_details": {
      "text_tokens": 221,
      "audio_tokens": 0,
      "image_tokens": 2407,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 261,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "num_sources_used": 0,
    "cost_in_usd_ticks": 68460000
  },
  "system_fingerprint": "fp_a7b4933f4a93564d",
  "service_tier": "default"
}
```

</details>

<details>

<summary>**Function Calling** — Force the model to return a typed function call</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.6',
  {
    messages: [{ content: 'What is the current temperature in San Francisco?', role: 'user' }],
    tool_choice: 'required',
    tools: [
      {
        function: {
          description: 'Get the current temperature for a city',
          name: 'get_temperature',
          parameters: {
            additionalProperties: false,
            properties: {
              city: { type: 'string' },
              unit: { enum: ['celsius', 'fahrenheit'], type: 'string' },
            },
            required: ['city', 'unit'],
            type: 'object',
          },
          strict: true,
        },
        type: 'function',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.6",
  "messages": [
    {
      "content": "What is the current temperature in San Francisco?",
      "role": "user"
    }
  ],
  "tool_choice": "required",
  "tools": [
    {
      "function": {
        "description": "Get the current temperature for a city",
        "name": "get_temperature",
        "parameters": {
          "additionalProperties": false,
          "properties": {
            "city": {
              "type": "string"
            },
            "unit": {
              "enum": [
                "celsius",
                "fahrenheit"
              ],
              "type": "string"
            }
          },
          "required": [
            "city",
            "unit"
          ],
          "type": "object"
        },
        "strict": true
      },
      "type": "function"
    }
  ]
}'
```

```json
{
  "id": "d1c2cf6d-a4c2-9b8b-a6e3-ff60e4dd12b8",
  "object": "chat.completion",
  "created": 1786550955,
  "model": "grok-4.6",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "",
        "reasoning_content": "The user is asking for the current temperature in San Francisco. I have a tool called \"get_temperature\" that can get the current temperature for a city. It requires \"city\" and \"unit\".\n",
        "tool_calls": [
          {
            "id": "call-67aeb658-cc74-4375-b860-f18970d8187a-0",
            "function": {
              "name": "get_temperature",
              "arguments": "{\"city\":\"San Francisco\",\"unit\":\"fahrenheit\"}"
            },
            "type": "function"
          }
        ],
        "refusal": null
      },
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 333,
    "completion_tokens": 20,
    "total_tokens": 654,
    "prompt_tokens_details": {
      "text_tokens": 333,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 301,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "num_sources_used": 0,
    "cost_in_usd_ticks": 24000000
  },
  "system_fingerprint": "fp_a7b4933f4a93564d",
  "service_tier": "default"
}
```

</details>

<details>

<summary>**Structured Output** — Constrain the response to a JSON schema</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.6',
  {
    messages: [
      {
        content: 'Classify the sentiment of: The launch was smooth and customers loved it.',
        role: 'user',
      },
    ],
    response_format: {
      json_schema: {
        name: 'sentiment_result',
        schema: {
          additionalProperties: false,
          properties: {
            confidence: { maximum: 1, minimum: 0, type: 'number' },
            sentiment: { enum: ['positive', 'neutral', 'negative'], type: 'string' },
          },
          required: ['sentiment', 'confidence'],
          type: 'object',
        },
        strict: true,
      },
      type: 'json_schema',
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.6",
  "messages": [
    {
      "content": "Classify the sentiment of: The launch was smooth and customers loved it.",
      "role": "user"
    }
  ],
  "response_format": {
    "json_schema": {
      "name": "sentiment_result",
      "schema": {
        "additionalProperties": false,
        "properties": {
          "confidence": {
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "sentiment": {
            "enum": [
              "positive",
              "neutral",
              "negative"
            ],
            "type": "string"
          }
        },
        "required": [
          "sentiment",
          "confidence"
        ],
        "type": "object"
      },
      "strict": true
    },
    "type": "json_schema"
  }
}'
```

```
{"confidence":0.95,"sentiment":"positive"}
```

```json
{
  "id": "e89a3a47-b193-9785-9c35-f4dd3c098107",
  "object": "chat.completion",
  "created": 1786550957,
  "model": "grok-4.6",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "{\"confidence\":0.95,\"sentiment\":\"positive\"}",
        "reasoning_content": "The task is to classify the sentiment of: \"The launch was smooth and customers loved it.\"\n",
        "refusal": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 300,
    "completion_tokens": 12,
    "total_tokens": 607,
    "prompt_tokens_details": {
      "text_tokens": 300,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 295,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "num_sources_used": 0,
    "cost_in_usd_ticks": 22500000
  },
  "system_fingerprint": "fp_a7b4933f4a93564d",
  "service_tier": "default"
}
```

</details>

## Parameters

▶messages\[]

`array`requiredminItems: 1maxItems: 500

max\_completion\_tokens

`integer | null`

max\_tokens

`integer | null`

n

`integer | null`

parallel\_tool\_calls

`boolean`

prompt\_cache\_key

`string`

reasoning\_effort

`string | null`enum: low, medium, high

▶response\_format

`one of`

▶search\_parameters{}

`object`

seed

`integer | null`

service\_tier

`string`enum: default, priority

stream

`boolean`

▶stream\_options{}

`object`

temperature

`number | null`

▶tool\_choice

`one of`

tools

`array | null`

top\_p

`number | null`

user

`string`

▶web\_search\_options{}

`object`

id

`string`

object

`string`const: chat.completion

created

`number`

model

`string`

▶choices\[]

`array`

citations

`array | null`

output\_files

`array | null`

service\_tier

`string`enum: default, priority

system\_fingerprint

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.6/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.6/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.6/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.6/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-4.6/#page","headline":"Grok 4.6","description":"xAI's Grok 4.6, a flagship reasoning model for coding, agentic tasks, and visual work. Accepts text and image inputs, and supports function calling and structured outputs.","url":"https://developers.cloudflare.com/ai/models/xai/grok-4.6/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's Grok 4.7, a frontier reasoning model for coding, agentic tasks, and knowledge work. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (low, medium, high, xhigh).
title: Grok 4.7
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok 4.7

Text Generation • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-4.7/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-4.7`

- Third-party
- Zero data retention

xAI's Grok 4.7, a frontier reasoning model for coding, agentic tasks, and knowledge work. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (low, medium, high, xhigh).

| Model Info | |
| --- | --- |
| Context Window [ ↗](https://developers.cloudflare.com/workers-ai/platform/glossary/) | 500,000 tokens |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service-enterprise) |
| More information | [link ↗](https://docs.x.ai/developers/models/grok-4.7) |
| Zero data retention | Yes |
| Request formats | Chat Completions |
| Pricing | <ul><li>Input <200k (per 1M)$2.00</li><li>Cached input <200k (per 1M)$0.50</li><li>Output <200k (per 1M)$6.00</li><li>Input >=200k (per 1M)$4.00</li><li>Cached input >=200k (per 1M)$1.00</li><li>Output >=200k (per 1M)$12.00</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-4.7',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.7",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
```

```
The three fundamental laws of thermodynamics (excluding the later-added zeroth law) are:

- **First law** (conservation of energy): Energy cannot be created or destroyed, only converted between forms. For a closed system, the change in internal energy \(\Delta U\) equals heat added \(Q\) minus work done by the system \(W\) (\(\Delta U = Q - W\)).

- **Second law** (entropy): The total entropy of an isolated system never decreases; it increases for irreversible processes and stays constant for reversible ones. Equivalently, heat does not spontaneously flow from a colder body to a hotter one, and no process can convert heat entirely into work without losses.

- **Third law**: The entropy of a perfect crystalline substance approaches a universal constant (often taken as zero) as temperature approaches absolute zero. Absolute zero is unattainable in any finite number of steps.

(The zeroth law, which defines thermal equilibrium and temperature, is sometimes listed alongside these.)
```

```json
{
  "id": "aa4ae961-5289-9990-b9fd-14db5eb33bc1",
  "object": "chat.completion",
  "created": 1790013433,
  "model": "grok-4.7",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The three fundamental laws of thermodynamics (excluding the later-added zeroth law) are:\n\n- **First law** (conservation of energy): Energy cannot be created or destroyed, only converted between forms. For a closed system, the change in internal energy \\(\\Delta U\\) equals heat added \\(Q\\) minus work done by the system \\(W\\) (\\(\\Delta U = Q - W\\)).\n\n- **Second law** (entropy): The total entropy of an isolated system never decreases; it increases for irreversible processes and stays constant for reversible ones. Equivalently, heat does not spontaneously flow from a colder body to a hotter one, and no process can convert heat entirely into work without losses.\n\n- **Third law**: The entropy of a perfect crystalline substance approaches a universal constant (often taken as zero) as temperature approaches absolute zero. Absolute zero is unattainable in any finite number of steps.\n\n(The zeroth law, which defines thermal equilibrium and temperature, is sometimes listed alongside these.)",
        "reasoning_content": "The question is: \"What are the three laws of thermodynamics?\"\nThe three laws of thermodynamics, as commonly referred to, are the first, second, and third laws. The zeroth law is sometimes listed separately as it sets the foundation for temperature.\n\nHere they are:\n\n**First Law**: Energy is conserved.",
        "refusal": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 214,
    "completion_tokens": 200,
    "total_tokens": 959,
    "prompt_tokens_details": {
      "text_tokens": 214,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 545,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "num_sources_used": 0,
    "cost_in_usd_ticks": 47060000
  },
  "system_fingerprint": "fp_c60958d81f66f847",
  "service_tier": "default"
}
```

## Examples

<details>

<summary>**Image Understanding** — Analyze an image supplied alongside a text prompt</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.7',
  {
    messages: [
      {
        content: [
          {
            image_url: { url: 'https://v3.fal.media/files/koala/NLVPfOI4XL1cWT2PmmqT3_Hope.png' },
            type: 'image_url',
          },
          {
            text: 'Describe the person in this image and their surroundings in one sentence.',
            type: 'text',
          },
        ],
        role: 'user',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.7",
  "messages": [
    {
      "content": [
        {
          "image_url": {
            "url": "https://v3.fal.media/files/koala/NLVPfOI4XL1cWT2PmmqT3_Hope.png"
          },
          "type": "image_url"
        },
        {
          "text": "Describe the person in this image and their surroundings in one sentence.",
          "type": "text"
        }
      ],
      "role": "user"
    }
  ]
}'
```

```
A young woman with dark hair pulled back, wearing a navy knit sweater, gold necklace, and several rings, sits smiling while holding a small microphone with a fuzzy windscreen in a softly lit room with framed photos and a lamp.
```

```json
{
  "id": "f3f060d5-351e-96cb-b367-1091568e9f60",
  "object": "chat.completion",
  "created": 1790013440,
  "model": "grok-4.7",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "A young woman with dark hair pulled back, wearing a navy knit sweater, gold necklace, and several rings, sits smiling while holding a small microphone with a fuzzy windscreen in a softly lit room with framed photos and a lamp.",
        "reasoning_content": "The user wants me to describe the person in the image and their surroundings in one sentence. Let me observe the image carefully.\n",
        "refusal": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 2679,
    "completion_tokens": 46,
    "total_tokens": 2951,
    "prompt_tokens_details": {
      "text_tokens": 272,
      "audio_tokens": 0,
      "image_tokens": 2407,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 226,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "num_sources_used": 0,
    "cost_in_usd_ticks": 67980000
  },
  "system_fingerprint": "fp_c60958d81f66f847",
  "service_tier": "default"
}
```

</details>

<details>

<summary>**Function Calling** — Force the model to return a typed function call</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.7',
  {
    messages: [{ content: 'What is the current temperature in San Francisco?', role: 'user' }],
    tool_choice: 'required',
    tools: [
      {
        function: {
          description: 'Get the current temperature for a city',
          name: 'get_temperature',
          parameters: {
            additionalProperties: false,
            properties: {
              city: { type: 'string' },
              unit: { enum: ['celsius', 'fahrenheit'], type: 'string' },
            },
            required: ['city', 'unit'],
            type: 'object',
          },
          strict: true,
        },
        type: 'function',
      },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.7",
  "messages": [
    {
      "content": "What is the current temperature in San Francisco?",
      "role": "user"
    }
  ],
  "tool_choice": "required",
  "tools": [
    {
      "function": {
        "description": "Get the current temperature for a city",
        "name": "get_temperature",
        "parameters": {
          "additionalProperties": false,
          "properties": {
            "city": {
              "type": "string"
            },
            "unit": {
              "enum": [
                "celsius",
                "fahrenheit"
              ],
              "type": "string"
            }
          },
          "required": [
            "city",
            "unit"
          ],
          "type": "object"
        },
        "strict": true
      },
      "type": "function"
    }
  ]
}'
```

```json
{
  "id": "c6f138a4-af95-98d8-aa31-016f3650c2ec",
  "object": "chat.completion",
  "created": 1790013442,
  "model": "grok-4.7",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "",
        "reasoning_content": "The user wants the current temperature in San Francisco. I have a tool for that: get_temperature. It requires city and unit.\n",
        "tool_calls": [
          {
            "id": "call-6774f30b-801b-4ad9-9c49-c8809040decc-0",
            "function": {
              "name": "get_temperature",
              "arguments": "{\"city\":\"San Francisco\",\"unit\":\"fahrenheit\"}"
            },
            "type": "function"
          }
        ],
        "refusal": null
      },
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 333,
    "completion_tokens": 17,
    "total_tokens": 428,
    "prompt_tokens_details": {
      "text_tokens": 333,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 78,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "num_sources_used": 0,
    "cost_in_usd_ticks": 10440000
  },
  "system_fingerprint": "fp_c60958d81f66f847",
  "service_tier": "default"
}
```

</details>

<details>

<summary>**Structured Output** — Constrain the response to a JSON schema</summary>



```ts
const response = await env.AI.run(
  'xai/grok-4.7',
  {
    messages: [
      {
        content: 'Classify the sentiment of: The launch was smooth and customers loved it.',
        role: 'user',
      },
    ],
    response_format: {
      json_schema: {
        name: 'sentiment_result',
        schema: {
          additionalProperties: false,
          properties: {
            confidence: { maximum: 1, minimum: 0, type: 'number' },
            sentiment: { enum: ['positive', 'neutral', 'negative'], type: 'string' },
          },
          required: ['sentiment', 'confidence'],
          type: 'object',
        },
        strict: true,
      },
      type: 'json_schema',
    },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.7",
  "messages": [
    {
      "content": "Classify the sentiment of: The launch was smooth and customers loved it.",
      "role": "user"
    }
  ],
  "response_format": {
    "json_schema": {
      "name": "sentiment_result",
      "schema": {
        "additionalProperties": false,
        "properties": {
          "confidence": {
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "sentiment": {
            "enum": [
              "positive",
              "neutral",
              "negative"
            ],
            "type": "string"
          }
        },
        "required": [
          "sentiment",
          "confidence"
        ],
        "type": "object"
      },
      "strict": true
    },
    "type": "json_schema"
  }
}'
```

```
{"confidence":0.95,"sentiment":"positive"}
```

```json
{
  "id": "db60c6df-4285-9e1a-97b8-30bb8136e5ac",
  "object": "chat.completion",
  "created": 1790013445,
  "model": "grok-4.7",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "{\"confidence\":0.95,\"sentiment\":\"positive\"}",
        "reasoning_content": "The user wants me to classify the sentiment of the sentence: \"The launch was smooth and customers loved it.\"\n",
        "refusal": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 300,
    "completion_tokens": 12,
    "total_tokens": 454,
    "prompt_tokens_details": {
      "text_tokens": 300,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 128
    },
    "completion_tokens_details": {
      "reasoning_tokens": 142,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "num_sources_used": 0,
    "cost_in_usd_ticks": 13320000
  },
  "system_fingerprint": "fp_c60958d81f66f847",
  "service_tier": "default"
}
```

</details>

## Parameters

▶messages\[]

`array`requiredminItems: 1maxItems: 500

max\_completion\_tokens

`integer | null`

max\_tokens

`integer | null`

n

`integer | null`

parallel\_tool\_calls

`boolean`

prompt\_cache\_key

`string`

reasoning\_effort

`string | null`enum: low, medium, high, xhigh

▶response\_format

`one of`

▶search\_parameters{}

`object`

seed

`integer | null`

service\_tier

`string`enum: default, priority

stream

`boolean`

▶stream\_options{}

`object`

temperature

`number | null`

▶tool\_choice

`one of`

tools

`array | null`

top\_p

`number | null`

user

`string`

▶web\_search\_options{}

`object`

id

`string`

object

`string`const: chat.completion

created

`number`

model

`string`

▶choices\[]

`array`

citations

`array | null`

output\_files

`array | null`

service\_tier

`string`enum: default, priority

system\_fingerprint

`string`

▶usage{}

`object`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.7/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.7/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-4.7/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-4.7/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-4.7/#page","headline":"Grok 4.7","description":"xAI's Grok 4.7, a frontier reasoning model for coding, agentic tasks, and knowledge work. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (low, medium, high, xhigh).","url":"https://developers.cloudflare.com/ai/models/xai/grok-4.7/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's Grok Imagine image model. Generates and edits images from text and reference-image inputs with configurable aspect ratio and resolution.
title: Grok Imagine Image
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok Imagine Image

Text-to-Image • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-imagine-image`

- Third-party
- Zero data retention

xAI's Grok Imagine image model. Generates and edits images from text and reference-image inputs with configurable aspect ratio and resolution.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://docs.x.ai/developers/models/grok-imagine-image) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.02</li><li>Per input image$0.002</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-imagine-image',
  { prompt: 'A golden retriever puppy playing in autumn leaves' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-image",
  "input": {
    "prompt": "A golden retriever puppy playing in autumn leaves"
  }
}'
```

![Simple Generation](https://examples.aig.cloudflare.com/xai/grok-imagine-image/simple-generation.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/xai/grok-imagine-image/simple-generation.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Custom Aspect Ratio** — Portrait orientation render at 2K resolution</summary>



```ts
const response = await env.AI.run(
  'xai/grok-imagine-image',
  {
    prompt:
      'A detailed botanical illustration of exotic tropical flowers with fine line work and watercolor textures',
    aspect_ratio: '3:4',
    resolution: '2k',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-image",
  "input": {
    "prompt": "A detailed botanical illustration of exotic tropical flowers with fine line work and watercolor textures",
    "aspect_ratio": "3:4",
    "resolution": "2k"
  }
}'
```

![Custom Aspect Ratio](https://examples.aig.cloudflare.com/xai/grok-imagine-image/custom-aspect-ratio.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/xai/grok-imagine-image/custom-aspect-ratio.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Cinematic Landscape** — Widescreen landscape at 2K resolution</summary>



```ts
const response = await env.AI.run(
  'xai/grok-imagine-image',
  {
    prompt:
      'A neon-lit cyberpunk figure standing in the rain beneath a holographic billboard, cinematic lighting',
    aspect_ratio: '16:9',
    resolution: '2k',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-image",
  "input": {
    "prompt": "A neon-lit cyberpunk figure standing in the rain beneath a holographic billboard, cinematic lighting",
    "aspect_ratio": "16:9",
    "resolution": "2k"
  }
}'
```

![Cinematic Landscape](https://examples.aig.cloudflare.com/xai/grok-imagine-image/cinematic-landscape.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/xai/grok-imagine-image/cinematic-landscape.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`required

n

`integer`minimum: 1maximum: 10

aspect\_ratio

`string`enum: 1:1, 3:4, 4:3, 9:16, 16:9, 2:3, 3:2, 9:19.5, 19.5:9, 9:20, 20:9, 1:2, 2:1, auto

quality

`string`enum: low, medium, high

resolution

`string`enum: 1k, 2k

response\_format

`string`enum: url, b64\_json

user

`string`

▶image{}

`object`

▶images\[]

`array`maxItems: 10

▶mask{}

`object`

image

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-imagine-image/#page","headline":"Grok Imagine Image","description":"xAI's Grok Imagine image model. Generates and edits images from text and reference-image inputs with configurable aspect ratio and resolution.","url":"https://developers.cloudflare.com/ai/models/xai/grok-imagine-image/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's Grok Imagine Image 2.0 is a precise image generation and editing model for creative work, with strong instruction following, typography, layout, and reference-image preservation.
title: Grok Imagine Image 2.0
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok Imagine Image 2.0

Text-to-Image • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-2.0/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-imagine-image-2.0`

- Third-party

xAI's Grok Imagine Image 2.0 is a precise image generation and editing model for creative work, with strong instruction following, typography, layout, and reference-image preservation.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://docs.x.ai/developers/model-capabilities/images/generation) |
| Pricing | <ul><li>Per image$0.04</li><li>Per input image$0.01</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-imagine-image-2.0',
  { prompt: 'A concert poster for a synthwave band, bold retro typography, sharp small print' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-image-2.0",
  "input": {
    "prompt": "A concert poster for a synthwave band, bold retro typography, sharp small print"
  }
}'
```

![Simple Generation](https://examples.aig.cloudflare.com/xai/grok-imagine-image-2.0/simple-generation.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/xai/grok-imagine-image-2.0/simple-generation.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Portrait 2K** — High-resolution image with a controlled aspect ratio</summary>



```ts
const response = await env.AI.run(
  'xai/grok-imagine-image-2.0',
  {
    aspect_ratio: '3:4',
    prompt:
      'A detailed botanical illustration of exotic tropical flowers with fine line work and watercolor textures',
    quality: 'medium',
    resolution: '2k',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-image-2.0",
  "input": {
    "aspect_ratio": "3:4",
    "prompt": "A detailed botanical illustration of exotic tropical flowers with fine line work and watercolor textures",
    "quality": "medium",
    "resolution": "2k"
  }
}'
```

![Portrait 2K](https://examples.aig.cloudflare.com/xai/grok-imagine-image-2.0/portrait-2k.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/xai/grok-imagine-image-2.0/portrait-2k.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Low Quality Draft** — Fast low-quality draft for iteration</summary>



```ts
const response = await env.AI.run(
  'xai/grok-imagine-image-2.0',
  {
    aspect_ratio: '1:1',
    prompt: 'A quiet Japanese garden in morning mist with a stone lantern and koi pond',
    quality: 'low',
    resolution: '1k',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-image-2.0",
  "input": {
    "aspect_ratio": "1:1",
    "prompt": "A quiet Japanese garden in morning mist with a stone lantern and koi pond",
    "quality": "low",
    "resolution": "1k"
  }
}'
```

![Low Quality Draft](https://examples.aig.cloudflare.com/xai/grok-imagine-image-2.0/low-quality-draft.jpg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/xai/grok-imagine-image-2.0/low-quality-draft.jpg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`required

aspect\_ratio

`string`enum: 1:1, 3:4, 4:3, 9:16, 16:9, 2:3, 3:2, 9:19.5, 19.5:9, 9:20, 20:9, 1:2, 2:1, auto

quality

`string`enum: low, medium

resolution

`string`enum: 1k, 2k

response\_format

`string`enum: url, b64\_json

user

`string`

▶image{}

`object`

▶images\[]

`array`maxItems: 5

▶mask{}

`object`

image

`string`Generated image. Either a base64 data URI (\`data:image/png;base64,...\`) or an \`https://\` URL, depending on the upstream \`response\_format\`.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-2.0/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-2.0/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-2.0/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-2.0/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-2.0/#page","headline":"Grok Imagine Image 2.0","description":"xAI's Grok Imagine Image 2.0 is a precise image generation and editing model for creative work, with strong instruction following, typography, layout, and reference-image preservation.","url":"https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-2.0/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's higher-fidelity text-to-image model optimized for sharper details, more accurate compositions, and stronger text rendering. Supports image editing via reference images and masks. Trades speed for quality compared to grok-imagine-image. Default output at 2k resolution.
title: Grok Imagine Image Quality
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok Imagine Image Quality

Text-to-Image • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-quality/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-imagine-image-quality`

- Third-party
- Zero data retention

xAI's higher-fidelity text-to-image model optimized for sharper details, more accurate compositions, and stronger text rendering. Supports image editing via reference images and masks. Trades speed for quality compared to grok-imagine-image. Default output at 2k resolution.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://docs.x.ai/developers/models/grok-imagine-image-quality) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per image$0.05</li><li>Per input image$0.01</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-imagine-image-quality',
  { prompt: 'A golden retriever puppy playing in autumn leaves' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-image-quality",
  "input": {
    "prompt": "A golden retriever puppy playing in autumn leaves"
  }
}'
```

![Simple Generation](https://examples.aig.cloudflare.com/xai/grok-imagine-image-quality/simple-generation.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/xai/grok-imagine-image-quality/simple-generation.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**High Quality Portrait** — High-quality portrait-orientation render at 2K resolution</summary>



```ts
const response = await env.AI.run(
  'xai/grok-imagine-image-quality',
  {
    prompt:
      'A detailed botanical illustration of exotic tropical flowers with fine line work and watercolor textures',
    aspect_ratio: '3:4',
    quality: 'high',
    resolution: '2k',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-image-quality",
  "input": {
    "prompt": "A detailed botanical illustration of exotic tropical flowers with fine line work and watercolor textures",
    "aspect_ratio": "3:4",
    "quality": "high",
    "resolution": "2k"
  }
}'
```

![High Quality Portrait](https://examples.aig.cloudflare.com/xai/grok-imagine-image-quality/high-quality-portrait.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/xai/grok-imagine-image-quality/high-quality-portrait.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Cinematic Widescreen** — Widescreen cinematic composition</summary>



```ts
const response = await env.AI.run(
  'xai/grok-imagine-image-quality',
  {
    prompt:
      'A neon-lit cyberpunk figure standing in the rain beneath a holographic billboard, cinematic lighting',
    aspect_ratio: '16:9',
    quality: 'high',
    resolution: '2k',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-image-quality",
  "input": {
    "prompt": "A neon-lit cyberpunk figure standing in the rain beneath a holographic billboard, cinematic lighting",
    "aspect_ratio": "16:9",
    "quality": "high",
    "resolution": "2k"
  }
}'
```

![Cinematic Widescreen](https://examples.aig.cloudflare.com/xai/grok-imagine-image-quality/cinematic-widescreen.png)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/xai/grok-imagine-image-quality/cinematic-widescreen.png"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Medium Quality Landscape** — Balanced quality landscape render</summary>



```ts
const response = await env.AI.run(
  'xai/grok-imagine-image-quality',
  {
    prompt:
      'A panoramic view of the northern lights over a snowy mountain range, vivid greens and purples dancing across the sky',
    aspect_ratio: '16:9',
    quality: 'medium',
    resolution: '1k',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-image-quality",
  "input": {
    "prompt": "A panoramic view of the northern lights over a snowy mountain range, vivid greens and purples dancing across the sky",
    "aspect_ratio": "16:9",
    "quality": "medium",
    "resolution": "1k"
  }
}'
```

![Medium Quality Landscape](https://examples.aig.cloudflare.com/xai/grok-imagine-image-quality/medium-quality-landscape.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/xai/grok-imagine-image-quality/medium-quality-landscape.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Square Low Quality Draft** — Fast, rough draft for iteration</summary>



```ts
const response = await env.AI.run(
  'xai/grok-imagine-image-quality',
  {
    prompt: 'A quiet Japanese garden in morning mist with a stone lantern and koi pond',
    aspect_ratio: '1:1',
    quality: 'low',
    resolution: '1k',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-image-quality",
  "input": {
    "prompt": "A quiet Japanese garden in morning mist with a stone lantern and koi pond",
    "aspect_ratio": "1:1",
    "quality": "low",
    "resolution": "1k"
  }
}'
```

![Square Low Quality Draft](https://examples.aig.cloudflare.com/xai/grok-imagine-image-quality/square-low-quality-draft.jpeg)

```json
{
  "state": "Completed",
  "result": {
    "image": "https://examples.aig.cloudflare.com/xai/grok-imagine-image-quality/square-low-quality-draft.jpeg"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

prompt

`string`required

n

`integer`minimum: 1maximum: 10

aspect\_ratio

`string`enum: 1:1, 3:4, 4:3, 9:16, 16:9, 2:3, 3:2, 9:19.5, 19.5:9, 9:20, 20:9, 1:2, 2:1, auto

quality

`string`enum: low, medium, high

resolution

`string`enum: 1k, 2k

response\_format

`string`enum: url, b64\_json

user

`string`

▶image{}

`object`

▶images\[]

`array`maxItems: 10

▶mask{}

`object`

image

`string`Generated image. Either a base64 data URI (\`data:image/png;base64,...\`) or an \`https://\` URL, depending on the upstream \`response\_format\` (defaults to base64).

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-quality/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-quality/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-quality/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-quality/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-quality/#page","headline":"Grok Imagine Image Quality","description":"xAI's higher-fidelity text-to-image model optimized for sharper details, more accurate compositions, and stronger text rendering. Supports image editing via reference images and masks. Trades speed for quality compared to grok-imagine-image. Default output at 2k resolution.","url":"https://developers.cloudflare.com/ai/models/xai/grok-imagine-image-quality/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's video generation model. Generates, edits, and extends videos from text and image inputs with native synchronized audio including dialogue, sound effects, and music. Supports multiple creative modes (normal, fun, custom).
title: Grok Imagine Video
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok Imagine Video

Text-to-Video • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-imagine-video`

- Third-party
- Zero data retention

xAI's video generation model. Generates, edits, and extends videos from text and image inputs with native synchronized audio including dialogue, sound effects, and music. Supports multiple creative modes (normal, fun, custom).

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://docs.x.ai/developers/models/grok-imagine-video) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.05</li><li>@480p (per second)$0.05</li><li>@720p (per second)$0.07</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-imagine-video',
  {
    prompt: 'A golden retriever running through a field of sunflowers on a sunny day',
    aspect_ratio: '16:9',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-video",
  "input": {
    "prompt": "A golden retriever running through a field of sunflowers on a sunny day",
    "aspect_ratio": "16:9",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/xai/grok-imagine-video/simple-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Portrait Video** — Vertical video for social media</summary>



```ts
const response = await env.AI.run(
  'xai/grok-imagine-video',
  {
    prompt: 'Slow-motion close-up of ink drops blooming through water against a black background',
    aspect_ratio: '9:16',
    duration: 5,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-video",
  "input": {
    "prompt": "Slow-motion close-up of ink drops blooming through water against a black background",
    "aspect_ratio": "9:16",
    "duration": 5,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/xai/grok-imagine-video/portrait-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Cinematic Landscape** — Widescreen cinematic shot at extended duration</summary>



```ts
const response = await env.AI.run(
  'xai/grok-imagine-video',
  {
    prompt:
      'A wide drone shot over snow-covered mountain peaks at sunrise, dramatic lighting with low clouds',
    aspect_ratio: '16:9',
    duration: 10,
    resolution: '720p',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-video",
  "input": {
    "prompt": "A wide drone shot over snow-covered mountain peaks at sunrise, dramatic lighting with low clouds",
    "aspect_ratio": "16:9",
    "duration": 10,
    "resolution": "720p"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/xai/grok-imagine-video/cinematic-landscape.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

\_operation

`string`enum: generate, edit, extend

prompt

`string`

duration

`integer`minimum: 1maximum: 15

aspect\_ratio

`string`enum: 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3

resolution

`string`enum: 480p, 720p

size

`string`enum: 848x480, 1696x960, 1280x720, 1920x1080

▶image{}

`object`

▶video{}

`object`

▶reference\_images\[]

`array`maxItems: 10

▶output{}

`object`

user

`string`

video

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-imagine-video/#page","headline":"Grok Imagine Video","description":"xAI's video generation model. Generates, edits, and extends videos from text and image inputs with native synchronized audio including dialogue, sound effects, and music. Supports multiple creative modes (normal, fun, custom).","url":"https://developers.cloudflare.com/ai/models/xai/grok-imagine-video/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's next-generation video generation model. Generates, edits, and extends videos from text and image inputs. Supports multiple aspect ratios and resolutions with improved quality over the previous generation.
title: Grok Imagine Video 1.5 Preview
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok Imagine Video 1.5 Preview

Image-to-Video • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video-1.5-preview/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-imagine-video-1.5-preview`

- Third-party
- Zero data retention

xAI's next-generation video generation model. Generates, edits, and extends videos from text and image inputs. Supports multiple aspect ratios and resolutions with improved quality over the previous generation.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://docs.x.ai/developers/models/grok-imagine-video) |
| Zero data retention | Yes |
| Pricing | <ul><li>Default (per second)$0.08</li><li>@480p (per second)$0.08</li><li>@720p (per second)$0.14</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-imagine-video-1.5-preview',
  {
    prompt: 'Generate a slow and serene time-lapse',
    image: { url: 'https://docs.x.ai/assets/api-examples/video/milkyway-still.png' },
    duration: 12,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-imagine-video-1.5-preview",
  "input": {
    "prompt": "Generate a slow and serene time-lapse",
    "image": {
      "url": "https://docs.x.ai/assets/api-examples/video/milkyway-still.png"
    },
    "duration": 12
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "video": "https://examples.aig.cloudflare.com/xai/grok-imagine-video-1.5-preview/image-to-video.mp4"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

\_operation

`string`enum: generate, edit, extend

prompt

`string`

duration

`integer`minimum: 1maximum: 15

aspect\_ratio

`string`enum: 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3

resolution

`string`enum: 480p, 720p

size

`string`enum: 848x480, 1696x960, 1280x720, 1920x1080

▶image{}

`object`

▶video{}

`object`

▶reference\_images\[]

`array`maxItems: 10

▶output{}

`object`

user

`string`

video

`string`

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video-1.5-preview/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video-1.5-preview/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video-1.5-preview/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-imagine-video-1.5-preview/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-imagine-video-1.5-preview/#page","headline":"Grok Imagine Video 1.5 Preview","description":"xAI's next-generation video generation model. Generates, edits, and extends videos from text and image inputs. Supports multiple aspect ratios and resolutions with improved quality over the previous generation.","url":"https://developers.cloudflare.com/ai/models/xai/grok-imagine-video-1.5-preview/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's Grok speech-to-text model. Transcribes audio files into text across 25 languages with word-level timestamps, multichannel transcription, speaker diarization, and key-term biasing.
title: Grok STT
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok STT

Automatic Speech Recognition • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-stt/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-stt`

- Third-party
- Zero data retention

xAI's Grok speech-to-text model. Transcribes audio files into text across 25 languages with word-level timestamps, multichannel transcription, speaker diarization, and key-term biasing.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://docs.x.ai/developers/model-capabilities/audio/speech-to-text) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per audio minute$0.001667</li><li>input audio minutes streaming$0.003334</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-stt',
  { url: 'https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-stt",
  "input": {
    "url": "https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3"
  }
}'
```

```
How old is the Brooklyn Bridge?
```

```json
{
  "state": "Completed",
  "result": {
    "text": "How old is the Brooklyn Bridge?",
    "language": "English",
    "duration": 1.85,
    "words": [
      {
        "text": "How",
        "start": 0.14,
        "end": 0.28
      },
      {
        "text": "old",
        "start": 0.4,
        "end": 0.6
      },
      {
        "text": "is",
        "start": 0.65,
        "end": 0.75
      },
      {
        "text": "the",
        "start": 0.81,
        "end": 0.89
      },
      {
        "text": "Brooklyn",
        "start": 0.95,
        "end": 1.29
      },
      {
        "text": "Bridge?",
        "start": 1.35,
        "end": 1.69
      }
    ]
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**With Language and Formatting** — Enable Inverse Text Normalization so spoken numbers become digits</summary>



```ts
const response = await env.AI.run(
  'xai/grok-stt',
  {
    url: 'https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3',
    language: 'en',
    format: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-stt",
  "input": {
    "url": "https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3",
    "language": "en",
    "format": true
  }
}'
```

```
How old is the Brooklyn Bridge?
```

```json
{
  "state": "Completed",
  "result": {
    "text": "How old is the Brooklyn Bridge?",
    "language": "English",
    "duration": 1.85,
    "words": [
      {
        "text": "How",
        "start": 0.14,
        "end": 0.28
      },
      {
        "text": "old",
        "start": 0.4,
        "end": 0.6
      },
      {
        "text": "is",
        "start": 0.65,
        "end": 0.75
      },
      {
        "text": "the",
        "start": 0.81,
        "end": 0.89
      },
      {
        "text": "Brooklyn",
        "start": 0.95,
        "end": 1.29
      },
      {
        "text": "Bridge?",
        "start": 1.35,
        "end": 1.69
      }
    ]
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Speaker Diarization with Key Terms** — Identify speakers and bias transcription toward proper nouns</summary>



```ts
const response = await env.AI.run(
  'xai/grok-stt',
  {
    url: 'https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3',
    language: 'en',
    diarize: true,
    keyterm: ['Brooklyn', 'Manhattan'],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-stt",
  "input": {
    "url": "https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3",
    "language": "en",
    "diarize": true,
    "keyterm": [
      "Brooklyn",
      "Manhattan"
    ]
  }
}'
```

```
How old is the Brooklyn Bridge?
```

```json
{
  "state": "Completed",
  "result": {
    "text": "How old is the Brooklyn Bridge?",
    "language": "English",
    "duration": 1.85,
    "words": [
      {
        "text": "How",
        "start": 0.14,
        "end": 0.28,
        "speaker": 0
      },
      {
        "text": "old",
        "start": 0.4,
        "end": 0.6,
        "speaker": 0
      },
      {
        "text": "is",
        "start": 0.65,
        "end": 0.75,
        "speaker": 0
      },
      {
        "text": "the",
        "start": 0.81,
        "end": 0.89,
        "speaker": 0
      },
      {
        "text": "Brooklyn",
        "start": 0.95,
        "end": 1.29,
        "speaker": 0
      },
      {
        "text": "Bridge?",
        "start": 1.35,
        "end": 1.69,
        "speaker": 0
      }
    ]
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Filler Words Preserved** — Keep filler words (uh, um, er) in the transcript instead of removing them</summary>



```ts
const response = await env.AI.run(
  'xai/grok-stt',
  {
    url: 'https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3',
    language: 'en',
    filler_words: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-stt",
  "input": {
    "url": "https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3",
    "language": "en",
    "filler_words": true
  }
}'
```

```
How old is the Brooklyn Bridge?
```

```json
{
  "state": "Completed",
  "result": {
    "text": "How old is the Brooklyn Bridge?",
    "language": "English",
    "duration": 1.85,
    "words": [
      {
        "text": "How",
        "start": 0.14,
        "end": 0.28
      },
      {
        "text": "old",
        "start": 0.4,
        "end": 0.6
      },
      {
        "text": "is",
        "start": 0.65,
        "end": 0.75
      },
      {
        "text": "the",
        "start": 0.81,
        "end": 0.89
      },
      {
        "text": "Brooklyn",
        "start": 0.95,
        "end": 1.29
      },
      {
        "text": "Bridge?",
        "start": 1.35,
        "end": 1.69
      }
    ]
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Data URI Upload** — Pass the audio file directly as a base64 data URI (mutually exclusive with `url`)</summary>



```ts
const response = await env.AI.run(
  'xai/grok-stt',
  { file: 'data:audio/wav;base64,<...>' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-stt",
  "input": {
    "file": "data:audio/wav;base64,<...>"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "text": "",
    "language": "",
    "duration": 1
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

file

`string`Audio file as a data URI (data:audio/...;base64,...) or an HTTPS URL the gateway fetches and uploads. Supported container formats: flac, mp3, mp4, m4a, mkv, ogg, opus, wav, aac. Raw formats (pcm, mulaw, alaw) also accepted — supply audio\_format and sample\_rate. Gateway-side size limit: 25 MB. Mutually exclusive with \`url\`.

url

`string`format: uriHTTPS URL of an audio file for xAI to fetch server-side. Mutually exclusive with \`file\` and \`websocket\`. No gateway-side size limit applies.

websocket

`boolean`Enable WebSocket streaming for speech-to-text. When true, establishes a bidirectional WebSocket connection for real-time audio transcription. Mutually exclusive with \`file\` and \`url\`.

audio\_format

`string`enum: pcm, mulaw, alawFormat hint for raw/headerless audio. Required for pcm, mulaw, alaw. Omit for container formats (mp3, wav, etc.) — xAI auto-detects them.

sample\_rate

`integer`minimum: -9007199254740991maximum: 9007199254740991Sample rate in Hz. Required when audio\_format is set.

language

`string`Language code (e.g. "en", "fr", "de"). Used with format=true to enable Inverse Text Normalization. xAI transcribes in any language regardless — supplying this enables number/currency formatting in the transcript.

format

`boolean`When true, enables Inverse Text Normalization — spoken numbers and currencies are converted to written form (e.g. "one hundred dollars" → "$100"). Requires language to be set.

diarize

`boolean`When true, enables speaker diarization. Each word in the response includes a \`speaker\` integer identifying the detected speaker.

filler\_words

`boolean`When true, filler words (uh, um, er) are included in the transcript. Defaults to false — filler words are removed.

multichannel

`boolean`When true, each audio channel is transcribed independently. Results are returned in the \`channels\` array. Requires channels ≥ 2.

channels

`integer`minimum: 2maximum: 8Number of audio channels (2–8). Required only for multichannel raw audio; auto-detected for container formats.

▶keyterm\[]

`array`maxItems: 100Key terms to bias transcription toward (e.g. product names, proper nouns). Each term up to 50 characters, max 100 terms. Sent as repeated form fields: keyterm=Term+One&keyterm=Term+Two.

text

`string`Full transcript text.

language

`string`Detected language name (e.g. "English", "French").

duration

`number`Audio duration in seconds (2 d.p.).

▶words\[]

`array`Word-level segments. Each entry has text, start, end (seconds). Includes speaker integer when diarize=true.

▶channels\[]

`array`Per-channel transcripts when multichannel=true.

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-stt/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-stt/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-stt/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-stt/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-stt/#page","headline":"Grok STT","description":"xAI's Grok speech-to-text model. Transcribes audio files into text across 25 languages with word-level timestamps, multichannel transcription, speaker diarization, and key-term biasing.","url":"https://developers.cloudflare.com/ai/models/xai/grok-stt/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's Grok text-to-speech model. Generates high-fidelity spoken audio in 5 expressive voices (eve, ara, rex, sal, leo) with 20+ supported languages. Supports inline speech tags for laughter, whispers, and pauses.
title: Grok TTS
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok TTS

Text-to-Speech • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-tts/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-tts`

- Third-party
- Zero data retention

xAI's Grok text-to-speech model. Generates high-fidelity spoken audio in 5 expressive voices (eve, ara, rex, sal, leo) with 20+ supported languages. Supports inline speech tags for laughter, whispers, and pauses.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://docs.x.ai/developers/model-capabilities/audio/text-to-speech) |
| Zero data retention | Yes |
| Pricing | <ul><li>Per character$0.000015</li></ul> |

## Usage

```ts
const response = await env.AI.run(
  'xai/grok-tts',
  { text: 'Hello! Welcome to the xAI Text to Speech API.', language: 'en' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-tts",
  "input": {
    "text": "Hello! Welcome to the xAI Text to Speech API.",
    "language": "en"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "audio": "https://examples.aig.cloudflare.com/xai/grok-tts/simple-generation.mp3"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Examples

<details>

<summary>**Different Voice** — Use the warm, conversational `ara` voice</summary>



```ts
const response = await env.AI.run(
  'xai/grok-tts',
  { text: 'Thank you for calling. How can I help you today?', voice_id: 'ara', language: 'en' },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-tts",
  "input": {
    "text": "Thank you for calling. How can I help you today?",
    "voice_id": "ara",
    "language": "en"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "audio": "https://examples.aig.cloudflare.com/xai/grok-tts/different-voice.mp3"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**High-Fidelity MP3** — 44.1 kHz / 192 kbps MP3 for production use</summary>



```ts
const response = await env.AI.run(
  'xai/grok-tts',
  {
    text: 'Crystal clear audio at maximum quality.',
    voice_id: 'rex',
    language: 'en',
    output_format: { codec: 'mp3', sample_rate: 44100, bit_rate: 192000 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-tts",
  "input": {
    "text": "Crystal clear audio at maximum quality.",
    "voice_id": "rex",
    "language": "en",
    "output_format": {
      "codec": "mp3",
      "sample_rate": 44100,
      "bit_rate": 192000
    }
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "audio": "https://examples.aig.cloudflare.com/xai/grok-tts/high-fidelity-mp3.mp3"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Telephony (mulaw)** — G.711 μ-law at 8 kHz for SIP / PSTN integration</summary>



```ts
const response = await env.AI.run(
  'xai/grok-tts',
  {
    text: 'Hello, thank you for calling. How can I help you today?',
    voice_id: 'ara',
    language: 'en',
    output_format: { codec: 'mulaw', sample_rate: 8000 },
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-tts",
  "input": {
    "text": "Hello, thank you for calling. How can I help you today?",
    "voice_id": "ara",
    "language": "en",
    "output_format": {
      "codec": "mulaw",
      "sample_rate": 8000
    }
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "audio": "https://examples.aig.cloudflare.com/xai/grok-tts/telephony-law.mp3"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Expressive Delivery** — Inline speech tags for laughter, pauses, and whispers</summary>



```ts
const response = await env.AI.run(
  'xai/grok-tts',
  {
    text: 'So I walked in and [pause] there it was. [laugh] I honestly could not believe it! <whisper>It was a secret the whole time.</whisper>',
    voice_id: 'eve',
    language: 'en',
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-tts",
  "input": {
    "text": "So I walked in and [pause] there it was. [laugh] I honestly could not believe it! <whisper>It was a secret the whole time.</whisper>",
    "voice_id": "eve",
    "language": "en"
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "audio": "https://examples.aig.cloudflare.com/xai/grok-tts/expressive-delivery.mp3"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

<details>

<summary>**Text Normalization** — Convert written numbers and abbreviations to spoken form</summary>



```ts
const response = await env.AI.run(
  'xai/grok-tts',
  {
    text: 'The total is $1,234.56 and the meeting is at 3pm on Jan 15th.',
    voice_id: 'rex',
    language: 'en',
    text_normalization: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-tts",
  "input": {
    "text": "The total is $1,234.56 and the meeting is at 3pm on Jan 15th.",
    "voice_id": "rex",
    "language": "en",
    "text_normalization": true
  }
}'
```

```json
{
  "state": "Completed",
  "result": {
    "audio": "https://examples.aig.cloudflare.com/xai/grok-tts/text-normalization.mp3"
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

</details>

## Parameters

text

`string`minLength: 1maxLength: 15000Text to convert to speech. Maximum 15,000 characters. Supports inline speech tags: \[pause], \[laugh], \<whisper>…\</whisper>, etc. Required for REST mode, mutually exclusive with websocket.

language

`string`requiredBCP-47 language code (e.g. "en", "zh", "pt-BR") or "auto" for automatic language detection. Required for both REST and WebSocket modes. Supported codes: auto, en, ar-EG, ar-SA, ar-AE, bn, zh, fr, de, hi, id, it, ja, ko, pt-BR, pt-PT, ru, es-MX, es-ES, tr, vi.

websocket

`boolean`Enable WebSocket streaming for text-to-speech. When true, establishes a bidirectional WebSocket connection. Mutually exclusive with text.

voice\_id

`string`minLength: 1Voice for synthesis. Defaults to "eve". Built-in voices: eve (energetic), ara (warm), rex (confident), sal (balanced), leo (authoritative). Custom voice IDs from /v1/tts/voices are also accepted. Case-insensitive — "Eve", "EVE", and "eve" are equivalent.

▶output\_format{}

`object`Output audio format. Defaults to MP3 at 24 kHz / 128 kbps when omitted.

▶optimize\_streaming\_latency

`one of`

text\_normalization

`boolean`When true, normalizes written-form text into spoken-form before synthesis (e.g. "Dr." → "Doctor", "100" → "one hundred"). Defaults to false.

speed

`number`minimum: 0.7maximum: 1.5Speech speed multiplier. 1.0 is normal speed. Range: 0.7 to 1.5. Defaults to 1.0. Only used in WebSocket mode.

audio

`string`Presigned R2 URL for the generated audio file. MIME type reflects the requested codec (audio/mpeg for mp3, audio/wav for wav, etc.).

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-tts/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-tts/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-tts/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-tts/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-tts/#page","headline":"Grok TTS","description":"xAI's Grok text-to-speech model. Generates high-fidelity spoken audio in 5 expressive voices (eve, ara, rex, sal, leo) with 20+ supported languages. Supports inline speech tags for laughter, whispers, and pauses.","url":"https://developers.cloudflare.com/ai/models/xai/grok-tts/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: xAI's real-time voice conversation model with low-latency audio input and output streaming.
title: Grok Voice
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt  
> Use this file to discover all available pages before exploring further.

![xAI logo](https://developers.cloudflare.com/_astro/xai.2Y8IhZGx.svg)

# Grok Voice

websocket • xAI

Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/models/xai/grok-voice/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

`xai/grok-voice`

- Third-party
- Zero data retention

xAI's real-time voice conversation model with low-latency audio input and output streaming.

| Model Info | |
| --- | --- |
| Terms and License | [link ↗](https://x.ai/legal/terms-of-service) |
| More information | [link ↗](https://docs.x.ai/developers/rest-api-reference/inference/voice) |
| Zero data retention | Yes |
| Pricing | <ul><li>total audio minutes$0.05</li><li>input text messages$0.004</li></ul> |

## Usage

```ts
// Establish WebSocket connection
const response = await fetch(
  `https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run?model=xai/grok-voice`,
  {
    method: 'GET',
    headers: {
      'Authorization': `Bearer $CLOUDFLARE_API_TOKEN`,
      'Upgrade': 'websocket'
    }
  }
)

const ws = response.webSocket
ws.accept()

// Send audio chunks
ws.send(JSON.stringify({
  type: 'input_audio_buffer.append',
  audio: audioBase64
}))

// Receive transcriptions and audio responses
ws.addEventListener('message', (event) => {
  const data = JSON.parse(event.data)
  console.log(data)
})
```

```bash
# Note: WebSocket connections require a WebSocket client
# curl does not support WebSocket upgrade
# Use wscat, websocat, or a programming language WebSocket library

wscat -c 'wss://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run?model=xai/grok-voice' \
  -H 'Authorization: Bearer $CLOUDFLARE_API_TOKEN'
```

```json
{
  "websocket": {
    "url": "wss://api.x.ai/v1/realtime?model=grok-voice-latest",
    "headers": {
      "Authorization": "Bearer [ephemeral_token]"
    }
  },
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}
```

## Parameters

websocket

`boolean`Enable real-time WebSocket connection for voice conversations. When true, establishes a bidirectional WebSocket for speech-to-speech interaction with Grok voice models.

url

`string`WebSocket URL for the realtime connection (e.g., wss://...)

▶headers{}

`object`Optional headers to include when establishing the WebSocket connection (e.g., Authorization)

## API Schemas (Raw)

Input [Open](https://developers.cloudflare.com/ai/models/xai/grok-voice/schema-input.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-voice/schema-input.json)

Output [Open](https://developers.cloudflare.com/ai/models/xai/grok-voice/schema-output.json) [Download](https://developers.cloudflare.com/ai/models/xai/grok-voice/schema-output.json)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-voice/#page","headline":"Grok Voice","description":"xAI's real-time voice conversation model with low-latency audio input and output streaming.","url":"https://developers.cloudflare.com/ai/models/xai/grok-voice/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Explore Cloudflare products that complement AI, including Workers AI, AI Gateway, Vectorize, and more.
title: Related products
image: https://developers.cloudflare.com/ai/related-products/og.png?v=e2eabf2d333ed6f6
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/ai/llms.txt  
> Use this file to discover all available pages before exploring further.

# Related products

Last updated Sep 30, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai/related-products/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

[Workers AI](https://developers.cloudflare.com/workers-ai/)

Run machine learning models on Cloudflare's GPU-powered infrastructure with serverless inference.

[AI Gateway](https://developers.cloudflare.com/ai-gateway/)

Observe and control your AI applications with caching, rate limiting, and analytics.

[Agents](https://developers.cloudflare.com/agents/)

Build AI-powered agents to perform tasks, persist state, and interact with external services.

[AI Search](https://developers.cloudflare.com/ai-search/)

Create fully managed RAG pipelines for your AI applications.

[Vectorize](https://developers.cloudflare.com/vectorize/)

Store, query, and manage high-dimensional vector databases for AI embeddings.

[AI Crawl Control](https://developers.cloudflare.com/ai-crawl-control/)

Analyze and control third-party AI crawlers on your website.

[Browser Rendering](https://developers.cloudflare.com/browser-run/)

Control and interact with headless browser instances for AI data extraction.

[Agent Lee](https://developers.cloudflare.com/agent-lee/)

An AI-powered assistant that helps you navigate, configure, and manage Cloudflare.

[Dynamic Workers](https://developers.cloudflare.com/dynamic-workers/)

Spin up isolated Workers on demand to execute code.

[Sandboxes](https://developers.cloudflare.com/sandbox/)

Run untrusted or generated code in isolated Workers or Linux virtual machines.

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/ai/related-products/#page","headline":"Related products","description":"Explore Cloudflare products that complement AI, including Workers AI, AI Gateway, Vectorize, and more.","url":"https://developers.cloudflare.com/ai/related-products/","inLanguage":"en","image":"https://developers.cloudflare.com/ai/related-products/og.png?v=e2eabf2d333ed6f6","dateModified":"2026-09-30","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Ask questions, run diagnostics, and take actions across your Cloudflare account using an AI-powered dashboard assistant.
title: Agent Lee
image: https://developers.cloudflare.com/agent-lee/og.png?v=e0b0bf7f4daf92bd
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/agent-lee/llms.txt  
> Use this file to discover all available pages before exploring further.

# Agent Lee

Last updated Sep 24, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/agent-lee/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

An AI co-pilot built into the Cloudflare dashboard. Ask questions about your account, take actions, and run diagnostics, all in plain language.

Beta

Agent Lee is currently in beta and available to accounts on a Free plan and to select Enterprise customers. Features and behaviors may change.

If you are on an Enterprise plan and would like access, contact your account team.

With Agent Lee, you can:

- Ask questions about your account configuration and get answers based on your actual data.
- Make changes to DNS records, zone settings, and security rules, with your approval required before anything executes.
- Undo a change Agent Lee made earlier in the conversation.
- Run network diagnostics like DNS lookups and certificate checks.
- Generate charts and visualizations from your account analytics.
- Find the right dashboard page for a task.
- Revisit your earlier conversations with Agent Lee.
- Open a Cloudflare Support case, if your account is eligible.

To get started, log in to the [Cloudflare dashboard ↗︎](https://dash.cloudflare.com) and select **Ask AI** in the upper-right corner of any dashboard page.

Agent Lee was previously referred to as Cloudflare Agent.

---

## Capabilities

### Account-aware answers

Agent Lee answers based on your actual account data, not just documentation. When you ask a question, it fetches your zone configuration, DNS records, and security settings before responding.

It can also tell you whether your account is entitled to a particular Cloudflare feature, and which plan tier you are on, so you know whether something is available to you before you try to configure it.

### Write operations

You can ask Agent Lee to create, update, or delete resources across your account using natural language. Every write operation requires your explicit approval before it executes, Agent Lee shows you exactly what it plans to do and waits for confirmation.

If you would rather Agent Lee never change anything, you can grant it [read-only access](https://developers.cloudflare.com/agent-lee/manage-access/), which leaves questions and diagnostics available.

Example requests:

- "Add an A record for blog.example.com pointing to 192.0.2.10."
- "Enable Always Use HTTPS on my zone."
- "Set the SSL mode for example.com to Full (strict)."

### Undo a change

If Agent Lee made a change earlier in the conversation and you want to reverse it, ask it to undo the change. Agent Lee works out the inverse operation and presents it to you as a proposed write, which you approve in the same way as any other change. Undo is not automatic, and it cannot reverse changes made outside of Agent Lee.

### Network diagnostics

Run diagnostic commands to troubleshoot connectivity and configuration issues:

- **DNS lookups**: Query DNS records for any domain
- **Certificate checks**: Inspect TLS/SSL certificates
- **Domain information**: Look up WHOIS and RDAP registration data

### Generative UI

Agent Lee builds charts, tables, and metric summaries from your account analytics. Most visualizations appear in the chat panel as a card that you select to open the full-screen view.

Example requests:

- "Show me a chart of my traffic over the last 7 days."
- "What does my error rate look like for the past 24 hours?"

### Dashboard navigation

Agent Lee searches the dashboard's page index rather than guessing at URLs, so it can point you to the exact page for a task. Links open on the account you currently have selected.

Example requests:

- "Where do I configure page rules for example.com?"
- "Take me to my R2 bucket settings."

### Conversation history

Agent Lee can list, search, and summarize your previous conversations, so you can pick up where you left off without repeating context.

Example requests:

- "What did we decide about the SSL settings last week?"
- "Summarize my last conversation."

Agent Lee treats past conversation context as supplemental. It re-reads your live account data before answering rather than relying on what was true in an earlier session.

### Support case handoff

If Agent Lee cannot resolve your issue and your account is eligible for ticket-based support, it can prepare a Cloudflare Support case for you. Agent Lee always shows you the case and waits for your confirmation before filing anything — it never opens a case silently.

Eligibility depends on your support entitlement rather than your plan name alone. Accounts on a Free plan can file billing disputes, such as a duplicate charge or a charge after cancelling. Agent Lee limits how many cases you can open per account within a 24-hour period.

### Product knowledge

Agent Lee has built-in guidance for individual Cloudflare products — including DNS, SSL/TLS, R2, Workers, Cloudflare Tunnel, Gateway, Access, and WARP — and searches the Cloudflare developer documentation and changelog when it needs more detail. Grounding answers in the published changelog means Agent Lee will tell you when a product you asked about does not exist, rather than inventing one.

---

## Data access and privacy

### What Agent Lee can access

- Zone settings, DNS records, firewall and WAF rules
- Workers scripts, routes, and bindings
- R2 bucket names, Cloudflare Tunnel configuration, cache rules
- Registrar domain data, account plan and usage metadata

Agent Lee fetches this data on demand when your question requires it.

### What Agent Lee cannot access

- Payment methods, billing history, or invoice details
- Account passwords, login credentials, or API tokens
- Raw log data or Logpush datasets
- Data from other Cloudflare accounts

### Conversation storage

Conversations are stored per user using [Durable Objects](https://developers.cloudflare.com/durable-objects/). Conversation data is retained for one year in accordance with Cloudflare's data retention policy, measured from the last time you sent a message, so an actively used conversation is not purged while you are still working in it.

Agent Lee can list, search, and summarize conversations you have had with it. It cannot read another user's conversations.

### Data usage

Agent Lee does not currently use your conversations, prompts, or account data to train AI models, nor do we share your data with other Cloudflare customers. Should these practices change in the future, we will provide advance notice to keep you informed. For Cloudflare's authoritative data handling commitments, refer to the [Cloudflare Privacy Policy ↗︎](https://www.cloudflare.com/privacypolicy/).

---

## Limitations

Agent Lee cannot:

- Deploy applications on your behalf or run code for you (it can generate small starter projects and [export the source](https://developers.cloudflare.com/agent-lee/take-home-code/) for you to clone)
- Replace [Cloudflare Support ↗︎](https://support.cloudflare.com) for account recovery or outages (it can prepare a support case for you, but only if your account is eligible and you confirm it)
- Access payment methods, billing history, or API tokens
- Operate across multiple accounts: sessions are scoped to your authenticated account
- Query raw log data or Logpush datasets
- Execute write operations without your explicit approval

Agent Lee is entirely optional. If you do not open the Ask AI panel, none of your data is sent to or processed by it.

---

## Built on Cloudflare

Agent Lee is built on Cloudflare's own developer platform using the same primitives available to any Cloudflare developer.

| Component | Role |
| --- | --- |
| [Agents SDK](https://developers.cloudflare.com/agents/) | Agent lifecycle, state management, and scheduling |
| [Durable Objects](https://developers.cloudflare.com/durable-objects/) | Per-user conversation storage and write approval gate |
| [Workers AI](https://developers.cloudflare.com/workers-ai/) | LLM inference |
| [AI Gateway](https://developers.cloudflare.com/ai-gateway/) | Model request routing, logging, and analytics |
| [Cloudflare MCP server](https://developers.cloudflare.com/agents/model-context-protocol/apis/agent-api/) | Tool definitions for Cloudflare API operations |

---

## Related resources

- [Export generated code](https://developers.cloudflare.com/agent-lee/take-home-code/)
- [Manage access and permissions](https://developers.cloudflare.com/agent-lee/manage-access/)
- [Agents SDK](https://developers.cloudflare.com/agents/)
- [Human in the Loop](https://developers.cloudflare.com/agents/concepts/agentic-patterns/human-in-the-loop/)
- [Workers AI](https://developers.cloudflare.com/workers-ai/)
- [Blog post: Introducing Agent Lee ↗︎](https://blog.cloudflare.com/introducing-agent-lee)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/agent-lee/#page","headline":"Agent Lee","description":"Ask questions, run diagnostics, and take actions across your Cloudflare account using an AI-powered dashboard assistant.","url":"https://developers.cloudflare.com/agent-lee/","inLanguage":"en","image":"https://developers.cloudflare.com/agent-lee/og.png?v=e0b0bf7f4daf92bd","dateModified":"2026-09-24","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["AI"]}
```

---

---
description: Create stateful AI agents with persistent memory, real-time WebSocket connections, and scheduled tasks using the Cloudflare Agents SDK.
title: Build Agents on Cloudflare
image: https://developers.cloudflare.com/agents/og.png?v=5f3790c1b824e669
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/agents/llms.txt  
> Use this file to discover all available pages before exploring further.

# Build Agents on Cloudflare

Last updated Sep 18, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/agents/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

Build and host Agents on Cloudflare, connect chat, voice, email, Slack, and webhooks to a durable agent runtime with Browser, Sandbox, AI Search, MCP, Payments, and other MCP tools.

When you host agents on Cloudflare, each agent session has a durable identity, local SQL storage, real-time connections, scheduled work, and recoverable execution.

Deploy once and Cloudflare runs your agents across its global network, scaling to tens of millions of instances. No infrastructure to manage, no sessions to reconstruct, no state to externalize.

[Chat](https://developers.cloudflare.com/agents/communication-channels/chat/) [Email](https://developers.cloudflare.com/agents/communication-channels/email/) [Voice](https://developers.cloudflare.com/agents/communication-channels/voice/) [Slack](https://developers.cloudflare.com/agents/communication-channels/slack/) [Webhook](https://developers.cloudflare.com/agents/communication-channels/webhooks/)

Agent harness

Controls planning, tool use, and response flow.

[Project Think](https://developers.cloudflare.com/agents/harnesses/think/) [Build-your-own agent](https://developers.cloudflare.com/agents/runtime/agents-api/)

Agents SDK runtime

Durable identity, state, connections, scheduling, and recovery.

[Agent class](https://developers.cloudflare.com/agents/runtime/agents-api/)

[State](https://developers.cloudflare.com/agents/runtime/lifecycle/state/) [Sessions](https://developers.cloudflare.com/agents/runtime/lifecycle/sessions/) [Routing](https://developers.cloudflare.com/agents/runtime/communication/routing/) [WebSockets](https://developers.cloudflare.com/agents/runtime/communication/websockets/) [Scheduling](https://developers.cloudflare.com/agents/runtime/execution/schedule-tasks/) [Fibers](https://developers.cloudflare.com/agents/runtime/execution/durable-execution/)

[Sandbox](https://developers.cloudflare.com/agents/tools/sandbox/) [MCP](https://developers.cloudflare.com/agents/tools/mcp/) [Browser](https://developers.cloudflare.com/agents/tools/browser/) [AI Search](https://developers.cloudflare.com/agents/tools/ai-search/) [Payments](https://developers.cloudflare.com/agents/tools/payments/)

[ObservabilityLogs · metrics · traces](https://developers.cloudflare.com/agents/runtime/operations/observability/)

Agents on Cloudflare are composed from four parts:

- **Communication channels** define how users and systems reach your agent, such as [chat](https://developers.cloudflare.com/agents/communication-channels/chat/), [voice](https://developers.cloudflare.com/agents/communication-channels/voice/), [email](https://developers.cloudflare.com/agents/communication-channels/email/), [Slack](https://developers.cloudflare.com/agents/communication-channels/slack/), [webhooks](https://developers.cloudflare.com/agents/communication-channels/webhooks/), and other event sources.
- **The agent harness** defines the loop: how the agent calls models, selects tools, handles tool results, streams responses, and decides whether to continue. Use [Project Think](https://developers.cloudflare.com/agents/harnesses/think/) for an opinionated harness, or build your own loop directly on the [Agents SDK runtime](https://developers.cloudflare.com/agents/runtime/agents-api/).
- **The Agents SDK runtime** provides durable infrastructure: the [`Agent` class](https://developers.cloudflare.com/agents/runtime/lifecycle/agent-class/), [state](https://developers.cloudflare.com/agents/runtime/lifecycle/state/), [sessions](https://developers.cloudflare.com/agents/runtime/lifecycle/sessions/), [routing](https://developers.cloudflare.com/agents/runtime/communication/routing/), [WebSockets](https://developers.cloudflare.com/agents/runtime/communication/websockets/), [scheduling](https://developers.cloudflare.com/agents/runtime/execution/schedule-tasks/), [fibers](https://developers.cloudflare.com/agents/runtime/execution/durable-execution/), and [observability](https://developers.cloudflare.com/agents/runtime/operations/observability/).
- **Tools** give the agent capabilities: [browser automation](https://developers.cloudflare.com/agents/tools/browser/), [sandboxed code execution](https://developers.cloudflare.com/agents/tools/sandbox/), [AI Search](https://developers.cloudflare.com/agents/tools/ai-search/), [MCP tools](https://developers.cloudflare.com/agents/tools/mcp/), and [payments](https://developers.cloudflare.com/agents/tools/payments/). [Code Mode](https://developers.cloudflare.com/agents/tools/codemode/) lets models discover and orchestrate multiple tools by writing code.

### Get started

Three commands to a running agent. No API keys required — the starter uses [Workers AI](https://developers.cloudflare.com/workers-ai/) by default.

```sh
npx create-cloudflare@latest --template cloudflare/agents-starter
cd agents-starter && npm install
npm run dev
```

The starter includes streaming AI chat, server-side and client-side tools, human-in-the-loop approval, and task scheduling — a foundation you can build on or tear apart. You can also swap in [OpenAI, Anthropic, Google Gemini, or any other provider](https://developers.cloudflare.com/agents/runtime/operations/using-ai-models/).

### Example agents

[Chat agent](https://developers.cloudflare.com/agents/examples/chat-agent/)

Build a streaming AI chat agent with tools and human-in-the-loop approvals.

[Slack agent](https://developers.cloudflare.com/agents/examples/slack-agent/)

Build an agent that responds to Slack messages, mentions, and commands.

[Voice agent](https://developers.cloudflare.com/agents/examples/voice-agent/)

Build a real-time voice agent with speech-to-text and text-to-speech.

[Browser agent](https://developers.cloudflare.com/agents/examples/browser-agent/)

Build an agent that can inspect pages, capture screenshots, and use browser tools.

[Email agent](https://developers.cloudflare.com/agents/examples/email-agent/)

Build an agent that sends, receives, routes, and replies to email.

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/agents/#page","headline":"Build Agents on Cloudflare","description":"Create stateful AI agents with persistent memory, real-time WebSocket connections, and scheduled tasks using the Cloudflare Agents SDK.","url":"https://developers.cloudflare.com/agents/","inLanguage":"en","image":"https://developers.cloudflare.com/agents/og.png?v=5f3790c1b824e669","dateModified":"2026-09-18","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["AI"]}
```

---

---
description: Monitor and control how AI services access your website content.
title: AI Crawl Control
image: https://developers.cloudflare.com/ai-crawl-control/og.png?v=9f8a355b477ca97e
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/ai-crawl-control/llms.txt  
> Use this file to discover all available pages before exploring further.

# AI Crawl Control

Last updated Aug 14, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai-crawl-control/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

Available on all plans

Monitor and control how AI services access your website content.

AI companies use web content to train their models and power AI applications. AI Crawl Control (formerly AI Audit) gives you visibility into which AI services are accessing your content, and provides tools to manage access according to your preferences.

With AI Crawl Control, you can:

- **See which AI services access your content** - Monitor the dashboard to see crawler activity and request patterns
- **Control access with granular policies** - Set allow or block rules for individual crawlers
- **Monitor robots.txt compliance** - Track which crawlers follow your directives and create enforcement rules
- **Explore monetization options** - Set up pay per crawl pricing for content access [(private beta)](https://developers.cloudflare.com/ai-crawl-control/features/pay-per-crawl/what-is-pay-per-crawl/)
- **Deploy with zero configuration** - Works automatically on all Cloudflare plans

[Get started](https://developers.cloudflare.com/ai-crawl-control/get-started/)

---

## Features

[Manage AI crawlers](https://developers.cloudflare.com/ai-crawl-control/features/manage-ai-crawlers/)

Control how AI crawlers interact with your domain.

Manage AI crawlers

[Analyze AI traffic](https://developers.cloudflare.com/ai-crawl-control/features/analyze-ai-traffic/)

Gain insight into how AI crawlers are interacting with your pages.

Analyze AI traffic

[Track robots.txt](https://developers.cloudflare.com/ai-crawl-control/features/track-robots-txt/)

Track the health of `robots.txt` files and identify which crawlers are violating your directives.

Track robots.txt

[Pay Per Crawl](https://developers.cloudflare.com/ai-crawl-control/features/pay-per-crawl/what-is-pay-per-crawl/)

Allow AI crawlers to access content by paying per crawl.

Pay per crawl

---

## Use cases

### Publishers and content creators

Publishers and content creators can monitor which AI crawlers are accessing their articles and educational content. Set policies to allow beneficial crawlers while blocking others.

### E-commerce and business sites

E-commerce and business sites can identify AI crawler activity on product pages and business information. Control access to sensitive data like pricing and inventory.

### Documentation sites

Documentation sites can track how AI crawlers are accessing their technical documentation. Gain insight into how AI crawlers are engaging with your site.

---

## Related Products

[Bots](https://developers.cloudflare.com/bots/)

Identify and mitigate automated traffic to protect your domain from bad bots.

[Web Application Firewall](https://developers.cloudflare.com/waf/)

Get automatic protection from vulnerabilities and the flexibility to create custom rules.

[Analytics](https://developers.cloudflare.com/analytics/)

View and analyze traffic on your domain.

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/ai-crawl-control/#page","headline":"AI Crawl Control","description":"Monitor and control how AI services access your website content.","url":"https://developers.cloudflare.com/ai-crawl-control/","inLanguage":"en","image":"https://developers.cloudflare.com/ai-crawl-control/og.png?v=9f8a355b477ca97e","dateModified":"2026-08-14","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["AI"]}
```

---

---
description: Observe and control your AI applications with analytics, caching, rate limiting, and model fallback through AI Gateway.
title: Cloudflare AI Gateway
image: https://developers.cloudflare.com/ai-gateway/og.png?v=d9b4c0d9dbab4986
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/ai-gateway/llms.txt  
> Use this file to discover all available pages before exploring further.

# Cloudflare AI Gateway

Last updated Apr 20, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai-gateway/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

Observe and control your AI applications.

Available on all plans

Cloudflare's AI Gateway allows you to gain visibility and control over your AI apps. By connecting your apps to AI Gateway, you can gather insights on how people are using your application with analytics and logging and then control how your application scales with features such as caching, rate limiting, as well as request retries, model fallback, and more. Better yet - it only takes one line of code to get started.

Check out the [Get started guide](https://developers.cloudflare.com/ai-gateway/get-started/) to learn how to configure your applications with AI Gateway.

## Features

[Models](https://developers.cloudflare.com/ai/models/)

Explore all AI models available through AI Gateway, including OpenAI, Anthropic, Google, and more.

Browse models

[Analytics](https://developers.cloudflare.com/ai-gateway/observability/analytics/)

View metrics such as the number of requests, tokens, and the cost it takes to run your application.

View Analytics

[Logging](https://developers.cloudflare.com/ai-gateway/observability/logging/)

Gain insight on requests and errors.

View Logging

[Caching](https://developers.cloudflare.com/ai-gateway/features/caching/)

Serve requests directly from Cloudflare's cache instead of the original model provider for faster requests and cost savings.

Use Caching

[Rate limiting](https://developers.cloudflare.com/ai-gateway/features/rate-limiting/)

Control how your application scales by limiting the number of requests your application receives.

Use Rate limiting

[Request retry and fallback](https://developers.cloudflare.com/ai-gateway/features/dynamic-routing/)

Improve resilience by defining request retry and model fallbacks in case of an error.

Use Request retry and fallback

[Your favorite providers](https://developers.cloudflare.com/ai-gateway/usage/providers/)

Workers AI, Anthropic, Google Gemini, OpenAI, Replicate, and more work with AI Gateway.

Use Your favorite providers

---

## Related products

[Workers AI](https://developers.cloudflare.com/workers-ai/)

Run machine learning models, powered by serverless GPUs, on Cloudflare’s global network.

[Vectorize](https://developers.cloudflare.com/vectorize/)

Build full-stack AI applications with Vectorize, Cloudflare's vector database. Adding Vectorize enables you to perform tasks such as semantic search, recommendations, anomaly detection or can be used to provide context and memory to an LLM.

## More resources

### [Developer Discord](https://discord.cloudflare.com)

Connect with the Workers community on Discord to ask questions, show what you are building, and discuss the platform with other developers.

### [Use cases](https://developers.cloudflare.com/use-cases/ai/)

Learn how you can build and deploy ambitious AI applications to Cloudflare's global network.

### [@CloudflareDev](https://x.com/cloudflaredev)

Follow @CloudflareDev on Twitter to learn about product announcements, and what is new in Cloudflare Workers.

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/ai-gateway/#page","headline":"Cloudflare AI Gateway","description":"Observe and control your AI applications with analytics, caching, rate limiting, and model fallback through AI Gateway.","url":"https://developers.cloudflare.com/ai-gateway/","inLanguage":"en","image":"https://developers.cloudflare.com/ai-gateway/og.png?v=d9b4c0d9dbab4986","dateModified":"2026-04-20","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["AI"]}
```

---

---
description: Cloudflare AI Search is a managed search service. Index your content and query it with natural language from a Workers binding, REST API, or MCP server.
title: Overview
image: https://developers.cloudflare.com/ai-search/og.png?v=174c444ef16de8d7
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/ai-search/llms.txt  
> Use this file to discover all available pages before exploring further.

# Overview

Last updated Oct 1, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/ai-search/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

The search primitive for your applications and agents.

Available on all plans

AI Search lets you add search to any application or agent without having to build an entire retrieval infrastructure. Create an instance, give it your data, and search it with natural language.

[Upload or connect](https://developers.cloudflare.com/ai-search/configuration/data-source/)

AI Search

[Storage](https://developers.cloudflare.com/ai-search/configuration/data-source/built-in-storage/) [AI models](https://developers.cloudflare.com/ai-search/configuration/models/) [Index](https://developers.cloudflare.com/ai-search/configuration/indexing/)

[Search](https://developers.cloudflare.com/ai-search/concepts/search-modes/)

You can use AI Search for:

- Documentation and knowledge base search
- AI agents that perform research over your internal knowledge
- Let each tenant or agent upload and search their own files

[Get started](https://developers.cloudflare.com/ai-search/get-started/) [Watch AI Search demo](https://www.youtube.com/watch?v=JUFdbkiDN2U)

---

## Features

[Automated indexing](https://developers.cloudflare.com/ai-search/configuration/indexing/syncing/)

Automatically and continuously index your data source, keeping your content fresh without manual reprocessing.

View indexing

[Metadata filtering](https://developers.cloudflare.com/ai-search/configuration/retrieval/filtering/)

Define custom metadata fields and filter search results by category, version, language, or any attribute you define.

Add filters

[Hybrid search](https://developers.cloudflare.com/ai-search/configuration/indexing/hybrid-search/)

Combine semantic and keyword matching in the same query. Hybrid search is on by default.

Configure hybrid search

[Image search](https://developers.cloudflare.com/ai-search/configuration/models/supported-models/)

Use a multimodal embedding model to search with images and find relevant image content.

View embedding models

[Optical character recognition](https://developers.cloudflare.com/ai-search/configuration/data-source/#images-and-optical-character-recognition)

Use optical character recognition (OCR) to extract searchable text from scanned PDFs and images.

Configure indexing

[MCP and UI snippets](https://developers.cloudflare.com/ai-search/api/search/mcp/)

Every instance includes a built-in MCP endpoint for AI agents and embeddable search components for your website.

Connect agents

---

## Related products

[Workers AI](https://developers.cloudflare.com/workers-ai/)

Run machine learning models, powered by serverless GPUs, on Cloudflare's global network.

[AI Gateway](https://developers.cloudflare.com/ai-gateway/)

Observe and control your AI applications with caching, rate limiting, request retries, model fallback, and more.

[Vectorize](https://developers.cloudflare.com/vectorize/)

Build full-stack AI applications with Vectorize, Cloudflare's vector database.

[Workers](https://developers.cloudflare.com/workers/)

Build serverless applications and deploy instantly across the globe for exceptional performance, reliability, and scale.

[R2](https://developers.cloudflare.com/r2/)

Store large amounts of unstructured data without the costly egress bandwidth fees associated with typical cloud storage services.

---

## More resources

### [Get started](https://developers.cloudflare.com/ai-search/get-started/)

Create your first AI Search instance and run your first query.

### [Developer Discord](https://discord.cloudflare.com)

Connect with the Workers community on Discord to ask questions, share what you are building, and discuss the platform with other developers.

### [@CloudflareDev](https://x.com/cloudflaredev)

Follow @CloudflareDev on Twitter to learn about product announcements, and what is new in Cloudflare Workers.

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/ai-search/#page","headline":"Overview","description":"Cloudflare AI Search is a managed search service. Index your content and query it with natural language from a Workers binding, REST API, or MCP server.","url":"https://developers.cloudflare.com/ai-search/","inLanguage":"en","image":"https://developers.cloudflare.com/ai-search/og.png?v=174c444ef16de8d7","dateModified":"2026-10-01","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["AI"]}
```

---

---
description: Control headless browsers with Cloudflare's Workers Browser Run API. Automate tasks, take screenshots, convert pages to PDFs, and test web apps.
title: Browser Run
image: https://developers.cloudflare.com/browser-run/og.png?v=3bbb9fb2640f1748
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/browser-run/llms.txt  
> Use this file to discover all available pages before exploring further.

# Browser Run

Last updated Aug 11, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/browser-run/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

Run headless Chrome on [Cloudflare's global network](https://developers.cloudflare.com/workers/) for browser automation, web scraping, testing, and content generation.

Available on Free and Paid plans

Browser Run, formerly known as Browser Rendering, enables developers to programmatically control and interact with headless browser instances running on Cloudflare’s global network.

## Use cases

Programmatically load and fully render dynamic webpages or raw HTML and capture specific outputs such as:

- [Markdown](https://developers.cloudflare.com/browser-run/quick-actions/markdown-endpoint/)
- [Screenshots](https://developers.cloudflare.com/browser-run/quick-actions/screenshot-endpoint/)
- [PDFs](https://developers.cloudflare.com/browser-run/quick-actions/pdf-endpoint/)
- [Snapshots](https://developers.cloudflare.com/browser-run/quick-actions/snapshot/)
- [Links](https://developers.cloudflare.com/browser-run/quick-actions/links-endpoint/)
- [HTML elements](https://developers.cloudflare.com/browser-run/quick-actions/scrape-endpoint/)
- [Structured data](https://developers.cloudflare.com/browser-run/quick-actions/json-endpoint/)
- [Crawled web content](https://developers.cloudflare.com/browser-run/quick-actions/crawl-endpoint/)

## Integration methods

Browser Run offers two categories of integration methods:

- **[Quick Actions](https://developers.cloudflare.com/browser-run/quick-actions/)**: Simple, stateless browser tasks like screenshots, PDFs, and scraping. No code deployment needed.
- **Browser Sessions**: Direct browser control via [Puppeteer](https://developers.cloudflare.com/browser-run/puppeteer/), [Playwright](https://developers.cloudflare.com/browser-run/playwright/), [CDP](https://developers.cloudflare.com/browser-run/cdp/), or [Stagehand](https://developers.cloudflare.com/browser-run/stagehand/). Deploy within Cloudflare Workers or connect from any environment via CDP.

| Use case | Recommended | Why |
| --- | --- | --- |
| Simple screenshot, PDF, or scrape | [Quick Actions](https://developers.cloudflare.com/browser-run/quick-actions/) | No code deployment; single HTTP request |
| Browser automation | [Playwright](https://developers.cloudflare.com/browser-run/playwright/), [Puppeteer](https://developers.cloudflare.com/browser-run/puppeteer/), or [CDP](https://developers.cloudflare.com/browser-run/cdp/) | Full browser control with scripting |
| Porting existing scripts | [Puppeteer](https://developers.cloudflare.com/browser-run/puppeteer/), [Playwright](https://developers.cloudflare.com/browser-run/playwright/), or [CDP](https://developers.cloudflare.com/browser-run/cdp/) | Minimal code changes from standard libraries |
| AI-powered data extraction | [JSON endpoint](https://developers.cloudflare.com/browser-run/quick-actions/json-endpoint/) | Structured data via natural language prompts |
| Site-wide crawling | [Crawl endpoint](https://developers.cloudflare.com/browser-run/quick-actions/crawl-endpoint/) | Multi-page content extraction with async results |
| AI agent browsing | [Playwright MCP](https://developers.cloudflare.com/browser-run/playwright/playwright-mcp/) or [CDP with MCP clients](https://developers.cloudflare.com/browser-run/cdp/mcp-clients/) | LLMs control browsers via MCP |
| Resilient scraping | [Stagehand](https://developers.cloudflare.com/browser-run/stagehand/) | AI finds elements by intent, not selectors |
| Direct browser control from any environment | [CDP](https://developers.cloudflare.com/browser-run/cdp/) | WebSocket access from local machines, CI/CD, or external servers |

## Key features

- **Scale to thousands of browsers**: Instant access to a global pool of browsers with low cold-start time, ideal for high-volume screenshot generation, data extraction, or automation at scale
- **Global by default**: Browser sessions run on Cloudflare's edge network, opening close to your users for better speed and availability worldwide
- **Easy to integrate**: [Quick Actions](https://developers.cloudflare.com/browser-run/quick-actions/) for common tasks, [Puppeteer](https://developers.cloudflare.com/browser-run/puppeteer/) and [Playwright](https://developers.cloudflare.com/browser-run/playwright/) for complex workflows, and [CDP](https://developers.cloudflare.com/browser-run/cdp/) for direct browser control from any environment
- **Session management**: [Reuse browser sessions](https://developers.cloudflare.com/browser-run/features/reuse-sessions/) across requests to improve performance and reduce cold-start overhead
- **Flexible pricing**: Pay only for browser time used with generous free tier ([view pricing](https://developers.cloudflare.com/browser-run/pricing/))

## Related products

[Workers](https://developers.cloudflare.com/workers/)

Build serverless applications and deploy instantly across the globe for exceptional performance, reliability, and scale.

[Durable Objects](https://developers.cloudflare.com/durable-objects/)

A globally distributed coordination API with strongly consistent storage. Using Durable Objects to [persist browser sessions](https://developers.cloudflare.com/browser-run/how-to/browser-run-with-do/) improves performance by eliminating the time that it takes to spin up a new browser session.

[Agents](https://developers.cloudflare.com/agents/)

Build AI-powered agents that autonomously navigate websites and perform tasks using [Playwright MCP](https://developers.cloudflare.com/browser-run/playwright/playwright-mcp/) or [Stagehand](https://developers.cloudflare.com/browser-run/stagehand/).

## More resources

### [Get started](https://developers.cloudflare.com/browser-run/get-started/)

Choose an integration method and deploy your first project.

### [Limits](https://developers.cloudflare.com/browser-run/limits/)

Learn about Browser Run limits.

### [Pricing](https://developers.cloudflare.com/browser-run/pricing/)

Learn about Browser Run pricing.

### [Playwright API](https://developers.cloudflare.com/browser-run/playwright/)

Use Cloudflare's fork of Playwright for testing and automation.

### [Developer Discord](https://discord.cloudflare.com)

Connect with the Workers community on Discord to ask questions, show what you are building, and discuss the platform with other developers.

### [@CloudflareDev](https://x.com/cloudflaredev)

Follow @CloudflareDev on Twitter to learn about product announcements, and what is new in Cloudflare Workers.

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/browser-run/#page","headline":"Browser Run","description":"Control headless browsers with Cloudflare's Workers Browser Run API. Automate tasks, take screenshots, convert pages to PDFs, and test web apps.","url":"https://developers.cloudflare.com/browser-run/","inLanguage":"en","image":"https://developers.cloudflare.com/browser-run/og.png?v=3bbb9fb2640f1748","dateModified":"2026-08-11","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Spin up isolated Workers on demand to execute code.
title: Dynamic Workers
image: https://developers.cloudflare.com/dynamic-workers/og.png?v=51a25a49ca35a178
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/dynamic-workers/llms.txt  
> Use this file to discover all available pages before exploring further.

# Dynamic Workers

Last updated Apr 21, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/dynamic-workers/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

Spin up Workers at runtime to execute code on-demand in a secure, sandboxed environment.

Dynamic Workers let you spin up an unlimited number of Workers to execute arbitrary code specified at runtime. Dynamic Workers can be used as a lightweight alternative to containers for securely sandboxing code you don't trust.

Dynamic Workers are the lowest-level primitive for spinning up a Worker, giving you full control over defining how the Worker is composed, which bindings it receives, whether it can reach the network, and more.

### Get started

Deploy the [Dynamic Workers Playground ↗︎](https://github.com/cloudflare/agents/tree/main/examples/dynamic-workers-playground) to create and run Workers dynamically from code you write or import from GitHub, with real-time logs and observability.

[![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/dinasaur404/dynamic-workers-playground)

## Use Dynamic Workers for

Use this pattern when code needs to run quickly in a secure, isolated environment.

- **AI Agent "Code Mode"**: LLMs are trained to write code. Instead of supplying an agent with tool calls to perform tasks, give it an API and let it write and execute code. Save up to 80% in inference tokens and cost by allowing the agent to programmatically process data instead of sending it all through the LLM.
- **AI-generated applications / "Vibe Code"**: Run generated code for prototypes, projects, and automations in a secure, isolated sandboxed environment.
- **Fast development and previews**: Load prototypes, previews, and playgrounds in milliseconds.
- **Custom automations**: Create custom tools on the fly that execute a task, call an integration, or automate a workflow.
- **Platforms**: Run applications uploaded by your users.

## Features

Because you compose the Worker that runs the code at runtime, you control how that Worker is configured and what it can access.

- **[Bindings](https://developers.cloudflare.com/dynamic-workers/usage/bindings/)**: Decide which bindings and structured data the dynamic Worker receives.
- **[Observability](https://developers.cloudflare.com/dynamic-workers/usage/observability/)**: Attach Tail Workers and capture logs for each run.
- **[Network access](https://developers.cloudflare.com/dynamic-workers/usage/egress-control/)**: Intercept or block Internet access for outbound requests.
- **[Limits](https://developers.cloudflare.com/dynamic-workers/usage/limits/)**: Enforce custom limits on the dynamic Worker's resource usage.
- **[Durable Object Facets](https://developers.cloudflare.com/dynamic-workers/usage/durable-object-facets/)**: Run dynamically-loaded code as a Durable Object with its own isolated SQLite storage.

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/dynamic-workers/#page","headline":"Dynamic Workers","description":"Spin up isolated Workers on demand to execute code.","url":"https://developers.cloudflare.com/dynamic-workers/","inLanguage":"en","image":"https://developers.cloudflare.com/dynamic-workers/og.png?v=51a25a49ca35a178","dateModified":"2026-04-21","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Execute untrusted or generated code in Linux virtual machines or isolated Workers.
title: Sandboxes on Cloudflare
image: https://developers.cloudflare.com/sandbox/og.png?v=a45996aa42e663ad
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/sandbox/llms.txt  
> Use this file to discover all available pages before exploring further.

# Sandboxes on Cloudflare

Last updated Sep 30, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/sandbox/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

Start a sandbox and run untrusted or generated code

Available on Workers Paid plan

A sandbox is an isolated place to run code. The code cannot directly read the memory or data of your application. Your Worker decides which application APIs and data the code receives, and whether the code can reach the public Internet.

You can use a sandbox for agent-written code, user-uploaded applications, data analysis, development previews, build pipelines, or any other work that should not share a process with your application.

Cloudflare provides two sandbox environments. Both are accessible through a [Worker](https://developers.cloudflare.com/workers/), the application that already handles your traffic.

If your application uses `@cloudflare/sandbox` 0.x, refer to [Sandbox SDK 0.x](https://developers.cloudflare.com/sandbox/sdk/), or move it to the current version with [Migrate from Sandbox SDK 0.x](https://developers.cloudflare.com/sandbox/sdk/migrate/).

---

## Containers

[Containers](https://developers.cloudflare.com/containers/) run an image you provide. The instance is a full Linux environment, so you can run any language and keep processes running. Your Worker starts the instance and sends it work. HTTP from the Internet reaches the instance only through your Worker.

Each instance is a microVM with its own kernel and network, so no other workload shares it.

A sandbox container uses the [Durable Object scheduling policy](https://developers.cloudflare.com/containers/configuration/scheduling-policy/#use-the-durable-object-scheduling-policy), which is in public beta.

A Durable Object in your Worker starts the instance from an image and runs a command in it:

```ts
container.start({
	image: "cloudflare/debian-trixie",
	entrypoint: ["sleep", "infinity"],
	enableInternet: false,
});
const process = await container.exec(["uname", "-a"]);
const output = await process.output();
```

[Run a Linux command](https://developers.cloudflare.com/sandbox/get-started/) [Build a coding agent runner](https://developers.cloudflare.com/sandbox/get-started/build-a-coding-agent-runner/)

---

## Dynamic Workers

[Dynamic Workers](https://developers.cloudflare.com/dynamic-workers/) create a new Worker at runtime. The untrusted code can be JavaScript, Python, or WebAssembly. Compile TypeScript to JavaScript before loading it.

The Workers runtime runs each Dynamic Worker apart from your Worker and from other Dynamic Workers. A Dynamic Worker reaches your application only through the methods and data you pass to it.

Your Worker loads the untrusted module as a new Worker, blocks its outbound requests, and calls it:

```ts
const sandbox = env.LOADER.load({
	compatibilityDate: "$today",
	mainModule: "code.js",
	modules: { "code.js": untrustedModule },
	globalOutbound: null,
});
const entrypoint = sandbox.getEntrypoint<CodeEntrypoint>("Code");
const result = await entrypoint.evaluate();
```

[Run JavaScript](https://developers.cloudflare.com/sandbox/get-started/dynamic-workers/) [Build an AI code interpreter](https://developers.cloudflare.com/sandbox/get-started/build-an-ai-code-interpreter/)

---

## Concepts

### [Choose a sandbox environment](https://developers.cloudflare.com/sandbox/concepts/)

Decide whether a job needs Linux or only calls methods that your Worker provides.

### [Sandbox lifetime](https://developers.cloudflare.com/sandbox/concepts/lifetime/)

Understand what keeps a Linux sandbox running, what stops it, and which files a snapshot brings back.

### [Sandbox security](https://developers.cloudflare.com/sandbox/concepts/security/)

Decide what each sandbox holds, because its code can use everything you place inside it.

## Guides

### [Run commands](https://developers.cloudflare.com/sandbox/commands/)

Run Python code and tests, stream output, keep processes running, and open a terminal.

### [Work with files](https://developers.cloudflare.com/sandbox/files/)

Move files, keep a workspace between instances, and mount an R2 bucket.

### [Preview applications](https://developers.cloudflare.com/sandbox/previews/)

From your browser, open a web server that runs in a sandbox.

### [Credentials and network](https://developers.cloudflare.com/sandbox/network/)

Keep credentials in your Worker, and decide which services a sandbox reaches.

### [Manage sandboxes](https://developers.cloudflare.com/sandbox/manage/)

List a user's sandboxes, and record when and why each one stops.

### [Coding agents](https://developers.cloudflare.com/sandbox/coding-agents/)

Run coding agents such as Claude Code, Codex, and Devin in a sandbox that belongs to one task.

---

## Related products

[Workers](https://developers.cloudflare.com/workers/)

The serverless platform these sandbox environments run on.

[Durable Objects](https://developers.cloudflare.com/durable-objects/)

Identity and coordination for an attached container.

[Workers AI](https://developers.cloudflare.com/workers-ai/)

Run models on Cloudflare, then execute the code they generate in a sandbox.

---

## More resources

| Topic | Links |
| --- | --- |
| Deploy and debug | [Deploy Containers](https://developers.cloudflare.com/containers/guides/deploy/), [Local development](https://developers.cloudflare.com/containers/guides/local-dev/), [Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/) |
| Reference | [`@cloudflare/sandbox`](https://developers.cloudflare.com/sandbox/reference/), [Durable Object container API](https://developers.cloudflare.com/containers/api/durable-object-container/), [Dynamic Workers API](https://developers.cloudflare.com/dynamic-workers/api-reference/) |
| Pricing and limits | [Containers pricing](https://developers.cloudflare.com/containers/platform/pricing/), [Container limits](https://developers.cloudflare.com/containers/platform/limits/), [Dynamic Workers pricing](https://developers.cloudflare.com/dynamic-workers/pricing/) |
| Related | [Code Mode](https://developers.cloudflare.com/agents/tools/codemode/), [Workers security model](https://developers.cloudflare.com/workers/reference/security-model/) |

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/sandbox/#page","headline":"Sandboxes on Cloudflare","description":"Execute untrusted or generated code in Linux virtual machines or isolated Workers.","url":"https://developers.cloudflare.com/sandbox/","inLanguage":"en","image":"https://developers.cloudflare.com/sandbox/og.png?v=a45996aa42e663ad","dateModified":"2026-09-30","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```

---

---
description: Build full-stack AI applications with Vectorize, Cloudflare's vector database.
title: Cloudflare Vectorize
image: https://developers.cloudflare.com/vectorize/og.png?v=8ae170b0ccff3d67
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/vectorize/llms.txt  
> Use this file to discover all available pages before exploring further.

# Cloudflare Vectorize

Last updated Apr 21, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/vectorize/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

Build full-stack AI applications with Vectorize, Cloudflare's powerful vector database.

Vectorize is a globally distributed vector database that enables you to build full-stack, AI-powered applications with [Cloudflare Workers](https://developers.cloudflare.com/workers/). Vectorize makes querying embeddings — representations of values or objects like text, images, audio that are designed to be consumed by machine learning models and semantic search algorithms — faster, easier and more affordable.

Vectorize is now Generally Available

To report bugs or give feedback, go to the [#vectorize Discord channel ↗︎](https://discord.cloudflare.com). If you are having issues with Wrangler, report issues in the [Wrangler GitHub repository ↗︎](https://github.com/cloudflare/workers-sdk/issues/new/choose).

For example, by storing the embeddings (vectors) generated by a machine learning model, including those built-in to [Workers AI](https://developers.cloudflare.com/workers-ai/) or by bringing your own from platforms like OpenAI, you can build applications with powerful search, similarity, recommendation, classification and/or anomaly detection capabilities based on your own data.

The vectors returned can reference images stored in Cloudflare R2, documents in KV, and/or user profiles stored in D1 — enabling you to go from vector search result to concrete object all within the Workers platform, and without standing up additional infrastructure.

---

## Features

[Vector database](https://developers.cloudflare.com/vectorize/get-started/intro/)

Learn how to create your first Vectorize database, upload vector embeddings, and query those embeddings from [Cloudflare Workers](https://developers.cloudflare.com/workers/).

Create your Vector database

[Vector embeddings using Workers AI](https://developers.cloudflare.com/vectorize/get-started/embeddings/)

Learn how to use Vectorize to generate vector embeddings using Workers AI.

Create vector embeddings using Workers AI

[Search using Vectorize and AI Search](https://developers.cloudflare.com/ai-search/)

Learn how to automatically index your data and store it in Vectorize, then query it to generate context-aware responses using AI Search.

Build a RAG with Vectorize

---

## Related products

[Workers AI](https://developers.cloudflare.com/workers-ai/)

Run machine learning models, powered by serverless GPUs, on Cloudflare’s global network.

[R2 Storage](https://developers.cloudflare.com/r2/)

Store large amounts of unstructured data without the costly egress bandwidth fees associated with typical cloud storage services.

---

## More resources

### [Limits](https://developers.cloudflare.com/vectorize/platform/limits/)

Learn about Vectorize limits and how to work within them.

### [Use cases](https://developers.cloudflare.com/use-cases/ai/)

Learn how you can build and deploy ambitious AI applications to Cloudflare's global network.

### [Storage options](https://developers.cloudflare.com/workers/platform/storage-options/)

Learn more about the storage and database options you can build on with Workers.

### [Developer Discord](https://discord.cloudflare.com)

Connect with the Workers community on Discord to ask questions, join the `#vectorize` channel to show what you are building, and discuss the platform with other developers.

### [@CloudflareDev](https://x.com/cloudflaredev)

Follow @CloudflareDev on Twitter to learn about product announcements, and what is new in Cloudflare Developer Platform.

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/vectorize/#page","headline":"Cloudflare Vectorize","description":"Build full-stack AI applications with Vectorize, Cloudflare's vector database.","url":"https://developers.cloudflare.com/vectorize/","inLanguage":"en","image":"https://developers.cloudflare.com/vectorize/og.png?v=8ae170b0ccff3d67","dateModified":"2026-04-21","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["AI"]}
```

---

---
description: Run machine learning models, powered by serverless GPUs, on Cloudflare's global network.
title: Cloudflare Workers AI
image: https://developers.cloudflare.com/workers-ai/og.png?v=28f3ca6015fd2e9e
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/workers-ai/llms.txt  
> Use this file to discover all available pages before exploring further.

# Cloudflare Workers AI

Last updated Apr 21, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/workers-ai/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

Run machine learning models, powered by serverless GPUs, on Cloudflare's global network.

Available on Free and Paid plans

Workers AI allows you to run AI models in a serverless way, without having to worry about scaling, maintaining, or paying for unused infrastructure. You can invoke models running on GPUs on Cloudflare's network from your own code — from [Workers](https://developers.cloudflare.com/workers/), [Pages](https://developers.cloudflare.com/pages/), or anywhere via [the Cloudflare API](https://developers.cloudflare.com/api/resources/ai/methods/run/).

Workers AI gives you access to:

- **50+ [open-source models](https://developers.cloudflare.com/workers-ai/models/)**, available as a part of our model catalog
- Serverless, **pay-for-what-you-use** [pricing model](https://developers.cloudflare.com/workers-ai/platform/pricing/)
- All as part of a **fully-featured developer platform**, including [AI Gateway](https://developers.cloudflare.com/ai-gateway/), [Vectorize](https://developers.cloudflare.com/vectorize/), [Workers](https://developers.cloudflare.com/workers/) and more...

[Get started](https://developers.cloudflare.com/workers-ai/get-started) [Watch a Workers AI demo](https://youtu.be/cK_leoJsBWY?si=4u6BIy_uBOZf9Ve8)

Custom requirements

If you have custom requirements like private custom models or higher limits, complete the [Custom Requirements Form ↗︎](https://forms.gle/axnnpGDb6xrmR31T6). Cloudflare will contact you with next steps.

Workers AI is now Generally Available

To report bugs or give feedback, go to the [#workers-ai Discord channel ↗︎](https://discord.cloudflare.com). If you are having issues with Wrangler, report issues in the [Wrangler GitHub repository ↗︎](https://github.com/cloudflare/workers-sdk/issues/new/choose).

---

## Features

[Models](https://developers.cloudflare.com/workers-ai/models/)

Workers AI comes with a curated set of popular open-source models that enable you to do tasks such as image classification, text generation, object detection and more.

Browse models

---

## Related products

[AI Gateway](https://developers.cloudflare.com/ai-gateway/)

Observe and control your AI applications with caching, rate limiting, request retries, model fallback, and more.

[Vectorize](https://developers.cloudflare.com/vectorize/)

Build full-stack AI applications with Vectorize, Cloudflare’s vector database. Adding Vectorize enables you to perform tasks such as semantic search, recommendations, anomaly detection or can be used to provide context and memory to an LLM.

[Workers](https://developers.cloudflare.com/workers/)

Build serverless applications and deploy instantly across the globe for exceptional performance, reliability, and scale.

[Pages](https://developers.cloudflare.com/pages/)

Create full-stack applications that are instantly deployed to the Cloudflare global network.

[R2](https://developers.cloudflare.com/r2/)

Store large amounts of unstructured data without the costly egress bandwidth fees associated with typical cloud storage services.

[D1](https://developers.cloudflare.com/d1/)

Create new serverless SQL databases to query from your Workers and Pages projects.

[Durable Objects](https://developers.cloudflare.com/durable-objects/)

A globally distributed coordination API with strongly consistent storage.

[KV](https://developers.cloudflare.com/kv/)

Create a global, low-latency, key-value data storage.

---

## More resources

### [Get started](https://developers.cloudflare.com/workers-ai/get-started/workers-wrangler/)

Build and deploy your first Workers AI application.

### [Plans](https://developers.cloudflare.com/workers-ai/platform/pricing/)

Learn about Free and Paid plans.

### [Limits](https://developers.cloudflare.com/workers-ai/platform/limits/)

Learn about Workers AI limits.

### [Use cases](https://developers.cloudflare.com/use-cases/ai/)

Learn how you can build and deploy ambitious AI applications to Cloudflare's global network.

### [Storage options](https://developers.cloudflare.com/workers/platform/storage-options/)

Learn which storage option is best for your project.

### [Developer Discord](https://discord.cloudflare.com)

Connect with the Workers community on Discord to ask questions, share what you are building, and discuss the platform with other developers.

### [@CloudflareDev](https://x.com/cloudflaredev)

Follow @CloudflareDev on Twitter to learn about product announcements, and what is new in Cloudflare Workers.

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/workers-ai/#page","headline":"Cloudflare Workers AI","description":"Run machine learning models, powered by serverless GPUs, on Cloudflare's global network.","url":"https://developers.cloudflare.com/workers-ai/","inLanguage":"en","image":"https://developers.cloudflare.com/workers-ai/og.png?v=28f3ca6015fd2e9e","dateModified":"2026-04-21","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["AI"]}
```
