from fastapi import Request from openai import OpenAI from core.graph import create_agent_graph def get_llm_client(request: Request) -> OpenAI: """FastAPI dependency — returns the singleton OpenAI client from app.state.""" return request.app.state.llm_client def get_agent_graph(agent_id: str, request: Request): """ FastAPI dependency — returns the compiled LangGraph graph for *agent_id*. Graphs are lazily compiled on first use and cached on app.state so each agent's graph is only built once per process lifetime. """ cache: dict = request.app.state.agent_graphs if agent_id not in cache: from agents import get as get_agent agent = get_agent(agent_id) if agent is None: # Fall back to the naked agent if the requested one doesn't exist agent_id = "naked" agent = get_agent(agent_id) cache[agent_id] = create_agent_graph( client=request.app.state.llm_client, agent_skills=agent.skills, system_prompt=agent.build_system_prompt(), ) return cache[agent_id]