> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nonhumans.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Nonhumans Python SDK: Full AI Agent Reference Guide

> Install the Nonhumans Python SDK and give your AI agent email, wallet, memory, vault, compute, phone, and web presence — with sync and async support.

The Nonhumans Python SDK brings your AI agent a complete digital identity without the infrastructure overhead. In a few lines of Python your agent gains a real email inbox, crypto and fiat wallet, vector memory, credential vault, LLM access, always-on compute, and more — all through a single, consistent API key.

## Installation

<CodeGroup>
  ```bash pip theme={null}
  pip install nonhumans
  ```

  ```bash poetry theme={null}
  poetry add nonhumans
  ```
</CodeGroup>

<Note>
  Python 3.9 or later is required. The SDK ships with type hints throughout, so you get autocomplete and static analysis in editors like VS Code and PyCharm.
</Note>

## Initialization

```python theme={null}
from nonhumans import Nonhumans
import os

agent = Nonhumans(api_key=os.environ['NONHUMANS_KEY'])
```

Store your API key in an environment variable — never hardcode it. The client reads `NONHUMANS_KEY` automatically if you omit `api_key`.

### Configuration options

<ParamField body="api_key" type="str" required>
  Your agent's API key. Retrieve it from the [Nonhumans dashboard](https://nonhumans.ai). Defaults to the `NONHUMANS_KEY` environment variable.
</ParamField>

<ParamField body="base_url" type="str">
  Override the default API base URL. Defaults to `https://api.nonhumans.ai/v1`.
</ParamField>

<ParamField body="timeout" type="float">
  Request timeout in seconds. Defaults to `30.0`.
</ParamField>

<ParamField body="retries" type="int">
  Number of automatic retries on transient network errors. Defaults to `2`.
</ParamField>

***

## Modules

### `agent.email` — Email inbox

Your agent has a real email address (e.g. `alice@nonhumans.ai`). Read, send, and reply to messages programmatically.

```python theme={null}
# Send an email
agent.email.send(
    to="hiring@acme.com",
    subject="Application received",
    body="Thank you for applying. We will be in touch shortly.",
)

# List recent unread messages
inbox = agent.email.list(limit=20, unread=True)
for message in inbox:
    print(message.subject, message.from_address)

# Fetch a single message by ID
message = agent.email.get("msg_01hx...")

# Reply to a thread
agent.email.reply(
    "msg_01hx...",
    body="Following up on your earlier question — see details below.",
)
```

***

### `agent.wallet` — Crypto & fiat payments

Send and receive payments, issue invoices, and create virtual cards without wiring up a separate payments provider.

```python theme={null}
# Check balances
balances = agent.wallet.balance()
# {'usdc': '250.00', 'eth': '0.412', 'usd': '1042.50'}

# Send a payment
agent.wallet.send(
    to="0xAbC123...",
    amount="50",
    currency="usdc",
    memo="Contractor payout — March",
)

# Create a payment invoice
invoice = agent.wallet.invoice.create(
    amount="200",
    currency="usd",
    description="Consulting fee",
    due_date="2025-04-01",
)
print(invoice.payment_url)

# Issue a virtual card
card = agent.wallet.card.create(
    label="Cloud infra budget",
    limit_amount="500",
    limit_currency="usd",
)
```

***

### `agent.memory` — Vector memory & file storage

Store, retrieve, and semantically search anything your agent needs to remember across sessions.

```python theme={null}
# Store a memory
agent.memory.store(
    content="User prefers email summaries on Monday mornings.",
    metadata={"user_id": "usr_99", "category": "preferences"},
)

# Semantic search
results = agent.memory.search(query="email preferences", top_k=5)
for record in results:
    print(record.content, record.score)

# Upload a file to agent storage
with open("contract.pdf", "rb") as f:
    file_ref = agent.memory.files.upload(
        name="contract.pdf",
        content=f.read(),
        mime_type="application/pdf",
    )
print(file_ref.url)
```

***

### `agent.models` — LLM access

Call language models through the same API key — no separate provider accounts required.

```python theme={null}
# Chat completion
response = agent.models.chat(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful recruiting assistant."},
        {"role": "user", "content": "Summarise this resume in three bullet points."},
    ],
    temperature=0.3,
)
print(response.choices[0].message.content)

# Generate embeddings
embedding = agent.models.embed(
    model="text-embedding-3-small",
    input="Candidate has 5 years of Python experience.",
)
print(len(embedding.data[0].embedding))  # e.g. 1536
```

***

### `agent.compute` — Always-on compute

Run code on persistent agent compute without managing infrastructure.

```python theme={null}
# Execute a Python snippet on agent compute
result = agent.compute.run(
    runtime="python",
    code="""
data = [1, 2, 3]
return [x * 2 for x in data]
""",
)
print(result.output)  # [2, 4, 6]
```

***

### `agent.vault` — Credential vault

Securely store and retrieve API keys, tokens, and other secrets your agent needs at runtime.

```python theme={null}
# Store a secret
agent.vault.set("stripe_key", "sk_live_...")

# Retrieve a secret
stripe_key = agent.vault.get("stripe_key")

# List all stored secret names (values are never returned in list)
keys = agent.vault.list()
# ['stripe_key', 'openai_key', 'twilio_sid']

# Delete a secret
agent.vault.delete("stripe_key")
```

***

### `agent.phone` — SMS & voice calls

Your agent has a real phone number it can use to send texts and make outbound calls.

```python theme={null}
# Send an SMS
agent.phone.sms(
    to="+14155550199",
    body="Your verification code is 849201.",
)

# Initiate an outbound call
call = agent.phone.call(
    to="+14155550199",
    script="Hello, this is Alice calling from Acme to confirm your appointment.",
)
```

***

### `agent.web` — Web presence & calendar

Register HTTP endpoints on your agent's public subdomain and expose a bookable calendar to the world.

```python theme={null}
# Register a webhook endpoint
agent.web.endpoint.register(
    path="/webhooks/stripe",
    method="POST",
    handler=lambda req: {"status": 200, "body": {"received": True}},
)

# Set calendar availability
agent.web.calendar.set_availability(
    timezone="America/New_York",
    slots=[
        {"day": "monday", "start": "09:00", "end": "17:00"},
        {"day": "wednesday", "start": "09:00", "end": "12:00"},
    ],
)
```

***

## Async support

For async frameworks like FastAPI, asyncio, or LangChain async chains, use `AsyncNonhumans`. Every method is `await`-able and the interface mirrors the sync client exactly.

```python theme={null}
import asyncio
from nonhumans import AsyncNonhumans
import os

agent = AsyncNonhumans(api_key=os.environ['NONHUMANS_KEY'])

async def process_inbox():
    emails = await agent.email.list(unread=True, limit=50)

    for email in emails:
        # Score with an LLM
        score = await agent.models.chat(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "Rate this application 1–10."},
                {"role": "user", "content": email.body},
            ],
        )
        # Store result
        await agent.memory.store(
            content=f"Score for {email.from_address}: {score.choices[0].message.content}",
            metadata={"email_id": email.id},
        )
        # Reply
        await agent.email.reply(email.id, body="Thanks for your application!")

asyncio.run(process_inbox())
```

<Tip>
  Use `AsyncNonhumans` inside any async framework — FastAPI route handlers, Celery async tasks, or standalone `asyncio` scripts — without any extra configuration.
</Tip>

***

## Error handling

All SDK methods raise `NonhumansError` on failure. Inspect `status`, `code`, and `message` to handle errors cleanly.

```python theme={null}
from nonhumans import Nonhumans, NonhumansError
import os

agent = Nonhumans(api_key=os.environ['NONHUMANS_KEY'])

try:
    agent.email.send(
        to="not-an-email",
        subject="Test",
        body="Hello",
    )
except NonhumansError as e:
    print(f"[{e.status}] {e.code}: {e.message}")
    # e.g. [422] validation_error: 'to' must be a valid email address
```

<Warning>
  In async code, use `try/except` inside your `async` functions or attach an exception handler to your event loop to avoid silent task failures.
</Warning>

***

## Full example — Recruiting agent

This example shows an agent that monitors its inbox for job applications, scores them, stores the result in memory, and sends a personalised reply.

```python theme={null}
from nonhumans import Nonhumans, NonhumansError
import os

agent = Nonhumans(api_key=os.environ['NONHUMANS_KEY'])

def process_applications():
    # 1. Fetch unread emails
    emails = agent.email.list(unread=True, limit=50)
    print(f"Found {len(emails)} new application(s).")

    for email in emails:
        try:
            # 2. Score the application with an LLM
            score = agent.models.chat(
                model="gpt-4o",
                messages=[
                    {
                        "role": "system",
                        "content": (
                            "You are a recruiting assistant. "
                            "Rate the candidate 1–10 and give a one-sentence reason."
                        ),
                    },
                    {"role": "user", "content": email.body},
                ],
                temperature=0,
            )
            score_text = score.choices[0].message.content

            # 3. Persist to memory
            agent.memory.store(
                content=f"Application from {email.from_address}: {score_text}",
                metadata={"email_id": email.id, "from": email.from_address},
            )

            # 4. Send a personalised reply
            agent.email.reply(
                email.id,
                body=(
                    "Hi,\n\n"
                    "Thank you for reaching out. We have received your application "
                    "and will review it shortly.\n\n"
                    "Best,\nAlice"
                ),
            )

        except NonhumansError as e:
            print(f"Failed to process {email.id}: {e.message}")

if __name__ == "__main__":
    process_applications()
```

***

## Next steps

<CardGroup cols={2}>
  <Card title="TypeScript SDK" icon="js" href="/sdk/typescript">
    Build agents in TypeScript or JavaScript with the same full-featured SDK.
  </Card>

  <Card title="CLI Reference" icon="terminal" href="/sdk/cli">
    Scaffold, deploy, and inspect agents from the command line.
  </Card>
</CardGroup>
