Skip to main content

Async client

Imagine a cook who puts a pot on the stove and, while it heats, chops vegetables, instead of staring at the pot. Async works like that. While your program waits for one AI answer, it can send more requests.

AsyncNuRouteClient is the async version of NuRouteClient. It uses httpx's async transport and has the same groups of methods (auth, chat, providers, routing, projects, and so on). The difference: the methods are async def, so you call them with await.

Use it when you want to send many requests at once, or when your app is already async (like FastAPI). Otherwise the simpler sync client is fine.

Setup​

from nuroute import AsyncNuRouteClient

client = AsyncNuRouteClient(
api_key="aicp-...",
base_url="https://your-gateway",
timeout=30.0,
)

An async with block closes the client neatly when you are done:

async with AsyncNuRouteClient(
api_key="aicp-...",
base_url="https://your-gateway",
) as client:
response = await client.chat.complete(
model="auto",
messages=[{"role": "user", "content": "Hello!"}],
)

Routing​

chat.complete() and chat.stream() take the same keywords as the sync client's.

  • Artemis decides every model="auto" request. The router= option is optional, and its only values, "artemis" and "v2", change nothing.
  • Whether the fallback router decided a request instead, and why, is on the request log: see Which router decided.

Example: many requests at once​

This sends three questions at the same time and waits for all the answers together:

import asyncio
from nuroute import AsyncNuRouteClient

async def main():
async with AsyncNuRouteClient(api_key="aicp-...", base_url="https://your-gateway") as client:
prompts = [
"Summarise the French Revolution in one sentence.",
"What is the boiling point of water in Kelvin?",
"Name three uses of transformer models.",
]

tasks = [
client.chat.complete(
model="auto",
messages=[{"role": "user", "content": p}],
)
for p in prompts
]

responses = await asyncio.gather(*tasks)

for prompt, response in zip(prompts, responses):
print(f"Q: {prompt}")
print(f"A: {response['choices'][0]['message']['content']}\n")

asyncio.run(main())

FastAPI integration​

FastAPI is a popular Python tool for building web services. This example creates one client when the app starts, shares it across requests, and closes it when the app stops:

from contextlib import asynccontextmanager
from fastapi import FastAPI
from nuroute import AsyncNuRouteClient

client: AsyncNuRouteClient

@asynccontextmanager
async def lifespan(app: FastAPI):
global client
client = AsyncNuRouteClient(api_key="aicp-...", base_url="https://your-gateway")
yield
await client.aclose()

app = FastAPI(lifespan=lifespan)

@app.post("/ask")
async def ask(question: str):
response = await client.chat.complete(
model="auto",
messages=[{"role": "user", "content": question}],
)
return {"answer": response["choices"][0]["message"]["content"]}

Sync or async? The differences​

NuRouteClient (sync)AsyncNuRouteClient (async)
Methodsdefasync def
Transporthttpx.Clienthttpx.AsyncClient
chat.stream()Iterator[str]AsyncIterator[str]
Context managerwithasync with
close()syncawait client.aclose()