Patterns for using OpenAI-compatible SDKs reliably inside agent loops.
An agent loop calls the model repeatedly — planning, acting, observing — so small inefficiencies compound fast. These patterns keep your loops predictable and cheap when running against the OpenDunes API.
Instantiate the SDK client once and reuse it for every call in the loop. Creating a new client per iteration adds TLS handshake overhead and makes it harder to share retry state.
Streaming keeps each turn responsive even when a step produces a long answer. The final chunk includes usage so you can track token spend per turn.
The X-Balance-Available response header carries your remaining balance in micro-DA after each call. Check it and halt the loop before you run dry — a 402 insufficient_credits mid-loop is harder to recover from than a graceful stop.
See Response Headers for the full header reference.
429 with backoff#The default rate limit is 60 requests per minute per key. Agent loops can saturate that quickly if steps are fast. Respect the Retry-After header rather than spinning.
Rewrite the system message only when the agent's role changes. Keeping it constant across turns improves model consistency and makes logs easier to read in your dashboard.
X-Request-Id#Each response includes an X-Request-Id header (UUID v7). Store it alongside the turn index so you can correlate agent traces to specific API calls when debugging.