Spaces:
Runtime error
Runtime error
File size: 2,485 Bytes
1ffd0a4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | """
Gemini ↔ OpenAI Agents SDK bridge.
Why this exists
---------------
CIRO standardizes on the OpenAI Agents SDK for orchestration (tracing, tool
calls, handoffs) but uses Google Gemini as the underlying LLM. Gemini exposes
an OpenAI-compatible REST surface at
`https://generativelanguage.googleapis.com/v1beta/openai/`, so we plug it in
as a custom `AsyncOpenAI` client wrapped by `OpenAIChatCompletionsModel`.
Every agent in the project imports `get_gemini_model()` from here. That keeps
model selection, base_url, and API-key wiring in one place — swap the model
ID once and every agent inherits the change.
"""
from functools import lru_cache
from agents import OpenAIChatCompletionsModel
from openai import AsyncOpenAI
from backend.core.config import settings
# Gemini's OpenAI-compatible endpoint. Documented at:
# https://ai.google.dev/gemini-api/docs/openai
GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
# Default model for every CIRO agent. `gemini-2.5-flash` is the cheap/fast tier
# and is sufficient for the hackathon's reasoning workloads. Phase-specific
# agents can override by passing `model=` to `get_gemini_model()`.
# (Note: `gemini-2.0-flash` was the original choice but is no longer issued to
# new API keys — use 2.5-flash going forward.)
DEFAULT_GEMINI_MODEL = "gemini-2.5-flash"
@lru_cache(maxsize=1)
def _gemini_client() -> AsyncOpenAI:
"""Singleton AsyncOpenAI client pointed at Gemini.
Cached so we reuse a single underlying httpx connection pool across every
agent invocation in the process.
"""
if not settings.gemini_api_key:
raise RuntimeError(
"GEMINI_API_KEY is not set. Add it to backend/.env before running "
"any agent — see backend/.env.example."
)
return AsyncOpenAI(
base_url=GEMINI_BASE_URL,
api_key=settings.gemini_api_key,
)
def get_gemini_model(model: str = DEFAULT_GEMINI_MODEL) -> OpenAIChatCompletionsModel:
"""Return an SDK-ready model object backed by Gemini.
Args:
model: Gemini model ID (defaults to `gemini-2.0-flash`). Use a stronger
model like `gemini-2.0-pro` for higher-stakes reasoning stages
(planning, analysis) if quality demands it.
Returns:
An `OpenAIChatCompletionsModel` instance ready to pass to `Agent(model=...)`.
"""
return OpenAIChatCompletionsModel(
model=model,
openai_client=_gemini_client(),
)
|