Skip to main content

AsyncClient / SyncClient

BAML generates both sync and async clients with the same public API.

Basic Usage​

Async Client​

from baml_client.async_client import b

async def example():
story = await b.TellMeAStory()
poem = await b.WriteAPoemAbout("Roses")

Sync Client​

from baml_client.sync_client import b

def example():
story = b.TellMeAStory()
poem = b.WriteAPoemAbout("Roses")

Call Patterns​

.stream​

Stream responses from a function:

from baml_client.async_client import b

async def example():
stream = b.stream.TellMeAStory()

async for partial in stream:
print(partial)

print(await stream.get_final_response())

.request​

info

Added in version 0.79.0

Get the raw HTTP request without sending it:

from baml_client.async_client import b

async def example():
request = await b.request.TellMeAStory()
print(request.url)
print(request.headers)
print(request.body.json())

.stream_request​

info

Added in version 0.79.0

Same as .request but sets streaming options to true:

from baml_client.async_client import b

async def example():
request = await b.stream_request.TellMeAStory()
print(request.url)
print(request.headers)
print(request.body.json())

.parse​

info

Added in version 0.79.0

Parse LLM responses. Use with .request for custom HTTP handling:

import requests
from baml_client.sync_client import b

def example():
request = b.request.TellMeAStory()
response = requests.post(
request.url,
headers=request.headers,
json=request.body.json()
)
parsed = b.parse.TellMeAStory(
response.json()["choices"][0]["message"]["content"]
)
print(parsed)

.parse_stream​

info

Added in version 0.79.0

Parse streaming responses. Use with .stream_request:

from openai import AsyncOpenAI
from baml_client.async_client import b

async def example():
client = AsyncOpenAI()

request = await b.stream_request.TellMeAStory()
stream = await client.chat.completions.create(**request.body.json())

llm_response: list[str] = []
async for chunk in stream:
if len(chunk.choices) > 0 and chunk.choices[0].delta.content is not None:
llm_response.append(chunk.choices[0].delta.content)
print(b.parse_stream.TellMeAStory("".join(llm_response)))

See Also​