Spaces:
Sleeping
Sleeping
Update agent.py
Browse files19 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626335 unmodified lines9910010110210310410510610710810911011111211311411511637 unmodified lines15415515615715815916016119 unmodified lines# --------------------------------------------------------------------# 1. API Key Rotation Setup# --------------------------------------------------------------------api_keys = [os.getenv("OPENROUTER_API_KEY"),os.getenv("OPENROUTER_API_KEY_1")]if not any(api_keys):raise EnvironmentError("No OpenRouter API keys found in environment variables.")api_key_cycle = itertools.cycle([k for k in api_keys if k])def get_next_api_key():"""Get the next API key in rotation."""return next(api_key_cycle)class RotatingChatOpenAI(ChatOpenAI):"""ChatOpenAI wrapper that automatically rotates API keys on failure."""def invoke(self, *args, **kwargs):# Try each key once per callfor _ in range(len(api_keys)):self.api_key = get_next_api_key()try:return super().invoke(*args, **kwargs)except Exception as e:# Handle rate-limits or auth errorsif any(code in str(e) for code in ["429", "401", "403"]):print(f"[API Key Rotation] Key {self.api_key[:5]}... failed, trying next key...")continueraise # Re-raise other unexpected errorsraise RuntimeError("All OpenRouter API keys failed or rate-limited.")# --------------------------------------------------------------------# 2. Initialize LLM with API Key Rotation# --------------------------------------------------------------------llm = RotatingChatOpenAI(base_url="https://openrouter.ai/api/v1",api_key=get_next_api_key(), # Start with the first keymodel="qwen/qwen3-coder:free", # Model must support function callingtemperature=1)35 unmodified lines# Tool Nodedef tool_node(state: MessagesState):"""Executes tools requested by the LLM."""result = []for tool_call in state["messages"][-1].tool_calls:tool = tools_by_name[tool_call["name"]]observation = tool.invoke(tool_call["args"])result.append(ToolMessage(content=observation, tool_call_id=tool_call["id"]))return {"messages": result}# Conditional Routingdef should_continue(state: MessagesState) -> Literal["Action", END]:"""Route to tools if LLM made a tool call, else end."""last_message = state["messages"][-1]return "Action" if last_message.tool_calls else END# --------------------------------------------------------------------# 5. Build LangGraph Agent37 unmodified linesresult = gaia_agent.invoke(input_state, config)final_response = result["messages"][-1].contenttry:return final_response.split("FINAL ANSWER:")[-1].strip()except Exception:print("Could not split on 'FINAL ANSWER:'")return final_response19 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626335 unmodified lines9910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812937 unmodified lines16716816917017117217317419 unmodified lines# --------------------------------------------------------------------# 1. API Key Rotation Setup# --------------------------------------------------------------------api_keys = [k for k in [os.getenv("OPENROUTER_API_KEY"),os.getenv("OPENROUTER_API_KEY_1")] if k]if not api_keys:raise EnvironmentError("No OpenRouter API keys found in environment variables.")api_key_cycle = itertools.cycle(api_keys)def get_next_api_key() -> str:"""Get the next API key in rotation."""return next(api_key_cycle)class RotatingChatOpenAI(ChatOpenAI):"""ChatOpenAI wrapper that automatically rotates OpenRouter API keys on failure."""def invoke(self, *args, **kwargs):for _ in range(len(api_keys)): # try each key once per callcurrent_key = get_next_api_key()self.openai_api_key = current_key # ✅ Correct for ChatOpenAItry:return super().invoke(*args, **kwargs)except Exception as e:# Handle rate-limits or auth errorsif any(code in str(e) for code in ["429", "401", "403"]):print(f"[API Key Rotation] Key {current_key[:5]}... failed, trying next key...")continueraise # Re-raise unexpected errorsraise RuntimeError("All OpenRouter API keys failed or were rate-limited.")# --------------------------------------------------------------------# 2. Initialize LLM with API Key Rotation# --------------------------------------------------------------------llm = RotatingChatOpenAI(base_url="https://openrouter.ai/api/v1",openai_api_key=get_next_api_key(), # ✅ start with the first keymodel="qwen/qwen3-coder:free", # must support tool/function callingtemperature=1)35 unmodified lines# Tool Nodedef tool_node(state: MessagesState):"""Executes tools requested by the LLM."""results = []last_message = state["messages"][-1]for tool_call in getattr(last_message, "tool_calls", []) or []:tool = tools_by_name.get(tool_call["name"])if not tool:results.append(ToolMessage(content=f"Unknown tool: {tool_call['name']}", tool_call_id=tool_call["id"]))continueargs = tool_call["args"]# Handle dict vs positional args safelytry:observation = tool.invoke(**args) if isinstance(args, dict) else tool.invoke(args)except Exception as e:observation = f"[Tool Error] {str(e)}"results.append(ToolMessage(content=observation, tool_call_id=tool_call["id"]))return {"messages": results}# Conditional Routingdef should_continue(state: MessagesState) -> Literal["Action", END]:"""Route to tools if LLM made a tool call, else end."""last_message = state["messages"][-1]return "Action" if getattr(last_message, "tool_calls", None) else END# --------------------------------------------------------------------# 5. Build LangGraph Agent37 unmodified linesresult = gaia_agent.invoke(input_state, config)final_response = result["messages"][-1].content# Extract "FINAL ANSWER" if presentif isinstance(final_response, str):return final_response.split("FINAL ANSWER:")[-1].strip()else:return str(final_response)
agent.py+38-25