Model API Parameters: Messages, Embeddings, Tools, and Retrieval
How to shape messages, generation limits, tools, embeddings, and retrieval options when calling hosted inference and search APIs.
Most of this material comes from Cloudflare Workers AI model reference pages and Cloudflare AI Search bindings. The same request ideas also appear in Brave Answers, Perplexity embeddings and search, and agent helpers such as runWithTools. If you are wiring a Worker, an SDK, or a third-party client against a hosted model, you are usually choosing a schema variant (chat messages versus Responses-style input), then filling generation, tools, or embedding fields that the provider actually enforces.
messages and roles: what every chat-style call needs
Section titled “messages and roles: what every chat-style call needs”Chat and completion endpoints expect a messages array (or, on some surfaces, contents with role user | model). On the OpenAI-compatible shape exposed for many Workers AI models, each message has a role and content that can be a string, null, or a multimodal array.
Typical roles on that shape are system, developer, user, assistant, and tool (see parameter lists on models such as GPT-4o and DeepSeek V4 Pro). Anthropic-shaped models on Workers AI (for example Claude Haiku 4.5) restrict roles to user and assistant, support a top-level system string, and allow structured content blocks with optional cache_control (type ephemeral, ttl 5m | 1h).
Cloudflare AI Search extends the chat pattern for RAG: roles include system, developer, user, assistant, and tool; content may be text, image_url (HTTPS or data:image/...;base64,...), or file parts (base64 file data plus filename, decoded size up to 10 MiB).
The chat model is text-only. File and image message parts are not supported.
— Cloudflare, AI SDK
Generation parameters: temperature, caps, stream, and finish reasons
Section titled “Generation parameters: temperature, caps, stream, and finish reasons”Generation options are passed through to the model configured on the instance or named in the request. Common fields across Workers AI chat models include:
| Parameter | Typical role | Notes from cluster schemas |
|---|---|---|
temperature |
Randomness | Often 0–2 (Anthropic models on Workers AI often cap at 1) |
max_tokens / max_completion_tokens / max_output_tokens |
Output cap | Name depends on schema variant; must be > 0 where exclusiveMinimum applies |
top_p, frequency_penalty, presence_penalty |
Sampling / repetition | OpenAI-compatible chat models |
stream |
Incremental output | Default varies; Brave Answers defaults stream to true |
reasoning_effort / reasoning.effort |
Reasoning depth | Values are model-dependent (for example none | low | medium | high on GPT-4.1; extended sets on some GPT-6 family pages) |
For AI Search chat, maxOutputTokens truncates the response and sets finishReason to "length". If a model ignores an option, the result’s warnings array may stay empty, so unsupported options can fail silently—the same page notes that you override the generation model per request with instance.chat({ model: "..." }).
Generation options such as temperature and maxOutputTokens are passed through to the instance’s generation model. maxOutputTokens truncates the response and sets finishReason to “length”. If a model ignores an option, the result’s warnings array stays empty, so an unsupported option fails silently.
— Cloudflare, AI SDK
Responses-style schemas (for example GPT-5, Ember-1) accept input as a string or array, plus instructions, tools, tool_choice, text, and reasoning. Returned objects use status values such as in_progress, completed, failed, or incomplete, with usage token fields.
Schema variants: when to use messages vs input
Section titled “Schema variants: when to use messages vs input”Many Cloudflare model pages list two schema variants for the same underlying capability:
- Chat Completions —
messages[],choices[],finish_reason, optionaltool_callsandaudioon Beam 1.0. - Responses —
input,instructions,output[],output_text,object: "response"on the same models and on OpenAI-style o3.
Gemini-family pages add a native contents / systemInstruction / generationConfig shape alongside the OpenAI-compatible messages form (Gemini 2.5 Flash). Pick the variant your HTTP client or binding expects; mixing fields from both shapes in one request usually fails validation.
Specialized non-chat APIs use their own bodies—for example OpenAI Decisions (questions[] with predicate, choice, or score types) and Typesafe Jev (state plus questions map).
Tools and function calling
Section titled “Tools and function calling”OpenAI-compatible models accept a tools array and tool_choice. Grok 4.3 allows up to 128 tool calls on an assistant message and supports parallel_tool_calls, response_format (text, json_object, json_schema), and search_parameters for grounded answers.
On Workers, embedded function calling uses runWithTools: you pass the AI binding, model id, messages, tools, and optional config (streamFinalResponse, maxRecursiveToolRuns, strictValidation, verbose, trimFunction / autoTrimTools to reduce tokens sent to inference).
This wrapper method enables you to do embedded function calling. You pass it the AI binding, model, inputs (messages array and tools array), and optional configurations.
— Cloudflare, runWithTools API reference
Claude Opus 5.5 adds thinking (type: "adaptive"), output_config.effort, and tool_choice types auto or none with optional disable_parallel_tool_use.
Embeddings: text batches, pooling, query–context, and response encoding
Section titled “Embeddings: text batches, pooling, query–context, and response encoding”Workers AI embedding models
Section titled “Workers AI embedding models”English BGE models (bge-base-en-v1.5, bge-small-en-v1.5, bge-large-en-v1.5) take text as one string or up to 100 strings per call. The pooling parameter is mean (default) or cls:
clspooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling.
— Cloudflare, bge-base-en-v1.5
bge-m3 accepts query plus contexts[] (index order matters in the response) or embedding mode without a query; truncate_inputs controls whether overlong context errors or truncates. bge-reranker-base scores contexts against a query and returns top_k results with id (context index) and score.
qwen3-embedding-0.6b supports queries, documents, or text aliases, up to 32 items per array, with optional instruction defaulting to a web-search retrieval phrase.
Perplexity embeddings API
Section titled “Perplexity embeddings API”Create Embeddings returns data[].embedding as a Base64-encoded vector (with base64_int8 / base64_binary decoding rules documented on the response). Usage includes prompt_tokens, total_tokens, and USD cost fields. Contextualized embeddings nest vectors per document chunk with data[].index and per-chunk data[].data[].embedding.
AI Search retrieval and chat overrides
Section titled “AI Search retrieval and chat overrides”The current Workers binding accepts messages, optional model, stream, and ai_search_options for retrieval and generation behavior:
ai_search_options area |
Purpose |
|---|---|
retrieval.retrieval_type |
vector, keyword, or hybrid (default hybrid) |
retrieval.match_threshold |
0–1, default 0.4 |
retrieval.max_num_results |
1–50, default 10 |
retrieval.keyword_match_mode |
and (default) or or for keyword matching |
retrieval.fusion_method |
rrf or max for hybrid scoring |
reranking |
enabled, model e.g. @cf/baai/bge-reranker-base, match_threshold |
query_rewrite |
Optional rewrite model and rewrite_prompt |
cache |
Per-request cache override and cache_threshold presets |
The legacy binding used a single query string plus rewrite_query, ranking_options.score_threshold, and a simpler reranking block—migrate to messages + ai_search_options for parity with multimodal and retrieval controls.
Web-grounded answers: Brave and Perplexity
Section titled “Web-grounded answers: Brave and Perplexity”Brave Answers (API reference) is stricter than a full chat API: messages must contain exactly one user message. It supports web_search_options (search_context_size low | medium | high, optional user_location), enable_research (iterative deep research; requires stream=true), and research budgets (research_maximum_number_of_queries 1–50 default 20, research_maximum_number_of_seconds 1–300 default 180). Fields such as metadata and seed are accepted for OpenAI SDK compatibility but ignored (answers are not reproducible).
Perplexity Search (Search the Web) takes query (string or array), search_type web | fast | people, max_results up to 50 for people search, token limits on page content, and date or recency filters. The Agent API prompt guide stresses that input wording drives retrieval quality: vague prompts produce vague searches. Customizing effort levels shows overriding a single field (for example max_steps) while keeping an effort preset. The Orchestrator quickstart points to separate Chat Completions, Responses, and Messages schema references.
Common conclusion: grounded APIs couple tight input shape (one user turn on Brave; descriptive input on Perplexity) with search knobs you do not see on plain chat models. Chat parameters like temperature matter less if the product spends most of the budget on search and synthesis.
Safety, vision, and task-specific bodies
Section titled “Safety, vision, and task-specific bodies”Some models are not general chat:
- llama-guard-3-8b — alternating
user/assistantstrings;response_format.typejson_objectyieldssafeandcategories(S1–S14). - moondream3.1-9B-A2B —
taskquery|caption|point|detect; image URL or base64;point/detectdo not stream. - distilbert-sst-2-int8 — single
textin, classification array out.
For agent harnesses, TurnContext lists what a turn assembles: system, messages, merged tools, model, continuation, and custom body fields. OpenCode documents harness.prompt(), operationId deduplication, and whenBusy: "steer" for queued follow-ups.
Common mistakes
Section titled “Common mistakes”- Sending multimodal
contentthrough the AI Search AI SDK path while the binding documents images and files. - Mixing
meanandclspooling in the same vector index without re-embedding. - Assuming
metadataorseedon Brave Answers change behavior; they are ignored. - Using
enable_citations/enable_entities/enable_researchon Brave withoutstream=true, or expecting them in non-research mode where unsupported. - Passing unsupported generation options to AI Search and not checking
warningsorfinishReason: "length". - Choosing Responses field names (
max_output_tokens,input) against a Chat Completions endpoint (or the reverse). - Ignoring context index order on bge-m3 and bge-reranker-base when mapping scores back to documents.
How to check this on your site
Section titled “How to check this on your site”- Open the parameter reference for your exact model (for example GPT-4o) and confirm which schema variant your client sends.
- For RAG, compare your Worker payload to AI Search Workers binding fields (
retrieval_type,match_threshold,reranking). - For embeddings, run a one-string and a small batch call on bge-base-en-v1.5 with the same
poolingyou use in production. - If you use Brave or Perplexity grounded APIs, validate request shape against Brave Answers and Perplexity Create Embeddings or Search the Web responses.
- You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page does not match the provider docs or your live API behavior, email yimasynthetic@gmail.com with the page URL and the exact statement you believe is wrong so it can be corrected.