> ## 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 TypeScript SDK: Complete Agent Reference

> Install the Nonhumans TypeScript SDK and give your AI agent email, wallet, memory, vault, compute, phone, and web presence — fully typed.

The Nonhumans TypeScript SDK gives your AI agent a complete digital identity in a single package. Import one client, pass your API key, and your agent gains access to a real email inbox, crypto and fiat wallet, vector memory, credential vault, LLM model access, always-on compute, phone number, and a live web presence — all fully typed and ready to use in TypeScript or JavaScript projects.

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @nonhumans/sdk
  ```

  ```bash yarn theme={null}
  yarn add @nonhumans/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @nonhumans/sdk
  ```
</CodeGroup>

## Initialization

```typescript theme={null}
import { Nonhumans } from '@nonhumans/sdk'

const agent = new Nonhumans({ apiKey: process.env.NONHUMANS_KEY })
```

<Note>
  Store your API key in an environment variable. Never hardcode it in source files or commit it to version control.
</Note>

### Configuration options

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

<ParamField body="baseUrl" type="string">
  Override the default API base URL. Useful for self-hosted or regional deployments. Defaults to `https://api.nonhumans.ai/v1`.
</ParamField>

<ParamField body="timeout" type="number">
  Request timeout in milliseconds. Defaults to `30000` (30 seconds).
</ParamField>

<ParamField body="retries" type="number">
  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.

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

// List recent messages
const inbox = await agent.email.list({ limit: 20, unread: true })

// Get a single message by ID
const message = await agent.email.get('msg_01hx...')

// Reply to a message thread
await 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.

```typescript theme={null}
// Check balances
const balances = await agent.wallet.balance()
// { usdc: '250.00', eth: '0.412', usd: '1042.50' }

// Send a payment
await agent.wallet.send({
  to: '0xAbC123...',
  amount: '50',
  currency: 'usdc',
  memo: 'Contractor payout — March',
})

// Create a payment invoice
const invoice = await agent.wallet.invoice.create({
  amount: '200',
  currency: 'usd',
  description: 'Consulting fee',
  dueDate: '2025-04-01',
})

// Issue a virtual card for a spend limit
const card = await agent.wallet.card.create({
  label: 'Cloud infra budget',
  limitAmount: '500',
  limitCurrency: 'usd',
})
```

***

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

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

```typescript theme={null}
// Store a memory
await agent.memory.store({
  content: 'User prefers email summaries on Monday mornings.',
  metadata: { userId: 'usr_99', category: 'preferences' },
})

// Semantic search
const results = await agent.memory.search({
  query: 'email preferences',
  topK: 5,
})

// Upload a file to agent storage
const file = await agent.memory.files.upload({
  name: 'contract.pdf',
  content: pdfBuffer,
  mimeType: 'application/pdf',
})
```

***

### `agent.models` — LLM access

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

```typescript theme={null}
// Chat completion
const response = await 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,
})

console.log(response.choices[0].message.content)

// Generate embeddings
const embedding = await agent.models.embed({
  model: 'text-embedding-3-small',
  input: 'Candidate has 5 years of TypeScript experience.',
})
```

***

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

Run code or open a browser session on persistent compute without managing infrastructure.

```typescript theme={null}
// Execute a script on agent compute
const result = await agent.compute.run({
  runtime: 'node',
  code: `
    const data = [1, 2, 3]
    return data.map(x => x * 2)
  `,
})

console.log(result.output) // [2, 4, 6]

// Open a headless browser session
const browser = await agent.compute.browser.open({ url: 'https://example.com' })
const title = await browser.evaluate(() => document.title)
await browser.close()
```

***

### `agent.vault` — Credential vault

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

```typescript theme={null}
// Store a secret
await agent.vault.set('stripe_key', 'sk_live_...')

// Retrieve a secret
const stripeKey = await agent.vault.get('stripe_key')

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

// Delete a secret
await 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 calls.

```typescript theme={null}
// Send an SMS
await agent.phone.sms({
  to: '+14155550199',
  body: 'Your verification code is 849201.',
})

// Initiate an outbound call
const call = await 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.

```typescript theme={null}
// Register a webhook endpoint
await agent.web.endpoint.register({
  path: '/webhooks/stripe',
  method: 'POST',
  handler: async (req) => {
    const event = req.body
    // process Stripe event...
    return { status: 200, body: { received: true } }
  },
})

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

***

## Error handling

All SDK methods throw a `NonhumansError` on failure. Catch it to inspect the status code and message.

```typescript theme={null}
import { Nonhumans, NonhumansError } from '@nonhumans/sdk'

const agent = new Nonhumans({ apiKey: process.env.NONHUMANS_KEY })

try {
  await agent.email.send({
    to: 'invalid',
    subject: 'Test',
    body: 'Hello',
  })
} catch (err) {
  if (err instanceof NonhumansError) {
    console.error(`[${err.status}] ${err.code}: ${err.message}`)
    // e.g. [422] validation_error: 'to' must be a valid email address
  } else {
    throw err
  }
}
```

<Warning>
  Always handle `NonhumansError` in production code. Unhandled promise rejections will cause your agent to crash silently in some runtimes.
</Warning>

***

## TypeScript types

Every method is fully typed — parameters, return values, and errors. You get autocomplete and compile-time safety out of the box.

```typescript theme={null}
import type {
  EmailMessage,
  WalletBalance,
  MemoryRecord,
  VaultKey,
  ChatResponse,
  ComputeResult,
  NonhumansConfig,
} from '@nonhumans/sdk'

// Example: typed helper
async function summariseInbox(agent: Nonhumans): Promise<EmailMessage[]> {
  return agent.email.list({ limit: 10, unread: true })
}
```

***

## Full example — Recruiting agent

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

```typescript theme={null}
import { Nonhumans } from '@nonhumans/sdk'

const agent = new Nonhumans({ apiKey: process.env.NONHUMANS_KEY })

async function processApplications() {
  // 1. Fetch unread emails
  const emails = await agent.email.list({ unread: true, limit: 50 })

  for (const email of emails) {
    // 2. Score the application with an LLM
    const score = await 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,
    })

    const scoreText = score.choices[0].message.content

    // 3. Persist to memory
    await agent.memory.store({
      content: `Application from ${email.from}: ${scoreText}`,
      metadata: { emailId: email.id, from: email.from },
    })

    // 4. Send a personalised reply
    await agent.email.reply(email.id, {
      body: `Hi,\n\nThank you for reaching out. We have received your application and will review it shortly.\n\nBest,\nAlice`,
    })
  }

  console.log(`Processed ${emails.length} application(s).`)
}

processApplications()
```

***

## Next steps

<CardGroup cols={2}>
  <Card title="Python SDK" icon="python" href="/sdk/python">
    Use Nonhumans from Python with the same capabilities and async support.
  </Card>

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