Skip to content

Build A Multi-Agent Workflow ​

This page shows the normal construction path for workflow graphs. For model-callable workflow tools, see Multi-Agent Capabilities.

Add Agents ​

Each node is an agent definition: an AgentConfig, or a definition the node writes inline.

csharp
var workflow = await AgentWorkflow.Create()
    .WithName("ResearchAndWrite")
    .AddAgent("research", new AgentConfig
    {
        Name = "Researcher",
        SystemInstructions = "Collect the key facts needed to answer the request.",
    }, node => node.WithOutputKey("research"))
    .AddAgent("write", new AgentConfig
    {
        Name = "Writer",
        SystemInstructions = "Write a concise final answer using the provided research.",
    }, node => node.WithInputKey("research"))
    .From("research").To("write")
    .BuildAsync();

AgentWorkflow.Create() returns the fluent builder. BuildAsync() creates an AgentWorkflowInstance, which is the runnable workflow object used by RunAsync(...), ExecuteStreamingAsync(...), subscriptions, and config export. The instance owns the workflow's AgentRuntime; dispose it with await using or DisposeAsync().

Agent insertion order is not the execution order. Declare edges for the order you want. A workflow with two unrelated agents and no declared edge has two entry nodes, not an automatic first -> second chain.

The example above constructs the graph. Direct execution still needs each node to resolve a provider client. For a standalone workflow, configure a provider on each definition (for example .WithOpenAI(model: "gpt-5-mini"), resolved through the application's provider composition and secrets) or give it a client with .WithChatClient(chatClient). Parent-client inheritance applies when the workflow is invoked from an agent through [MultiAgent].

Construction Forms ​

Use an AgentConfig when the definition is written ahead of the workflow. The workflow registers a copy of it under the node id:

csharp
.AddAgent("review", new AgentConfig
{
    Name = "Reviewer",
    SystemInstructions = "Review the answer for accuracy.",
})

Write the definition inline when it belongs to this node only. The action receives a fresh AgentConfig:

csharp
.AddAgent("review", config => config
    .WithInstructions("Review the answer for accuracy.")
    .WithToolHarness<ReviewTools>())

An inline definition is written when the workflow first runs and can carry process-local parts, so a workflow with an inline node cannot be exported to declarative configuration. Use an AgentConfig for nodes that should export.

On first execution the workflow builds one AgentRuntime, registers every node definition under its node id (the first node added is the runtime's default agent), and builds each node agent through it. Node ids are agent ids: a node's executions carry the node id as AgentId. If a node does not configure its own provider, it can inherit the invoking parent agent's client when the workflow is called through [MultiAgent]. Direct workflow execution has no parent agent from which to inherit.

Conversation Policy ​

Workflow outputs are separate from durable conversation history. Add a conversation policy when each node agent's transcript should be saved into HPD sessions and threads:

csharp
using HPD.Agent.Serialization;

if (!AgentEventCompositionHost.TryGetDefaultApplication(out var events))
    throw new InvalidOperationException("A generated application event composition is required.");

var sessionStore = new FileSessionStore("App_Data/sessions", events.Codec);

var workflow = await AgentWorkflow.Create()
    .WithName("ResearchAndWrite")
    .WithSessionStore(sessionStore)
    .WithConversation(MultiAgentConversationPolicies.ForkThreadPerAgent())
    .AddAgent("research", researchConfig, node => node.WithOutputKey("research"))
    .AddAgent("write", writeConfig, node => node.WithInputKey("research"))
    .From("research").To("write")
    .BuildAsync();

WithSessionStore(...) stores conversations and threads. The store must use the application's generated event codec; the workflow runtime uses it for every node agent. Without a session store the workflow runtime keeps sessions in memory.

Use SharedWorkflowThread() for one transcript, ThreadPerAgent() for durable agent-local threads, or ForkThreadPerAgent() when agents should start from the same request and write into separate threads.

Edges ​

Edges define the graph:

csharp
.From("research").To("write")

Multiple sources and targets are allowed:

csharp
.From("draft", "facts").To("review")

If you do not declare a node's incoming edge, HPD adds an edge from START. If you do not declare a node's outgoing edge, HPD adds an edge to END.

text
START -> first node without incoming declared edge
last node without outgoing declared edge -> END

You can still declare START and END yourself when you want the entry and exit points to be explicit:

csharp
.From("START").To("classify")
.From("write").To("END")

Use .From(...).To(...) for sequencing whenever one agent must run after another.

Execute ​

Subscribe before execution if the application needs live events:

csharp
using var events = workflow.SubscribeAny(evt =>
{
    timeline.Project(evt);
});

await foreach (var evt in workflow.ExecuteStreamingAsync(
    "Compare the two implementation options.",
    cancellationToken: CancellationToken.None))
{
    // Render from this stream, or from subscriptions, but avoid double-rendering both.
}

ExecuteStreamingAsync(...) emits workflow graph events and child agent events. RunAsync(...) drains the workflow and returns a WorkflowResult.

The workflow stream yields AgentEvent values, so application code does not need to reference HPD.Events. When the workflow is generated as a [MultiAgent] tool, the wrapper supplies parent event context internally. Use WorkflowEventCoordinator when the application needs to approve or deny a request while streaming.

Runtime Options ​

Node options control input, output, structured result handling, retry, timeout, context, approvals, and handoff targets.

csharp
.AddAgent("analyze", analyzerConfig, node =>
{
    node
        .WithInputKey("research")
        .WithOutputKey("analysis")
        .WithTimeout(TimeSpan.FromSeconds(30))
        .WithRetry(maxAttempts: 3);
    node.RunConfig.SystemInstructions = new SystemInstructionsRunConfig
    {
        Append = "Prefer concrete evidence over speculation."
    };
})

WithTimeout(...) is applied to the graph node and the child agent run. WithRetry(...) is wired through the graph node retry policy.

Error-mode helpers such as OnErrorFallback(...) are part of the configuration/export surface, but validate execution behavior in your workflow before relying on them as runtime policy.

Host Binding ​

A standalone workflow builds its runtime over the application's generated provider and event compositions, with the default secret resolution (environment variables and application configuration) and the session store passed to WithSessionStore(...), which must use the application's event codec (in memory when none is set).

A host that owns those pieces supplies a WorkflowHostBinding with WithHost(host), AgentWorkflow.FromFile(path, host), or new MultiAgentFactory(host). The binding carries the provider composition, event composition, session store, services, and the security ceiling for node runs. Subclass it to shape the workflow's runtime and its node definitions:

csharp
public sealed class AppWorkflowHost(
    ProviderComposition providers,
    AgentEventComposition events,
    ISessionStore sessionStore,
    AgentSecurityRunConfig authorization,
    IConfiguration configuration)
    : WorkflowHostBinding(providers, events, sessionStore, authorization)
{
    public override void ConfigureRuntime(string workflowName, AgentRuntimeBuilder builder)
        => builder
            .AddSecretResolver(new ConfigurationSecretResolver(configuration))
            .WithPermissions();

    public override void ConfigureAgent(WorkflowNodeIdentity identity, AgentConfig definition)
        => definition.WithInstructions(
            $"{definition.SystemInstructions}\nYou are node '{identity.NodeId}' of {identity.WorkflowName}.");
}

ConfigureRuntime(...) configures what every node agent shares: secrets, shared middleware such as permissions or a sandbox, and stores. The host's event composition, session store, and services are applied after it. ConfigureAgent(...) adjusts each node's definition, a copy the workflow owns, before the runtime registers it under the node id.

Durable Host Execution ​

AgentWorkflowInstance is an in-process graph runtime. It does not own restart-durable checkpoint or resume state.

For durable, restart-safe execution, install the graph as an HPD Base activation and expose it through the multi-agent ASP.NET projection. HPD Base owns activation state, retries, checkpointing, and worker recovery. See Checkpointing and ASP.NET Multi-Agent Workflows.

Built for production .NET agent applications.