Skip to content
Pyrula
Pre-release: the packages are not on PyPI yet, so pip install does not resolve. Build from source to try it today.

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.

pyrula.agents.compat.openai.AsyncOpenAI has the openai.AsyncOpenAI shape. Swap the import (pip install "pyrula[agents]"):

# from openai import AsyncOpenAI
from 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.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.

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, agent
from pyrula.agents.compat.openai import AsyncOpenAI
client = AsyncOpenAI() # reads OPENAI_API_KEY
@agent
async def support(ctx: AgentContext, message: str) -> str:
response = await client.responses.create(model="gpt-6-luna", input=message)
return response.output_text

A 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.

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.

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 asyncio
import json
import httpx
from pyrula.agents import AgentContext, agent
from pyrula.agents.compat.openai import OpenAI
from 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) == 1

A 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.

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 instructor
from pyrula.agents.compat import OpenAI
patched = instructor.from_openai(OpenAI()) # the drop-in, wrapped by instructor
extracted = 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.

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.

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.stream and messages.parse (and the beta versions) are journaled as their create plus the SDK’s own builder.
  • Refused in a run: beta.messages.tool_runner, beta.sessions, with_raw_response, with_streaming_response, the legacy completions and server-side tools that act (mcp_servers, code_execution, unknown tool types). The error names the argument. Custom tools, web_search, web_fetch and the client-executed bash, text_editor, computer and memory tools are allowed.
  • Server-held state. A call that continues a thread= or reuses a container needs that state to still exist at Anthropic on the first live call after the replayed prefix.

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.

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, the interactions, agents and triggers APIs, server tools that act) raise UnjournaledSurface naming the argument. Embeddings, token counts and file calls pass through.
  • Tools. A Python function in config.tools is refused unless automatic_function_calling={"disable": True} is set, because the SDK would call the model again inside one generate_content. Pass function declarations and run the calls yourself in a ctx.step or @tool.
  • Server-held state. cached_content names 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.

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 boto3
from 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_model and its variants, server-run tools) raise UnjournaledSurface naming the argument. Use converse.
  • Pass through: count_tokens and apply_guardrail, so a resume sends them again. Run apply_guardrail in a ctx.step when its verdict decides what the run does.
  • Errors. A service error (throttling, validation, access denied) is journaled once and replays as a ClientError with 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).

View this page as Markdown