Call pollinations.ai API with retry logic and exponential backoff Args: system_prompt: System prompt for the AI user_prompt: User prompt for the AI token: pollinations.ai API token temperature: Temperature for generation (default 0.7) Returns: Respon
(
system_prompt: str,
user_prompt: str,
token: str,
temperature: float = 0.7,
)
| 282 | |
| 283 | |
| 284 | def call_pollinations_api( |
| 285 | system_prompt: str, |
| 286 | user_prompt: str, |
| 287 | token: str, |
| 288 | temperature: float = 0.7, |
| 289 | ) -> Optional[str]: |
| 290 | """Call pollinations.ai API with retry logic and exponential backoff |
| 291 | |
| 292 | Args: |
| 293 | system_prompt: System prompt for the AI |
| 294 | user_prompt: User prompt for the AI |
| 295 | token: pollinations.ai API token |
| 296 | temperature: Temperature for generation (default 0.7) |
| 297 | |
| 298 | Returns: |
| 299 | Response content or None if failed |
| 300 | """ |
| 301 | headers = { |
| 302 | "Authorization": f"Bearer {token}", |
| 303 | "Content-Type": "application/json" |
| 304 | } |
| 305 | |
| 306 | last_error = None |
| 307 | |
| 308 | for attempt in range(MAX_RETRIES): |
| 309 | seed = random.randint(0, MAX_SEED) |
| 310 | |
| 311 | payload = { |
| 312 | "model": MODEL, |
| 313 | "messages": [ |
| 314 | {"role": "system", "content": system_prompt}, |
| 315 | {"role": "user", "content": user_prompt} |
| 316 | ], |
| 317 | "temperature": temperature, |
| 318 | "seed": seed |
| 319 | } |
| 320 | |
| 321 | if attempt > 0: |
| 322 | backoff_delay = INITIAL_RETRY_DELAY * (2 ** attempt) |
| 323 | print(f" Retry {attempt}/{MAX_RETRIES - 1} with new seed: {seed} (waiting {backoff_delay}s)") |
| 324 | time.sleep(backoff_delay) |
| 325 | |
| 326 | try: |
| 327 | response = requests.post( |
| 328 | POLLINATIONS_API_BASE, |
| 329 | headers=headers, |
| 330 | json=payload, |
| 331 | timeout=120 |
| 332 | ) |
| 333 | |
| 334 | if response.status_code == 200: |
| 335 | try: |
| 336 | result = response.json() |
| 337 | content = result['choices'][0]['message']['content'] |
| 338 | return content |
| 339 | except (KeyError, IndexError, json.JSONDecodeError) as e: |
| 340 | last_error = f"Error parsing API response: {e}" |
| 341 | error_preview = response.text[:500] + "..." if len(response.text) > 500 else response.text |
no test coverage detected