Drop-in LLM clients
Inside a Pyrula run, the drop-in clients below journal each model call, so a resume replays the recorded reply instead of calling the provider. Outside a run they pass through. The guarantee matrix lists each capability and the tested SDK versions.
Executing a tool the model requested is your code: wrap anything that must not run twice in ctx.step or @tool, so a crash mid-agent doesn’t fire it again.
The OpenAI drop-in
Section titled “The OpenAI drop-in”pyrula.agents.compat.openai.AsyncOpenAI has the openai.AsyncOpenAI shape. Swap the import (pip install "pyrula[agents]"):
# from openai import AsyncOpenAIfrom pyrula.agents.compat.openai import AsyncOpenAI
client = AsyncOpenAI()resp = await client.chat.completions.create(model="gpt-6-luna", messages=[...])Inside a run, chat.completions.create and responses.create are journaled and replay without calling the provider. That includes stream=True, structured output and the SDK’s parse and stream helpers. Outside a run they pass through with a one-time warning. For sync code, see Sync code and threads.
Other surfaces such as embeddings, files and models pass through. Surfaces a replay would have to call live (completions, audio, images, realtime, beta.threads, with_raw_response) raise UnjournaledSurface. A helper shares create’s journal entry, and your model’s validators run again on replay, so keep them free of side effects. The OpenAI Agents SDK runs on this client.
Chat completions and streams
Section titled “Chat completions and streams”chat.completions.create returns the SDK’s ChatCompletion, rebuilt from the journal on replay. stream=True returns one object that supports async for, async with and close(), live and on replay. It is not an openai.AsyncStream.
A streamed call is journaled, and its usage metered, when its last finish_reason chunk arrives. A stream you stop reading earlier is not journaled and runs live again. A stream the provider ends without a finish_reason chunk raises ProviderStreamTruncated.
The Responses API
Section titled “The Responses API”responses.create is journaled like chat.completions.create; with stream=True a replay yields the recorded events without calling the provider. The stream is not an openai.AsyncStream, so code that reads headers off it raises AttributeError inside a run. A stream you stop before its terminal event runs live again.
from pyrula.agents import AgentContext, agentfrom pyrula.agents.compat.openai import AsyncOpenAI
client = AsyncOpenAI() # reads OPENAI_API_KEY
@agentasync def support(ctx: AgentContext, message: str) -> str: response = await client.responses.create(model="gpt-6-luna", input=message) return response.output_textA provider error is journaled as the call’s outcome and re-raised, so a body that catches it and retries takes the same branch on replay.
These arguments raise UnjournaledSurface before anything is sent: background=True, conversation= (mutable server state; chain with previous_response_id or send the full input) and tools OpenAI’s servers run with side effects (mcp, code_interpreter, image_generation). function_call items replay with their call_ids, so wrap the tool’s side effects in ctx.step or @tool.
A call in flight when the process died has no recording, so a resume sends it again and the provider may bill it twice. The first live call after the replayed prefix carries the previous_response_id recorded earlier, so that response must still be stored at OpenAI.
Calls inside a step or tool
Section titled “Calls inside a step or tool”A drop-in call made inside a ctx.step or @tool body is metered but not journaled: the step or tool result is the durable unit, and its body runs again whole on a retry. Each call is held to the run’s caps (max_llm_calls, max_total_tokens, max_cost_usd) before it is sent and writes one llm:done right after.
Sync code and threads
Section titled “Sync code and threads”pyrula.agents.compat.openai.OpenAI (also from pyrula.agents.compat import OpenAI) is the sync twin of AsyncOpenAI, with the same surfaces. A built openai.OpenAI converts in place with journaled(client). The sync Anthropic client, pyrula.agents.compat.Anthropic, follows the same rules.
A run’s body is async, and the run’s event loop does all its journaling. A sync client therefore journals only when it is called on a thread of the run: await ctx.to_thread(fn) for one call and await ctx.map_threads(fn, items) for a fan-out. Each call gets its own replay scope, so a resume replays each one. See Blocking calls in threads.
import asyncioimport json
import httpx
from pyrula.agents import AgentContext, agentfrom pyrula.agents.compat.openai import OpenAIfrom pyrula.agents.testing.runner import AgentRunner
provider_calls = []
def provider(request: httpx.Request) -> httpx.Response: # A stand-in for the OpenAI API, so this block runs offline. provider_calls.append(json.loads(request.content)) return httpx.Response( 200, json={ "id": "chatcmpl-1", "object": "chat.completion", "created": 0, "model": "gpt-6-luna", "choices": [ { "index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "Pong."}, } ], "usage": {"prompt_tokens": 9, "completion_tokens": 2, "total_tokens": 11}, }, )
@agent(name="sync_ping")async def ping(ctx: AgentContext) -> str: client = OpenAI( api_key="unused", base_url="http://openai.test/v1", http_client=httpx.Client(transport=httpx.MockTransport(provider)), )
def ask() -> str: reply = client.chat.completions.create( model="gpt-6-luna", messages=[{"role": "user", "content": "Ping?"}] ) return reply.choices[0].message.content
return await ctx.to_thread(ask)
events = asyncio.run(AgentRunner(ping).run())assert events[-1].payload["result"] == "Pong." and len(provider_calls) == 1A sync call made directly in the async body raises UnjournaledSurface before any request is sent; use await ctx.to_thread(...) or the async twin. A thread started without the run’s context (threading.Thread, ThreadPoolExecutor) sees no run: the call logs a warning naming ctx.to_thread and runs live again on every resume.
instructor
Section titled “instructor”The journaled clients work unchanged under instructor. Each attempt, a reask included, is one journaled create, so a resume replays every attempt with no second request.
import instructorfrom pyrula.agents.compat import OpenAI
patched = instructor.from_openai(OpenAI()) # the drop-in, wrapped by instructorextracted = await ctx.to_thread( lambda: patched.chat.completions.create(model="gpt-6-luna", response_model=User, messages=[...]))Journal first, then wrap. journaled(client) after instructor.from_openai(client) leaves instructor with the SDK’s unjournaled method, so its calls run live again on every resume. The module-level client (openai.chat.completions.create) is not covered.
Azure OpenAI and Bedrock
Section titled “Azure OpenAI and Bedrock”AzureOpenAI and AsyncAzureOpenAI (and, on an openai release that has them, BedrockOpenAI and AsyncBedrockOpenAI) come from pyrula.agents.compat the same way, and journaled(client) converts one you built.
Anthropic
Section titled “Anthropic”pyrula.agents.compat.anthropic.AsyncAnthropic and the sync Anthropic (pip install "pyrula[agents]") journal messages.create and beta.messages.create, streaming or not. A stream is journaled when message_stop arrives. messages.batches.create is journaled as a write, so a replay returns the recorded object instead of creating another job. The sync client journals on a thread of the run, as described above for OpenAI.
- Helpers.
messages.streamandmessages.parse(and thebetaversions) are journaled as theircreateplus the SDK’s own builder. - Refused in a run:
beta.messages.tool_runner,beta.sessions,with_raw_response,with_streaming_response, the legacycompletionsand server-side tools that act (mcp_servers,code_execution, unknown tool types). The error names the argument. Custom tools,web_search,web_fetchand the client-executedbash,text_editor,computerandmemorytools are allowed. - Server-held state. A call that continues a
thread=or reuses acontainerneeds that state to still exist at Anthropic on the first live call after the replayed prefix.
Anthropic on Bedrock and Vertex
Section titled “Anthropic on Bedrock and Vertex”AnthropicBedrock, AsyncAnthropicBedrock, AnthropicVertex and AsyncAnthropicVertex come from pyrula.agents.compat the same way (pip install "anthropic[bedrock]" or "anthropic[vertex]"). They follow the rules above, and journaled(client) converts a client you built.
from pyrula.agents.compat import AsyncAnthropicBedrock, AsyncAnthropicVertex
bedrock = AsyncAnthropicBedrock(aws_region="us-east-1")vertex = AsyncAnthropicVertex(region="us-east5", project_id="my-project")reply = await bedrock.messages.create( model="anthropic.claude-haiku-4-5-20251001-v1:0", max_tokens=256, messages=messages)A failure raised before a request is sent (no credentials, an unsignable request) is not journaled, so a resume asks again. For instructor, journal first, then instructor.from_anthropic.
Gemini
Section titled “Gemini”pyrula.agents.compat.genai (pip install "pyrula[gemini]") replaces from google import genai:
from pyrula.agents.compat import genai
client = genai.Client(api_key="...")genai.Client is a subclass of google.genai.Client, so isinstance checks and every constructor argument are the SDK’s. models.generate_content and models.generate_content_stream are journaled on the sync client and on client.aio, and so is every chats turn. A client you built converts in place with journaled(client); read client.aio after that. The sync client journals on a thread of the run, as described above for OpenAI.
- Refused in a run: unsupported calls (image and video generation,
aio.live, theinteractions,agentsandtriggersAPIs, server tools that act) raiseUnjournaledSurfacenaming the argument. Embeddings, token counts and file calls pass through. - Tools. A Python function in
config.toolsis refused unlessautomatic_function_calling={"disable": True}is set, because the SDK would call the model again inside onegenerate_content. Pass function declarations and run the calls yourself in actx.stepor@tool. - Server-held state.
cached_contentnames and uploaded files live at Google and must still exist on the first live call after the replayed prefix.
Journal first, then instructor.from_genai.
Amazon Bedrock (boto3)
Section titled “Amazon Bedrock (boto3)”journaled(client) takes the boto3 bedrock-runtime client you already built (pip install "pyrula[bedrock]") and makes converse and converse_stream journaled, in place:
import boto3from pyrula.agents.compat import journaled
client = journaled(boto3.client("bedrock-runtime", region_name="us-east-1"))reply = await ctx.to_thread(lambda: client.converse(modelId=model_id, messages=messages))boto3 is blocking, so a call journals on a thread of the run (described above). Call journaled(client) before instructor.from_bedrock or anything else that captures client.converse.
- Refused in a run: unsupported calls (
invoke_modeland its variants, server-run tools) raiseUnjournaledSurfacenaming the argument. Useconverse. - Pass through:
count_tokensandapply_guardrail, so a resume sends them again. Runapply_guardrailin actx.stepwhen its verdict decides what the run does. - Errors. A service error (throttling, validation, access denied) is journaled once and replays as a
ClientErrorwith the recorded code. Failures botocore raises before the request goes out are not journaled.
The drop-ins and durable_chat_model count toward max_llm_calls, max_total_tokens and max_cost_usd (Spend caps).