CiscsoPonce commited on
Commit
48954f1
·
1 Parent(s): e5dcf96

fix(debate): exponential backoffs for 429 rate limits

Browse files

The debate nodes were instantly retrying fallback models upon getting
a 429 on the primary model, effectively flooding OpenRouter and tripping
global rate limits.

- Implemented _resilient_llm_call with 15s->30s->45s exponential backoff
- Increased LangGraph judge node _debate_retry to start at 15.0s

Files changed (1) hide show
  1. src/agents/debate.py +38 -21
src/agents/debate.py CHANGED
@@ -51,8 +51,6 @@ class DebateState(TypedDict, total=False):
51
 
52
  def _make_llm(model: str, max_tokens: int = 2048):
53
  from langchain_openai import ChatOpenAI
54
- import time as _time
55
- _time.sleep(_DEBATE_DELAY) # respect free-tier rate limits
56
 
57
  return ChatOpenAI(
58
  model=model,
@@ -64,6 +62,41 @@ def _make_llm(model: str, max_tokens: int = 2048):
64
  )
65
 
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  # ---------------------------------------------------------------------------
68
  # Node 1 — The Pitcher (bullish thesis)
69
  # ---------------------------------------------------------------------------
@@ -98,15 +131,7 @@ def pitcher_node(state: DebateState) -> dict:
98
  "Be specific and data-driven. Only cite facts present in the data above."
99
  )
100
 
101
- llm = _make_llm(PITCHER_MODEL)
102
- try:
103
- response = llm.invoke(prompt)
104
- bull_case = response.content
105
- except Exception as exc:
106
- logger.warning("Pitcher (%s) failed: %s — trying fallback", PITCHER_MODEL, exc)
107
- fallback = _make_llm(MODEL_CHAIN[0])
108
- response = fallback.invoke(prompt)
109
- bull_case = response.content
110
 
111
  logger.info("Pitcher delivered bull case for %s (%d chars)", ticker, len(bull_case))
112
  return {"bull_case": bull_case}
@@ -149,15 +174,7 @@ def skeptic_node(state: DebateState) -> dict:
149
  "Be thorough but concise."
150
  )
151
 
152
- llm = _make_llm(SKEPTIC_MODEL)
153
- try:
154
- response = llm.invoke(prompt)
155
- bear_case = response.content
156
- except Exception as exc:
157
- logger.warning("Skeptic (%s) failed: %s — trying fallback", SKEPTIC_MODEL, exc)
158
- fallback = _make_llm(MODEL_CHAIN[0])
159
- response = fallback.invoke(prompt)
160
- bear_case = response.content
161
 
162
  logger.info("Skeptic delivered bear case for %s (%d chars)", ticker, len(bear_case))
163
  return {"bear_case": bear_case}
@@ -225,7 +242,7 @@ def judge_node(state: DebateState) -> dict:
225
  # Compile the debate subgraph
226
  # ---------------------------------------------------------------------------
227
 
228
- _debate_retry = RetryPolicy(max_attempts=3, initial_interval=2.0)
229
 
230
  _debate_graph = StateGraph(DebateState)
231
  _debate_graph.add_node("pitcher", pitcher_node, retry=_debate_retry)
 
51
 
52
  def _make_llm(model: str, max_tokens: int = 2048):
53
  from langchain_openai import ChatOpenAI
 
 
54
 
55
  return ChatOpenAI(
56
  model=model,
 
62
  )
63
 
64
 
65
+ def _resilient_llm_call(model: str, prompt: str, fallback_model: str) -> str:
66
+ import time
67
+ time.sleep(_DEBATE_DELAY) # Initial spacing
68
+
69
+ llm = _make_llm(model)
70
+ # Try primary model with backoff
71
+ for attempt in range(4):
72
+ try:
73
+ return llm.invoke(prompt).content
74
+ except Exception as exc:
75
+ if "429" in str(exc):
76
+ sleep_time = 15 * (attempt + 1)
77
+ logger.warning("Rate limit on %s (attempt %d). Sleeping %ds...", model, attempt + 1, sleep_time)
78
+ time.sleep(sleep_time)
79
+ elif "404" in str(exc) or "too short" in str(exc):
80
+ break # Fatal error, move to fallback
81
+ else:
82
+ logger.warning("Error on %s: %s", model, exc)
83
+ time.sleep(5)
84
+
85
+ # Fallback model
86
+ logger.warning("Primary model %s exhausted, switching to fallback %s", model, fallback_model)
87
+ fallback = _make_llm(fallback_model)
88
+ for attempt in range(3):
89
+ try:
90
+ return fallback.invoke(prompt).content
91
+ except Exception as exc:
92
+ if "429" in str(exc):
93
+ time.sleep(20)
94
+ else:
95
+ time.sleep(5)
96
+
97
+ raise RuntimeError(f"Both {model} and {fallback_model} failed due to rate limits.")
98
+
99
+
100
  # ---------------------------------------------------------------------------
101
  # Node 1 — The Pitcher (bullish thesis)
102
  # ---------------------------------------------------------------------------
 
131
  "Be specific and data-driven. Only cite facts present in the data above."
132
  )
133
 
134
+ bull_case = _resilient_llm_call(PITCHER_MODEL, prompt, MODEL_CHAIN[0])
 
 
 
 
 
 
 
 
135
 
136
  logger.info("Pitcher delivered bull case for %s (%d chars)", ticker, len(bull_case))
137
  return {"bull_case": bull_case}
 
174
  "Be thorough but concise."
175
  )
176
 
177
+ bear_case = _resilient_llm_call(SKEPTIC_MODEL, prompt, MODEL_CHAIN[0])
 
 
 
 
 
 
 
 
178
 
179
  logger.info("Skeptic delivered bear case for %s (%d chars)", ticker, len(bear_case))
180
  return {"bear_case": bear_case}
 
242
  # Compile the debate subgraph
243
  # ---------------------------------------------------------------------------
244
 
245
+ _debate_retry = RetryPolicy(max_attempts=4, initial_interval=15.0, backoff_factor=1.5)
246
 
247
  _debate_graph = StateGraph(DebateState)
248
  _debate_graph.add_node("pitcher", pitcher_node, retry=_debate_retry)