04 - Build
Explore documentation · Previous: 03 - Understand · Next: 05 - Operate
Use the base SDK for direct application code, an optional adapter for an existing agent framework, or reviewed native providers for bounded enforced dependencies. Every example uses synthetic inputs. Default framework/model examples use mocks; no tutorial performs an external financial operation.
Build dependency-aware workflow
Problem: status can change between an assessment and a recommendation. Without Co2, keeping both results can preserve stale reasoning; refreshing everything repeats independent credit work.
Approach: register source versions, capture each invocation, publish immutable artifacts, obtain a plan after a change, and explicitly run eligible work with fresh identities. Start with the guided lending example:
python examples/quickstart.py
Outcome: eligibility and recommendation each execute twice, credit once; the original credit artifact is reused and a concurrent late result is rejected. plan_actions() supplies dispositions; explain_artifact() supplies selected causes. The host owns all actual execution and source bytes.
Publish outputs with separate dependencies
A single assessment invocation may produce eligibility and credit. Without distinct output slots, both would be invalidated together. With trusted structured dependencies, the two artifacts can retain independent contracts.
This standalone SDK example publishes both outputs atomically and shows the resulting granularity:
from co2 import (
Coherence, Declaration, DeclarationSource, DependencyStrategy,
ExecutionKind, OutputSubmission, PlanAction, ResourceRef,
)
with Coherence() as core:
core.register_resource("status", "active-v1")
core.register_resource("credit-history", "good-v1")
core.begin("assessment-1", "assess", resources=["status", "credit-history"],
strategy=DependencyStrategy.EXPLICIT_STRUCTURED,
execution=ExecutionKind.DETERMINISTIC)
core.complete_outputs("assessment-1", [
OutputSubmission("eligibility", "eligibility-1", b"active",
Declaration(DeclarationSource.DEVELOPER, (ResourceRef("status"),))),
OutputSubmission("credit", "credit-1", b"good",
Declaration(DeclarationSource.DEVELOPER, (ResourceRef("credit-history"),))),
])
core.register_resource("status", "inactive-v2")
actions = {step.output: step.action for step in core.plan_actions().steps}
assert actions == {"eligibility": PlanAction.RECOMPUTE, "credit": PlanAction.REUSE}
The fixed synthetic values stand for host-owned bytes matching the registered versions. Developer declarations are completeness assertions about the actual producer code; do not mark model-generated dependency lists as trusted. LLM declarations, absent declarations and observed omissions fall back conservatively. Malformed/inaccessible references or any stale captured input reject the batch without publishing one output early. See strategy semantics and output contracts.
To add a shared dependency, include its resource in the invocation and in both trusted declarations. To add a recommendation, capture both assessment artifact IDs. The complete quickstart implements that derived output and replaces only the affected slot after a change.
Handle concurrent and late work
Without a publication check, a slow assessment can overwrite newer reasoning. The host may execute work concurrently, but each result must pass Co2's atomic completion validation. The quickstart uses an actual worker thread and events to demonstrate the race; independent assessment agents in the framework examples overlap asynchronously.
If StaleDependencyError rejects a direct SDK result, do not relabel it with the new source version. Abandon that invocation if it will not complete; capture fresh context and new identities for eligible replacement work. Adapters perform their captured-attempt cleanup on failure. Cancellation of external inference remains separate. A plan does not reserve inputs or prevent updates after it was read. See publication guarantees and failure handling.
Control reasoning and consequential work
A model may produce a different response from identical inputs. Classify it as ExecutionKind.PROBABILISTIC_REASONING, validate the output before publication, and keep its prompt, schema, model configuration and every accessible semantic input in the dependency contract. An output schema is not a dependency-completeness or semantic-equivalence proof.
Stale reasoning is blocked by default. The application may explicitly request PlanPolicy(allow_probabilistic_recomputation=True) when asking for a plan and still decides whether to run it. Stale human decisions require revalidation; side effects block; irreversible operations escalate. A historical approval/funding record is a host assertion, not evidence of execution or authorization to repeat it.
python examples/lending.py
This synthetic example compares invocation-level, developer-declared and runtime-observed dependencies, plus execution-aware dispositions. It makes no LLM calls. For mock/live comparison mechanics, use the model experiment tutorial; live requests require a separate explicit opt-in and bounded usage.
Integrate agent frameworks
Each guide explains the application problem, adapter mapping, executable example, expected outcome, host responsibilities and failure boundary. Install only the extra you need. Frameworks retain orchestration; Co2 does not introduce another scheduler.
| Framework | Tutorial | Default executable | Critical boundary |
|---|---|---|---|
| LangGraph | Route graph nodes | python examples/langgraph_lending.py | Graph checkpoints and Co2 publication are separate authorities. |
| OpenAI Agents SDK | Run bounded agents | python examples/openai_agents_lending.py | Single-turn, tool-free runs; complete inputs remain host-supplied. |
| Google ADK | Version accessible session context | python examples/google_adk_lending.py | Fresh sessions, explicit versioned state and quiescent mapping checks. |
| Claude Agent SDK | Bound fresh executions | python examples/claude_agents_lending.py | Mock execution differs from actual SDK/CLI and live-provider validation. |
Each default demonstration executes eligibility twice, credit once and recommendation twice; it does not execute funding. The three agent-SDK examples also run a separate late-result probe. The base quickstart demonstrates threaded late rejection; LangGraph late-node rejection is covered by its integration tests. Runtime-observed dependencies retain conservative fallback in all adapters. Do not infer completeness from graph edges, session state or callbacks. Recovery of Core records does not restore framework checkpoints.
Use reviewed runtime providers
When a bounded deterministic rule must prove which granted inputs were consumed within a reviewed local profile, use a native provider. Ordinary intercepted host reads cannot provide that guarantee. Installation/enrollment is an authority-owner trust decision; no arbitrary Python callback or manifest can establish scoped assurance.
python examples/provider_substitution.py
python examples/wasmtime_selective.py
Install the corresponding native variant and Wasmtime dependency first. The substitution example publishes eight artifacts across two independently mediated providers, each executing four times. Unread updates after admission permit reuse; consumed/control changes invalidate. Every captured input is still validated before publication. See the admission tutorial and failure rules.
Explore operations and native APIs
| Task | Executable | Requirement and outcome |
|---|---|---|
| Native contracts | cargo run --locked --example selective_plan | Rust toolchain; deterministic strategy and disposition assertions. |
| Long-running state | python examples/lifecycle_workload.py --help | Expression native feature for execution; managed identities, collection and logical state versus process RSS. |
| Process restart | python examples/durable_restart.py | Persistence wheel and qualified default/temp storage; planning blocks until reconciliation. Choose TMPDIR/SQLITE_TMPDIR before startup if needed on Linux. |
| Model comparison | python examples/llm_lending.py --help | Optional dependencies; configurable trials and usage/latency reporting. No equivalence or billing guarantee. |
Continue with 05 - Operate for capacity, acknowledgement loss, recovery and safe retry decisions.

