Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

LLM Agent Function Calling, Multi-Turn Tools, and Structured Output

How function calling, multi-turn tools, JSON Schema outputs, and prompt chaining work when building LLM agents on hosted inference APIs.

Most of this page draws together Cloudflare Workers AI function-calling docs, Cloudflare agentic patterns, and Perplexity Agent API material on agents that call tools across many turns. The same ideas appear in model release notes for long-running agent sessions: large context windows, vision inputs, and optional “thinking” depth on some models (Workers AI changelog).

People usually land here when a chat model should do something—query an API, run code, or search—and they need reliable JSON back, not only prose. The providers differ in harness details, but the loop is the same: define tools, let the model request calls, execute them, feed results back, repeat until the task finishes.

Function calling: connect models to code and APIs

Section titled “Function calling: connect models to code and APIs”

Function calling (also called tool use) lets a large language model choose when to invoke developer-defined tools and return structured arguments your runtime can execute.

Function calling enables people to take Large Language Models (LLMs) and use the model response to execute functions or interact with external APIs. The developer usually defines a set of functions and the required input schema for each function, which we call tools. The model then intelligently understands when it needs to do a tool call, and it returns a JSON output which the user needs to feed to another function or API.

— Cloudflare, Function calling

In essence, function calling allows you to perform actions with LLMs by executing code or making additional API calls.

— Cloudflare, Function calling

You declare each tool with a name, description, and input schema (often JSON Schema). The model may answer in plain text or emit a tool-call payload; your application must run the tool and append the result to the conversation before the next model turn. On Workers AI, not every model supports this—catalog entries show a function-calling property; for example @hf/nousresearch/hermes-2-pro-mistral-7b is called out as a fine-tuned option (Function calling).

Workers AI features group related capabilities you typically combine with agents: Function calling, JSON Mode, asynchronous batch API, prompt caching, and others. Traditional function calling support was added in 2024 with per-model flags on the models page.

Multi-turn tool calling: keep the agent loop running

Section titled “Multi-turn tool calling: keep the agent loop running”

A single tool call rarely finishes a real task. Multi-turn tool calling means the model can request tools on turn one, read outputs you inject, then request more tools on later turns—the pattern behind coding agents, research assistants, and ops automations.

Recent Workers AI model announcements describe this explicitly for long sessions:

Multi-turn tool calling for building agents that invoke tools across multiple conversation turns

— Cloudflare, Moonshot AI Kimi K2.5 now available on Workers AI

The same bullet appears across Kimi K2.6/K2.7 and grouped AI changelog pages (changelog product group AI, Workers AI product changelog).

When you use OpenAI-style agent SDKs against Perplexity search tools, pairing matters: every function_call_output must carry the originating call_id when multiple parallel calls occur in one assistant turn (Use Search API with the OpenAI SDK). For long loops, previous_response_id lets you append new items instead of resending the full message array—important when context grows.

Instructions that shape tool output every turn

Section titled “Instructions that shape tool output every turn”

System or developer instructions apply on each iteration of the agent loop, so they are the right place for citation rules, grounding behavior, or response formatting after tools return.

Can be useful if you want to nudge how the model handles tool output. Things like citation style, grounding behavior, or response formatting fit naturally here, since instructions apply on every turn of the agent loop.

— Perplexity, Prompt Guide

Example from the same guide: cite sources inline by domain and state explicitly when tool results do not fully answer the question (Prompt Guide).

Structured outputs: JSON Mode, schema, and function calling together

Section titled “Structured outputs: JSON Mode, schema, and function calling together”

Downstream automation needs parseable data. Structured outputs (JSON mode or JSON Schema) constrain the model’s visible reply; function calling constrains tool arguments. Production agents often use both: tools for actions, schema-constrained messages for final reports or UI.

Cloudflare documents structured output alongside multi-turn tools on newer models:

Structured outputs with JSON mode and JSON Schema support for reliable downstream parsing

— Cloudflare, Moonshot AI Kimi K2.5 now available on Workers AI

Structured outputs with JSON schema support

— Cloudflare, Moonshot AI Kimi K2.7 Code now available on Workers AI

Perplexity’s cookbooks state the combination plainly:

Combine function calling with structured outputs and response shaping.

— Perplexity, Function Calling End-to-End

Combine structured outputs with multi-turn function calling.

— Perplexity, Structured Output Extraction

Practical cookbooks also cover RAG pipelines and cross-cutting agent patterns beyond core API reference (Getting Started).

Prompt chaining: break work into sequential model steps

Section titled “Prompt chaining: break work into sequential model steps”

Not every workflow needs a full tool loop. Prompt chaining decomposes a task into a sequence of LLM calls where each call consumes the previous output—useful for generate-then-verify flows without external APIs.

Decomposes tasks into a sequence of steps, where each LLM call processes the output of the previous one.

— Cloudflare, Agentic patterns

The Prompt Chaining example generates marketing copy, evaluates it with a structured quality object, and optionally regenerates with targeted fixes—showing how chaining plus schema validation can gate quality before you publish or call other systems.

For larger autonomous systems, some Workers AI models advertise agent swarm orchestration (hundreds of sub-agents and thousands of coordinated steps) and long-horizon coding across languages (Moonshot AI Kimi K2.6). That is horizontal scale on top of the same multi-turn tool pattern, not a separate integration model.

Long-running sessions: context, vision, reasoning, and harness hooks

Section titled “Long-running sessions: context, vision, reasoning, and harness hooks”

Model cards and changelogs emphasize capabilities that affect agent design rather than one-shot chat:

Capability Typical use in agents Source
256k–262k token context Keep history, tool definitions, and code in one session Kimi K2.5, Kimi K2.6
Vision inputs UI mocks, diagrams, screenshots in the loop Same changelogs
Thinking mode (chat_template_kwargs.thinking) Deeper reasoning when latency allows Kimi K2.7 Code
Function calling + multi-turn tools External APIs and staged workflows Workers AI features

On Google’s consumer research side, very large context plus retrieval is described as supporting long research chats (Gemini Deep Research)—a different product surface, but the same engineering pressure: agents must remember prior tool results.

If you build on Cloudflare’s agent harness (“think”), next topics include lifecycle hooks, workspace tools, code execution, client-side tools with approval, sub-agent RPC, and session compaction (Getting started). Sandbox tutorials point to a code interpreter API, file operations, and streaming progress (Analyze data with AI).

When agents run generated code, provider guidance stresses operational hygiene:

Clean up contexts - Delete contexts when done to free resources
Handle errors - Always check result.success and result.error
Stream long operations - Use streaming for code that takes >2 seconds
Validate AI code - Review generated code before execution

— Cloudflare, Use code interpreter

MCP and terminal agents: wiring external tools

Section titled “MCP and terminal agents: wiring external tools”

Model Context Protocol (MCP) servers expose tools to CLI agents. Cloudflare documents connecting the DEX MCP server through Gemini CLI: add an mcpServers entry pointing at https://dex.mcp.cloudflare.com/mcp in settings.json, then authenticate your Cloudflare account (DEX MCP server). A successful connection shows a message that one MCP server is in use (DEX MCP server).

The Gemini CLI repository targets enterprise Gemini Code Assist workflows; it documents install paths (npx, npm, Homebrew), GOOGLE_CLOUD_PROJECT / API key / Vertex AI auth, --output-format json for scripting, and features such as context files (GEMINI.md) and checkpointing (Gemini CLI). Perplexity’s TypeScript Agent CLI example is a smaller pattern: REPL, streaming, runtime model pick, optional web_search tool, and multi-turn history.

For enterprise Google Cloud deployments, Chrome’s AI docs note Gemini Enterprise Agent Platform and Model Garden for model choice (Evaluate product reviews with AI).

Common mistakes when building tool-calling agents

Section titled “Common mistakes when building tool-calling agents”
  • Assuming every model supports tools. Confirm function-calling support in the catalog (Function calling); guard models like llama-guard may require strictly alternating user/assistant messages (Workers AI changelog).
  • Dropping or mismatching call_id when parallel tool calls return (Use Search API with the OpenAI SDK).
  • Executing unreviewed generated code in sandboxes (Use code interpreter).
  • Omitting structured validation after a tool round—combine schema checks with chaining-style quality gates (Agentic patterns).
  • Debugging blind. On Workers AI embedded calling, runWithTools accepts { verbose: true } for call logs and I/O statistics (Troubleshooting).
  1. In the Workers AI model catalog, confirm your chosen model lists function calling (and JSON mode if you need structured replies).
  2. Run a minimal two-turn loop: one deliberate tool call, inject a fake result, and verify the model consumes it on turn two (Function calling).
  3. If you use Perplexity agent SDKs with search tools, inspect logs so each function_call_output includes the matching call_id (Use Search API with the OpenAI SDK).
  4. For embedded Workers AI calling, enable verbose runWithTools once in staging and confirm tool names and payloads match your schemas (Troubleshooting).
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page conflicts with the linked provider docs, email yimasynthetic@gmail.com with the page URL and the exact sentence you believe is wrong or unclear.