Skip to content

SDK Examples Python

Marcello Marchetti edited this page Jun 4, 2026 · 2 revisions

Python SDK — Examples

Package: hevolus-xrcopilotlab (Python 3.10+) · See SDK-Overview for installation and configuration.

The Python SDK is async-only: every method is async def and XRCopilotLabClient is an async context manager built on httpx. Operations are grouped under five service objects: client.topics, client.profiles, client.agents, client.orchestrators, client.common. Construct models with snake_case keyword arguments; they serialise to the camelCase wire shape automatically.

1. Client setup

Open the client inside an async with block so its connection pool is closed cleanly on exit. The API version defaults to the current production version.

import asyncio
from xrcopilotlab import XRCopilotLabClient


async def main() -> None:
    async with XRCopilotLabClient(api_key="<YOUR_API_KEY>") as client:
        topics = await client.topics.get_topics(company_id="company-id")
        for t in topics:
            print(t.topic_id, t.topic_name)


asyncio.run(main())

2. Chat with an agent

client.agents.chat sends the prompt and awaits the assistant's AssistantResponse (which may take several seconds for deep-reasoning agents). Reuse response.conversation_id to continue the same conversation.

import asyncio
from xrcopilotlab import XRCopilotLabClient
from xrcopilotlab.models import UserPrompt


async def main() -> None:
    async with XRCopilotLabClient(api_key="<YOUR_API_KEY>") as client:
        prompt = UserPrompt(
            company_id="company-id",
            topic_id="topic-id",
            agent_id="agent-id",
            endpoint_id="endpoint-id",
            message="Hello, how can you help me?",
        )
        response = await client.agents.chat(prompt)
        print(response.message)

        # Continue the conversation by reusing the returned conversation_id.
        follow_up = UserPrompt(
            company_id="company-id",
            topic_id="topic-id",
            agent_id="agent-id",
            endpoint_id="endpoint-id",
            message="Tell me more.",
            conversation_id=response.conversation_id,
        )
        second = await client.agents.chat(follow_up)
        print(second.message)


asyncio.run(main())

Async variant (fire-and-forget + history polling)

client.agents.start_chat submits the prompt and returns immediately (HTTP 202 Accepted) with a ChatAsyncResponse polling handle. Poll get_conversation_history until an assistant message appears.

import asyncio
from xrcopilotlab import XRCopilotLabClient
from xrcopilotlab.models import UserPrompt


async def main() -> None:
    async with XRCopilotLabClient(api_key="<YOUR_API_KEY>") as client:
        prompt = UserPrompt(
            company_id="company-id",
            topic_id="topic-id",
            agent_id="agent-id",
            endpoint_id="endpoint-id",
            message="Analyze this data in detail.",
        )
        accepted = await client.agents.start_chat(prompt)

        history = None
        while not history or not any(m.role == "assistant" for m in history.messages):
            await asyncio.sleep(2)
            history = await client.agents.get_conversation_history(
                company_id=accepted.company_id,
                topic_id=accepted.topic_id,
                agent_id=accepted.agent_id,
                conversation_id=accepted.conversation_id,
                messages=2,
            )

        print("Agent replied:", history.messages[-1].content)


asyncio.run(main())

3. Upload a file to a topic and check indexing status

client.topics.upload_file accepts a filesystem path, raw bytes, or a binary file-like object, plus the topic identifiers, target file name, and a FileScope (PROFILE or AGENT). Indexing runs server-side after upload — fetch the owning profile, then poll client.profiles.get_indexing_status, which takes the Profile object.

import asyncio
from xrcopilotlab import XRCopilotLabClient
from xrcopilotlab.enums import FileScope


async def main() -> None:
    async with XRCopilotLabClient(api_key="<YOUR_API_KEY>") as client:
        with open("document.pdf", "rb") as f:
            await client.topics.upload_file(
                f,
                company_id="company-id",
                topic_id="topic-id",
                file_name="document.pdf",
                scope=FileScope.PROFILE,   # PROFILE = 0, AGENT = 1
            )
        print("Upload accepted.")

        # get_indexing_status takes the Profile object, not raw ids.
        profile = await client.profiles.get_profile(
            company_id="company-id",
            topic_id="topic-id",
            profile_id="profile-id",
        )
        if profile is not None:
            status = await client.profiles.get_indexing_status(profile)
            print("Indexing status:", status)


asyncio.run(main())

4. Run an orchestrator and read the result/events

client.orchestrators.execute_and_wait starts the orchestration, subscribes to its SSE event stream, calls interaction_handler whenever the workflow pauses for user input, and returns the final OrchestrationResult. progress_handler fires for every event.

import asyncio
from xrcopilotlab import XRCopilotLabClient
from xrcopilotlab.models import (
    OrchestrationRequest,
    UserInteractionRequest,
    UserInteractionResponse,
)


async def main() -> None:
    async with XRCopilotLabClient(api_key="<YOUR_API_KEY>") as client:

        async def on_interaction(req: UserInteractionRequest) -> UserInteractionResponse:
            # The workflow paused to ask the user something.
            print("Interaction required:", req.message)
            return UserInteractionResponse(
                request_id=req.interaction_id,
                response_value="yes",
                answer_language="en",
            )

        result = await client.orchestrators.execute_and_wait(
            company_id="company-id",
            orchestrator_id="orchestrator-id",
            request=OrchestrationRequest(message="Analyze Q3 sales."),
            interaction_handler=on_interaction,
            progress_handler=lambda evt: print(f"[{evt.seq}] {evt.event_type}"),
        )
        print("Final output:", result.final_output)


asyncio.run(main())

For finer control, drive start_execution → stream_execution → resume_execution yourself, or poll get_execution_status for the terminal result after a disconnect.

5. Error handling

The Python SDK raises a typed-exception hierarchy rooted at XRCopilotError. Non-2xx HTTP responses raise XRCopilotApiError (with .status_code, .message, .response_text); 401/403 raise the XRCopilotAuthError subclass; failed orchestrator validation raises XRCopilotValidationError.

import asyncio
from xrcopilotlab import (
    XRCopilotLabClient,
    XRCopilotApiError,
    XRCopilotAuthError,
    XRCopilotError,
)
from xrcopilotlab.models import UserPrompt


async def main() -> None:
    async with XRCopilotLabClient(api_key="<YOUR_API_KEY>") as client:
        prompt = UserPrompt(
            company_id="company-id",
            topic_id="topic-id",
            agent_id="agent-id",
            endpoint_id="endpoint-id",
            message="Hello!",
        )
        try:
            response = await client.agents.chat(prompt)
            print(response.message)
        except XRCopilotAuthError as exc:
            print(f"Auth failed (HTTP {exc.status_code}): {exc.message}")
        except XRCopilotApiError as exc:
            print(f"API error (HTTP {exc.status_code}): {exc.message}")
        except XRCopilotError as exc:
            print(f"SDK error: {exc}")


asyncio.run(main())

More examples are added with each release. Have a use case you'd like covered? Open an issue on xrcopilot-docs.

Clone this wiki locally