Skip to content

Trace-native CI/CD for AI agents — production failures become regression tests that block the PR. Auto-detect, cluster, freeze into hermetic cases, replay in CI for $0.

4.9 KB
Raw Blame
"""Google Gemini — automatic tracing of a two-agent conversation (PRD 12).

A Support Agent answers order/inventory questions with Gemini's function calling, then hands the
pricing turn to a Billing Agent. `tracely.init()` activates the Gemini instrumentor, so each
`generate_content` call is captured automatically as a GENERATION span — **no span code on the LLM
calls**. We disable the SDK's *automatic* function calling and dispatch the tools ourselves — the
tool fns are decorated with `@observe(as_type="tool")`, so each tool round-trip is a TOOL span; each
agent is an ordinary `@observe(as_type="agent")` function.

    pip install "tracely-sdk[google]" google-genai
    export GEMINI_API_KEY=...        # or GOOGLE_API_KEY
    TRACELY_API=http://localhost:8000 uv run python sdk/examples/auto_gemini.py
"""

from __future__ import annotations

import os

import tracely_sdk as tracely
from _fake_db import (
    AGENTS,
    BILLING_SYSTEM,
    BILLING_TOOLS,
    SUPPORT_TOOLS,
    SYSTEM,
    TURNS,
    Conversation,
    check_inventory,
    compare_prices,
    get_order_status,
    observed_tools,
)

from pathlib import Path

from dotenv import load_dotenv

_PROJECT_ROOT = Path(__file__).resolve().parents[2]
load_dotenv(_PROJECT_ROOT / ".env", override=True)  # provider keys from the repo-root .env

_RAW_FNS = {
    "get_order_status": get_order_status,
    "check_inventory": check_inventory,
    "compare_prices": compare_prices,
}

API = os.environ.get("TRACELY_API", "http://localhost:8000")
KEY = os.environ.get("TRACELY_KEY", "tracely_dev_key")

# "gemini" is an alias for the canonical "google" provider.
tracely.init(
    endpoint=API, api_key=KEY, service_name="support-agent", env="prod", instrument=["gemini"]
)


def main() -> None:
    if "google" not in tracely._instrumented:
        print('Gemini instrumentation not active — pip install "tracely-sdk[google]" google-genai')
        return
    if not (os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")):
        print("Set GEMINI_API_KEY (or GOOGLE_API_KEY) to make a real call.")
        return

    from google import genai
    from google.genai import types

    client = genai.Client()
    tools = observed_tools()  # your tool fns, decorated once with @observe(as_type="tool")

    def run(question: str, system: str, tool_names: list[str]) -> str:
        """A normal Gemini function-calling loop. Each agent below is this loop with its own tools."""
        config = types.GenerateContentConfig(
            system_instruction=system,
            tools=[_RAW_FNS[n] for n in tool_names],  # the SDK builds tool schemas from the fns
            # disable the SDK's auto-calling so WE dispatch the tools — each becomes a TOOL span
            automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True),
        )
        # Thread the conversation: prior turns (assistant → Gemini's "model" role) + this question.
        contents: list = [
            types.Content(role="model" if m["role"] == "assistant" else "user", parts=[types.Part(text=m["content"])])
            for m in history.prior()
        ]
        contents.append(types.Content(role="user", parts=[types.Part(text=question)]))
        for _ in range(5):
            resp = client.models.generate_content(
                model="gemini-3.1-flash-lite", contents=contents, config=config
            )
            calls = resp.function_calls or []
            if not calls:
                return resp.text or ""
            contents.append(resp.candidates[0].content)  # the model's function-call turn
            parts = []
            for fc in calls:  # dispatch as usual — the decorator makes each a TOOL span
                result = tools[fc.name](**dict(fc.args))
                parts.append(types.Part.from_function_response(name=fc.name, response={"result": result}))
            contents.append(types.Content(role="user", parts=parts))
        return "(loop limit hit)"

    @tracely.observe(as_type="agent")
    def support_agent(question: str) -> str:
        return run(question, SYSTEM, SUPPORT_TOOLS)

    @tracely.observe(as_type="agent")
    def billing_agent(question: str) -> str:
        return run(question, BILLING_SYSTEM, BILLING_TOOLS)

    handlers = {"support-agent": support_agent, "billing-agent": billing_agent}
    conv = os.path.basename(__file__)
    history = Conversation()  # carries prior turns forward so each turn sees the conversation
    for i, (question, slug) in enumerate(TURNS):
        with tracely.trace(
            agent=slug, conversation=conv, turn=i, user="[email protected]", example=conv,
            agents=AGENTS if i == 0 else None,
        ):
            answer = handlers[slug](question)
            history.record(question, answer)
            print(f"[{slug}] turn {i}:", answer)

    tracely.flush()
    print("sent — a multi-turn, two-agent conversation → generations + tool spans, no span code.")


if __name__ == "__main__":
    main()