Skip to content

Fix: sync Anthropic client blocked event loop causing polling timeouts #1

@realaaa

Description

@realaaa

Problem

The summarizer was using the synchronous anthropic.Anthropic client inside an async handler. When messages.create() was called, it blocked the entire asyncio event loop for the duration of the API call (~80-90 seconds), preventing aiogram from polling Telegram for updates.

This caused:

  1. TelegramNetworkError: HTTP Client says - Request timeout error — aiogram's long-polling connection timed out while the event loop was blocked
  2. Failed to parse Claude response as JSON — the max_tokens=4096 limit was too low for 56 messages, causing Claude's response to be truncated mid-JSON

Symptoms

[ERROR] bot.summarizer: Failed to parse Claude response as JSON: { "topics": [ ...truncated...
[ERROR] aiogram.dispatcher: Failed to fetch updates - TelegramNetworkError: HTTP Client says - Request timeout error
[INFO] aiogram.event: Update id=454771996 is handled. Duration 92243 ms

Fix (commit 18e0207)

  1. Switched from anthropic.Anthropic (sync) to anthropic.AsyncAnthropic so the API call yields to the event loop
  2. Increased max_tokens from 4096 to 8192 to prevent response truncation
  3. Added a warning log when stop_reason != "end_turn" to detect future truncation issues

Lesson

Always use async SDK clients (AsyncAnthropic, AsyncOpenAI, etc.) inside async frameworks like aiogram to avoid blocking the event loop.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions