# Python SDK

> Install the core async Python client, search and read code, and ask Corfedo AI with streaming, reattach and your own tools.

Source: https://docs.corfedo.ai/connect/sdks/python/

The Python SDK requires Python 3.11 or later and uses Apache-2.0. The core package stays independent of AI frameworks. The extras add Corfedo to [LangChain](https://docs.corfedo.ai/connect/frameworks/langchain/) and [Pydantic AI](https://docs.corfedo.ai/connect/frameworks/pydantic-ai/).

```sh
pip install corfedo
pip install 'corfedo[langchain]'
pip install 'corfedo[pydantic-ai]'
```

`await client.search.search(...)` and `await client.code.read_file(...)` search and read code with the requests in `corfedo.models`, see [Search and read code](https://docs.corfedo.ai/connect/api/search-and-read/).

## Ask Corfedo AI

```python
import os
from uuid import uuid4
from corfedo import CorfedoClient
from corfedo.models import SendAiMessage

async with CorfedoClient.from_api_key_file(os.environ['CORFEDO_API_KEY_FILE']) as client:
    async with client.ai.stream(SendAiMessage(
        client_message_id=uuid4(), text='How are search requests routed?'
    )) as run:
        async for event in run:
            if event.type == 'text.delta':
                print(event.text, end='')
    print(run.outcome, run.answer, run.citations)
```

Run the snippet inside your application's async entry point. The key needs **Search and read code** and **Ask Corfedo AI**, see [API keys](https://docs.corfedo.ai/connect/authentication/#api-keys). Use `await client.ai.send(...)` for a non-streaming wait. It may return before the run ends. Continue with a new `client_message_id` and the returned `conversation_id`.

`list_profiles`, `list_conversations`, `get_conversation` and `delete_conversation` expose profiles and history. `reattach(run_id, after=...)` observes a run using an integer sequence. `get_run` returns a snapshot and `cancel` requests cancellation. Closing a stream only ends its subscription.

`stream_tool_results` and `submit_tool_results` return the results of your own tools. Run the calls in `required_calls` of the stream that sent the message. A reattached stream only lists `pending_calls`. See [Client tools](https://docs.corfedo.ai/connect/api/ai/client-tools/).

## Errors and recovery

The core raises `CorfedoError` with typed failures such as `AccessDenied`, `Conflict`, `SpendingLimitReached` and `StreamFailed`. Browser sign-in with `CorfedoAuthentication` asks for Corfedo AI only when `HumanAuthenticationOptions.scopes` includes it, see [Ask for Corfedo AI](https://docs.corfedo.ai/connect/authentication/#request-access-to-corfedo-ai).

If the connection drops, the SDK reconnects for up to 30 seconds, then raises the last error. The run keeps going. Use the [renewal callback](https://docs.corfedo.ai/connect/authentication/#keep-a-human-session-alive) for long-lived human sessions. Cancelling an async call or closing a stream does not cancel the backend run.
