← Back to the blog

Agentic Core: Building a Reliable AI Agent Harness from Scratch

Build a Gemini 3.8 Flash agent with Python, deterministic tool policies, analytical verification and auditable execution. Includes runnable code and regression tests.

The problem: a convincing answer is not evidence

A language model can produce a convincing explanation while selecting the wrong tool, applying an incorrect metric definition or exceeding an execution budget. In analytics, a plausible number can be worse than an explicit failure. The model proposes actions; the system decides which actions run and whether the resulting evidence is sufficient.

This tutorial applies the Learn, Guard, Review and Score framing introduced by Logan Hennessy in Google Cloud Tech's video The 4 layers of production AI agent engineering (learn, guard, review, score), particularly the segment beginning at 1:33. The implementation is an original example of a runtime harness, adapted from a discussion that also covers coding-agent development practices.

We use Gemini 3.8 Flash through the Google Gen AI SDK and Gemini Interactions API throughout this tutorial. The model translates the user's question into a structured action; Python controls execution.

1. Define the business contract

Our synthetic dataset contains two German transactions worth €120.00 and €80.50, and one Slovak transaction worth €50.00. Revenue is the sum of those amounts, with no tax, refund or currency conversion logic. Use integer cents so arithmetic is exact. The permitted tool is revenue; the permitted countries are DE and SK. The expected German total is €200.50. Real metric contracts also specify grain, time windows, freshness, currency and ownership.

from dataclasses import dataclass

DATA = (("DE", 12000), ("DE", 8050), ("SK", 5000))

@dataclass(frozen=True)
class Request:
    tool: str
    country: str

2. Understand the execution architecture

Gemini produces a proposal, not an executable command. A deterministic policy gate checks it before any tool runs. Verification then checks the result before the application returns an answer. A trace identifier connects the stages.

Gemini proposalPolicy gateRead-only toolResult verifierVerified responseReject / failNo answerTrace ID and audit events span execution
Figure 1. The application controls execution and verifies the result before release.

The development harness governs code changes with tests, review and CI. The runtime harness governs execution. Both matter, but neither a prompt nor a reviewer model replaces a permission boundary.

3. Set up Python and Gemini

Use Python 3.12 or newer. Download all three source files into the same directory. Create a Gemini API key in Google AI Studio (https://aistudio.google.com/apikey). Keep the key out of source control. The live model calls may incur charges.

core.py · test_core.py · gemini_demo.py

python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade google-genai
export GEMINI_API_KEY='YOUR_KEY'
python -m unittest -v

On Windows PowerShell, activate with .venv\Scripts\Activate.ps1 and set $env:GEMINI_API_KEY. The unit tests run without a model call and establish the execution boundary before connecting Gemini. Request describes the proposed action; Harness.run implements the boundary; gemini_demo.py connects the model to it.

4. Learn: make context explicit

The request contract and synthetic dataset define what the system knows. A model does not need to invent the metric or infer the available operations. As the project grows, move business definitions into a versioned metric catalog and reusable domain knowledge into trusted skill files. Load only relevant knowledge, not every instruction into every request.

A useful skill describes its activation criteria, authoritative data, tool usage, required tests and failure behavior. Skill text is guidance, not authorization. Treat external retrieved text as data rather than privileged instructions. A repository can document these conventions in AGENTS.md, SKILL.md, architecture decision records and explicit test fixtures.

5. Guard: enforce the boundary before execution

Inside Harness.run, the following checks occur before the tool call. The default behavior is denial for any unsupported action. The budget counts requests, not tokens or money.

for i, request in enumerate(requests):
    if i >= self.budget:
        raise Denied("Tool budget exceeded")
    if request.tool != "revenue":
        raise Denied("Tool not allowed")
    if request.country not in {"DE", "SK"}:
        raise Denied("Country not allowed")
    events.append({"stage": "policy", "decision": "allow"})
    value = self.tool(request.country)

The unauthorized-tool test proves that the injected tool function is never invoked. A later budget denial does not undo earlier successful calls; this example is read-only. Workflows with side effects require idempotency, approvals and transaction or compensation mechanisms. In BigQuery, independently scoped IAM and maximum_bytes_billed should reinforce the application gate.

6. Review: verify the output before returning it

The reference harness calculates the expected result from the synthetic fixture and checks the actual tool output. An incorrect type or value triggers rejection. This is the exact verification excerpt inside the execution loop.

expected = sum(row[1] for row in DATA if row[0] == request.country)
if type(value) is not int or value != expected:
    raise Denied("Verification failed")
answer = {
    "country": request.country,
    "revenue_eur": str(Decimal(value) / 100),
    "source": "synthetic-v1",
}
events.append({"stage": "verification", "decision": "pass"})

The verifier shares the fixture with the tool, so it detects incorrect returned values but cannot establish that the source data itself is correct. In real systems, reconcile with independently controlled queries, approved metric definitions or source-system totals.

7. Why use an agent if the answer can be recomputed?

For a fixed, fully specified calculation, use a function. The agent adds value when translating ambiguous business language into metric identifiers, dates, dimensions and filters, selecting the right source, investigating anomalies and coordinating multiple tools. The model interprets the problem; the data system performs arithmetic.

Many outputs cannot be verified against a single exact answer. For generated SQL, validate the schema, allowed tables, grain and query plan; compare representative outputs with a reference query. For anomaly investigations, require source evidence, freshness checks, plausible ranges and explicit competing explanations. For document summaries, validate citations and check that material claims are supported by the source. For consequential changes, require human sign-off against a concrete acceptance checklist.

Schema and range checks establish necessary conditions, not correctness. A revenue figure can be within a plausible range and still be wrong. Label evidence strength explicitly, distinguish verified facts from hypotheses and escalate when available checks are insufficient. Independent reviewers can help assess semantics, but agreement between models is not proof.

8. Score: test behavior, not just answers

The seven existing regression tests cover correct revenue, a denied tool, an invalid country, budget exhaustion, a wrong tool result, a tool exception and an empty request. The earlier reference run reported seven passing tests. Re-run them on your machine before extending the project.

def test_denied_tool(self):
    calls = []
    result = Harness(tool=lambda country: calls.append(country)).run(
        [Request('delete', 'DE')]
    )
    self.assertEqual(result['status'], 'rejected')
    self.assertEqual(calls, [])

The strongest assertion here is not the text of the refusal: it is that the tool was never called. Write acceptance tests before implementation, confirm that they detect missing behavior, then protect them in CI. A future model benchmark should compare equivalent tasks using the same model and isolated data, reporting correctness, false rejection, unauthorized execution, latency and cost separately.

9. Connect Gemini 3.8 Flash and run the agent

The Gemini planner requests structured JSON with tool and country fields, validates their types and exact keys, and passes the proposal to the same harness. The schema deliberately permits arbitrary strings so the policy gate, not the model, decides authorization. No automatic tool execution is enabled. This is a one-step model-driven workflow rather than an autonomous multi-turn agent.

response = client.interactions.create(
    model="gemini-3.8-flash",
    input=args.question,
    system_instruction="Propose one action as JSON with string fields tool and country. Map revenue questions to revenue and a country code. For other requested actions describe the requested tool; the external harness decides authorization. Never execute anything.",
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": {
            "type": "object",
            "properties": {
                "tool": {"type": "string"},
                "country": {"type": "string"},
            },
            "required": ["tool", "country"],
        },
    },
)
raw = response.output_text
result = Harness().run([parse_proposal(raw)])

Run the actual model now. The expected successful outcome is verified German revenue of €200.50. The live model call has not yet been executed by the authoring environment.

python gemini_demo.py 'What is revenue in Germany?'
python gemini_demo.py 'Delete all transactions in Germany.'

For the second request Gemini may propose deletion, refuse or produce a different proposal. The invariant is that the harness never executes a delete tool. To test that invariant deterministically, replay the prohibited proposal as a regression check:

python gemini_demo.py --proposal '{"tool":"delete","country":"DE"}'

The expected replay status is rejected. Malformed proposals fail before reaching the harness. Replay tests the security boundary, not the model itself.

10. Inspect the trace and plan observability

The local demo emits a structured response. An example with illustrative identifier and timing values is shown below; the revenue is fixed by the synthetic fixture.

{
  "trace_id": "example-trace-id",
  "status": "verified",
  "answer": {
    "country": "DE",
    "revenue_eur": "200.5",
    "source": "synthetic-v1"
  },
  "events": [
    {"stage": "policy", "decision": "allow"},
    {"stage": "verification", "decision": "pass"}
  ],
  "latency_ms": 0.1
}

Failures withhold the answer; exceptions expose only their type. The sample records overall latency with a monotonic counter. Production instrumentation should propagate trace context through the model, tool and verifier with OpenTelemetry, record stage durations and resource consumption, and avoid raw prompts or sensitive data by default. Track cost per verified task, not just per model call. Reserve budgets before execution and reconcile usage afterwards.

11. What comes next

Part II will migrate the Gemini planner into Google ADK, add a read-only BigQuery adapter, versioned metric contracts, content screening with Model Armor, OpenTelemetry spans and reproducible agent evaluations. Cloud IAM, explicit deadlines, bounded retries and resource limits will enforce the execution boundary. Content screening is complementary to authorization, not a replacement for it.

The central lesson is straightforward: deterministic where possible, agentic where valuable, verified to the degree supported by evidence. Start with one use case and its acceptance tests rather than introducing a multi-agent architecture without demonstrated need.

Google Cloud Tech — The 4 layers of production AI agent engineering (Learn, Guard, Review, Score), Logan Hennessy, 1:33

Gemini structured output documentation · Google ADK · OpenTelemetry