Skip to content

Declarative Config to AG2 Mapping

This document maps canonical workflow YAML declaratives to AG2-native execution.

Runtime loading is strict. Files are validated by typed contracts (Pydantic with extra="forbid"), so examples here use only canonical shapes.

Core Point

Only workflow declaratives map to AG2.

These do not map to AG2:

  • app backend declaratives
  • shell declaratives
  • domain event contracts
  • workflow triggers

Those are Mozaiks layers that exist before a workflow starts.

Workflow File Mapping

Workflow file Role AG2 relationship
orchestrator.yaml pattern, turns, startup behavior mostly AG2-native
agents.yaml agent roster and prompts AG2-native with Mozaiks composition helpers
transition_graph.yaml routing rules inside the workflow AG2 1.0 WorkflowAdapter / TransitionGraph
context_variables.yaml workflow state bindings AG2-native container plus Mozaiks adapters
tools.yaml tool declarations AG2 tool calling plus Mozaiks wrappers
middleware.yaml prompt injection and transient status context Mozaiks declarations compiled to AG2 middleware
structured_outputs.yaml typed runtime validation Mozaiks layer
ui_config.yaml frontend exposure metadata frontend-only
extended_orchestration/task_batches.yaml workflow-local deterministic task DAG contract Mozaiks contract layer executed through AG2 where possible

Native or Near-Native Mappings

orchestrator.yaml

Maps to workflow-local execution concerns such as:

  • pattern selection
  • startup mode
  • initial agent
  • initial message
  • turn budget

Canonical startup key is workflow_startup_mode (AgentDriven, UserDriven, BackendOnly).

orchestration_pattern is metadata describing the selected AG2 Network patternbook label. The runtime does not route from this string; it routes from the compiled transition_graph.yaml transition graph.

agents.yaml

Each agent entry becomes an AG2 agent definition after prompt composition and tool binding.

Provider selection stays explicit in llm_config. With AG2 1.2.2, api_type: openai maps to OpenAICompletionsConfig and keeps Chat Completions; setting use_responses_api: true selects OpenAIResponsesConfig instead. AG2's OpenAIConfig name is not used because its meaning changes in AG2 1.4.0. Anthropic configs omit the shared temperature setting: Anthropic SDK 2.x rejects that sampling parameter. OpenAI and Gemini retain their supported temperature settings.

The canonical Factory loader uses the existing provider config builder for LLM_PRIMARY_API_TYPE and LLM_PRIMARY_MODEL, with the matching secret handle. DEFAULT_LLM_MODEL applies when no explicit primary model is selected; LLM_FALLBACK_MODELS lists additional entries. Stored provider entries retain api_type, base_url, and native output/retry limits; an untyped stored entry keeps the historical OpenAI default. Provider order, type, URL, key, and limits participate in cache invalidation, and raw TTL refresh precedes derived-cache lookup. Config logs never include credential values. The Factory typed-config path selects the first configured entry; additional entries do not provide automatic provider failover in this path.

LLM_MAX_TOKENS is an optional positive integer for the existing native max_tokens field. Explicit per-call limits override this environment default; stored provider-entry limits retain the adapter's precedence. AG2 validates provider support, so Gemini's distinct max_output_tokens field must be supplied through explicit config or a stored provider entry. No provider default changes when the environment setting is absent.

Returning a tool's exact text

A local agent can delegate its entire reply to one declared workflow function. For example, add the following entry to agents.yaml:

- name: Receipt
  structured_outputs_required: false
  reply_tool: render_receipt

Declare render_receipt as this agent's sole bound Agent_Tool in tools.yaml, with auto_tool_call: false. Omit the model prompt and use a null structured-output registry entry. The Python function can take context_variables for runtime-bound scope, or take no arguments. It returns the nonempty text the user should see. The workflow still owns authorization and which records the function reads. Include the agent in ui_config.yaml's visual_agents and route to user for follow-up questions when appropriate.

AG2 invokes the declared function once per turn without a model provider or credentials. Its native final tool result becomes the workflow packet and follows normal transcript replay. An exception, empty result, or non-text result fails the turn. A reply that needs to communicate missing information should return an appropriate message from the function.

transition_graph.yaml

Maps to AG2 1.0 Network transition conditions and targets. Mozaiks compiles the rules into a TransitionGraph; turn-to-turn routing is resolved through AG2 1.0 WorkflowAdapter.

Runtime compilation rules:

  • unconditional after_turn rules compile to FromSpeaker
  • condition_type: context_equals rules compile to a source-scoped adapter over AG2 ContextEquals
  • condition_type: context_expression rules compile to a source-scoped custom AG2 1.0 TransitionCondition that evaluates Mozaiks ${context_variable} syntax against workflow context state
  • condition_type: tool_called rules compile to SourceScopedToolCalled, a native AG2 ToolCalled subclass that also checks the declared source agent
  • target_agent: user pauses the run for user input
  • target_agent: terminate compiles to TerminateTarget

AG2 derives tool routing from its native ToolCallEvent stream, including turns with an empty message body. The registered mozaiks_source_tool_called condition retains both source_agent_id and tool_name through graph serialization and rehydration. Static tool routing still evaluates the source predicate when AG2 selects the target: another agent calling the same tool cannot satisfy that rule. Text mentioning the tool and a ToolResultEvent without its matching call do not establish a tool transition. AG2 owns event interpretation, packet construction, transition evaluation, and workflow state progression.

LLM classification belongs before routing: a Refinement Engine route, agent tool, or structured output sets context state; the graph then routes deterministically.

Termination is declarative. A workflow bundle ends through transition_graph.yaml, usually by routing the final agent to:

- source_agent: FinalAgent
  target_agent: terminate
  transition_type: after_turn
  transition_target: TerminateTarget

The runtime does not inspect message text for completion and does not use a separate Python termination handler. During execution, Mozaiks resolves the next speaker through AG2 1.0 WorkflowAdapter; when that resolution returns AG2 TerminateTarget, the turn loop reports run_completed=true and the runtime marks the app-scoped ChatSessions run as completed. max_turns remains a safety cap, not the primary happy-path completion mechanism.

A rule may end the run as failed with termination_reason: workflow_failed. That close, max_turns and no_transition_matched end the run as failed: the session is marked failed and one chat.run_complete with status: failed carries the close reason. A workflow can explain a workflow_failed end to the user by naming a declared string context variable in orchestrator.yaml:

failure_message_key: app_build_failure_message

A deterministic tool writes that variable when it decides the run cannot continue; the runtime reports its text as the failed run's error.

context_variables.yaml

Maps to the shared workflow state container used during execution.

Canonical shape:

definitions:
  var_name:
    type: string
    source:
      type: state
      default: null
agents:
  AgentName:
    variables:
      - var_name

ContextAuthorityPolicy owns write permission. The factory-injected ContextVariablesBridge checks each set or delete before accepting it. A declared deterministic_tool writer is selected only inside the trusted callable invocation installed by the agent factory, bound to that exact bridge, policy instance, and (workflow_name, app_id, chat_id) run. Tool arguments cannot replace the injected bridge or choose its writer identity. Ordinary bridge access remains context_bridge; a variable declaration alone does not establish tool provenance.

The invocation's deterministic attribution expires when the callable exits, including on failure. Revocation also applies to invocation context inherited by unfinished child tasks. Each pending set or delete retains the writer that authorized that operation; later operations are checked independently. Before publication, the packet adapter verifies the same policy/run binding and checks every pending operation again under its retained writer. Updates already present in an outgoing packet receive only context_bridge attribution. Authorized updates then reach AG2's native fold before ContextEquals selects the next speaker.

tools.yaml

Maps to callable tool registration, with optional Mozaiks validation or wrapper behavior.

Canonical shape:

tools:
  - agent: AgentName
    file: tool_file.py
    function: run_tool
    tool_type: Agent_Tool
  - agent: AgentName
    file: render_status.py
    function: render_status
    tool_type: UI_Surface
    ui:
      component: StatusPanel
      mode: artifact
lifecycle_tools: []

middleware.yaml

Maps to prompt-injection declarations and optional AG2 1.3 statusbar middleware. Lifecycle behavior belongs in tools.yaml lifecycle_tools.

Canonical shape:

prompt_middleware:
  - agent: AgentName
    filename: hook_file.py
    function: update_state
statusbar_middleware:
  - agent: AgentName
    variables: [current_phase]

Statusbar entries select existing per-agent model-visible context keys. Runtime validation rejects undeclared/unexposed keys, duplicates and remote agents. Selected values are read from the live context bridge on every provider attempt and sent through statusbar_middleware(..., persist=False) as transient model input, instead of duplicating them in the ordinary system-prompt projection. This declares no UI, persistence, routing, or new state authority.

Mozaiks-Only Workflow Layers

structured_outputs.yaml

Used for:

  • typed validation
  • deterministic auto-tool flows
  • stronger execution guarantees than prompt text alone

Canonical shape:

schema_version: mozaiks.structured_outputs.v1
registry:
  AgentName: ModelName
models:
  ModelName:
    type: model
    fields:
      field_name:
        type: str

Schema transport is selected separately from this acceptance contract:

  • LLM_STRUCTURED_OUTPUT_MODE=native is the default and keeps the existing provider-native schema preparation. OpenAI, Azure and Gemini receive the wire projection from get_provider_response_model, which requires every property (a nullable field must still be present, as null). Gemini decodes against the schema and otherwise leaves optional properties out: PatternAgent dropped pack_partition_reason in 10 of 15 samples. Anthropic and Ollama receive the declared model.
  • LLM_STRUCTURED_OUTPUT_MODE=prompted uses AG2's PromptedSchema. AG2 includes the same declared model's JSON schema in the system prompt and validates the response with that model, without sending a native output grammar.

A top-level llm_config.structured_output_mode value overrides the environment; get_llm_config(extra_config={"structured_output_mode": "prompted"}) resolves and caches that choice explicitly. Values other than native and prompted fail before a model call. This applies to Factory agents and the shared AG2StructuredAgentRunner used for auxiliary refinement and coding calls. Mode selection is explicit; provider errors do not switch modes automatically.

An agent whose schema a provider cannot compile natively declares that provider in agents.yaml, for example prompted_schema_providers: [google]. On a listed provider the agent's own turns and its task-batch workers use the prompted transport; on every other provider the mode above applies unchanged. Accepted values are openai, azure, anthropic, google and ollama. AppGenerator declares google for AppPlanAgent, AppSchemaAgent, ConfigMiddlewareAgent and ControllerAgent. Their schemas (56 to 104 KB) exceed Gemini 3.8 Flash's native compiler ("too many states for serving"); every other Factory schema (28 KB or less) compiles.

Prompted mode preserves workflow context projection and local typed validation. Factory output must still pass the canonical acceptance model before an automatic save/tool event is emitted. Provider-native constraints are absent, so malformed responses can occur and must fail validation or use the caller's existing bounded schema-correction retries. An isolated provider/schema probe establishes transport and parsing behavior only; generated-app acceptance remains a separate check. See local setup for provider complexity limits and configuration.

ui_config.yaml

Used for:

  • frontend rendering metadata
  • agent visibility rules

extended_orchestration/task_batches.yaml

Used for:

  • declaring which agent produces or exposes a typed task list
  • mapping each task item to an AG2 worker agent and prompt
  • bounding concurrency, retries, timeouts, dependencies, and failure policy
  • declaring the result context key consumed by later workflow agents

The typed DAG contract is Mozaiks-owned because AG2 Task does not assign, dependency-sort, or merge artifact work. Worker execution, task lifecycle observation, and network turn handling should use AG2 Network/Task primitives where practical. See AG2 Execution Alignment Plan.

Minimal task batch authored form:

version: 1
batches:
  - id: my_tasks
    trigger_agent: PlanningAgent
    source:
      kind: context_variable
      path: plan.tasks
      task_model: MyTask
    worker:
      mode: ag2_agent
      agent_field: initial_agent
      prompt_field: initial_message
    result:
      context_key: my_task_results
      status_key: my_task_status

Schema defaults that do not need to be authored: - worker.mode defaults to ag2_agent - execution.concurrency defaults to 4 - execution.failure_policy defaults to fail_batch - result.merge_strategy defaults to collect_task_outputs

Declare result keys in context_variables.yaml when agents need to read them. task_batches.yaml is execution config; it is not a substitute for typed shared workflow state.

What Sits Before AG2

The following app-bundle families are consumed before AG2 is involved:

  • app/data/*
  • app/modules/*
  • app/config/*
  • workflow triggers: declared in workflows/*/orchestrator.yaml for app-owned workflows, or factory_app/workflows/*/orchestrator.yaml for builder/system workflows

Most importantly:

  • a domain event becomes a route decision before AG2 sees a workflow input

That route decision belongs to Mozaiks.

Design Guardrails

Do not use AG2 as the conceptual home for:

  • CRUD state
  • navigation
  • settings and subscription policy
  • domain event naming
  • event-to-workflow policy

Use AG2 for what it is good at:

  • conversations
  • handoffs
  • tool use
  • agent coordination inside a workflow

AgentGenerator selects workflow shapes from the shared AG2 Network Patternbook. The patternbook guides generation; the generated YAML remains the runtime contract.

Authoring Note

Use *.yaml declaratives in workflow bundles.

Cross References