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

# Tools API

> Agentic capabilities: Web Search, Documents/RAG, and Memory

# Tools API

The Tools Library provides agentic capabilities for your AI applications. Add web search, document retrieval (RAG), and conversation memory with a single API.

## Available Tools

| Tool              | Description                                     | Availability |
| ----------------- | ----------------------------------------------- | ------------ |
| **Web Search**    | Real-time web search with AI-optimized results  | All tiers    |
| **Documents/RAG** | Upload and query documents with semantic search | Pro+         |
| **Memory**        | Persistent conversation context across sessions | Pro+         |

## Web Search

Search the web in real-time with AI-optimized results.

### Endpoint

```
POST https://api.withperf.pro/v1/tools/search
```

### Request

```bash theme={null}
curl -X POST https://api.withperf.pro/v1/tools/search \
  -H "Authorization: Bearer pk_live_abc123" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "latest developments in AI agents",
    "max_results": 5,
    "search_depth": "basic"
  }'
```

| Parameter         | Type      | Default  | Description                             |
| ----------------- | --------- | -------- | --------------------------------------- |
| `query`           | string    | required | Search query                            |
| `max_results`     | integer   | 5        | Maximum results to return (1-10)        |
| `search_depth`    | string    | "basic"  | Search depth: `basic` or `advanced`     |
| `include_domains` | string\[] | -        | Only include results from these domains |
| `exclude_domains` | string\[] | -        | Exclude results from these domains      |

### Response

```json theme={null}
{
  "results": [
    {
      "title": "AI Agents Are Transforming Software Development",
      "url": "https://example.com/ai-agents-2024",
      "content": "Recent advances in AI agents have enabled autonomous coding, debugging, and deployment...",
      "relevance_score": 0.95
    }
  ],
  "metadata": {
    "provider": "perf",
    "latency_ms": 1234,
    "cost_usd": 0.01
  }
}
```

### Pricing

| Tier    | Cost per Search |
| ------- | --------------- |
| Starter | \$0.015         |
| Pro     | \$0.012         |
| Growth  | \$0.011         |
| Team    | \$0.01          |

## Documents / RAG

Upload documents and query them with semantic search. Use documents as context in chat requests for Q\&A, structured extraction, and more.

### Upload Document

```
POST https://api.withperf.pro/v1/documents
```

Upload a file directly or send base64-encoded content. Perf will automatically chunk the document, generate embeddings, and make it available for search and chat context.

#### File Upload (Recommended)

Send the file directly using `multipart/form-data`:

```bash theme={null}
curl -X POST https://api.withperf.pro/v1/documents \
  -H "Authorization: Bearer pk_live_abc123" \
  -F "file=@product-datasheet.pdf"
```

**Python:**

```python theme={null}
import requests

response = requests.post(
    "https://api.withperf.pro/v1/documents",
    headers={"Authorization": "Bearer pk_live_abc123"},
    files={"file": open("product-datasheet.pdf", "rb")}
)
document_id = response.json()["id"]  # Save this to use with /v1/chat
```

**Node.js:**

```javascript theme={null}
const form = new FormData();
form.append("file", fs.createReadStream("product-datasheet.pdf"));

const response = await fetch("https://api.withperf.pro/v1/documents", {
  method: "POST",
  headers: { "Authorization": "Bearer pk_live_abc123" },
  body: form
});
const { id: documentId } = await response.json();
```

You can include optional fields as form fields alongside the file:

```bash theme={null}
curl -X POST https://api.withperf.pro/v1/documents \
  -H "Authorization: Bearer pk_live_abc123" \
  -F "file=@product-datasheet.pdf" \
  -F "collection_id=solar-datasheets" \
  -F 'metadata={"manufacturer": "Vikram Solar"}'
```

#### JSON Upload (Base64)

Alternatively, send base64-encoded content in a JSON body:

```bash theme={null}
curl -X POST https://api.withperf.pro/v1/documents \
  -H "Authorization: Bearer pk_live_abc123" \
  -H "Content-Type: application/json" \
  -d '{
    "filename": "product-datasheet.pdf",
    "content": "<base64-encoded-file-content>",
    "content_type": "application/pdf"
  }'
```

#### Parameters

**File upload** (`multipart/form-data`):

| Field           | Type   | Required | Description                                   |
| --------------- | ------ | -------- | --------------------------------------------- |
| `file`          | file   | Yes      | The file to upload (PDF, TXT, MD). Max 20 MB. |
| `collection_id` | string | No       | Collection to organize the document into      |
| `metadata`      | string | No       | JSON string of custom key-value metadata      |

**JSON upload** (`application/json`):

| Parameter       | Type   | Required | Description                                                       |
| --------------- | ------ | -------- | ----------------------------------------------------------------- |
| `filename`      | string | Yes      | Original filename (used for display and format detection)         |
| `content`       | string | Yes      | Base64-encoded file content, or plain text for `.txt`/`.md` files |
| `content_type`  | string | No       | MIME type: `application/pdf`, `text/plain`, `text/markdown`       |
| `collection_id` | string | No       | Collection to organize the document into                          |
| `metadata`      | object | No       | Custom key-value metadata for filtering                           |

#### Response

```json theme={null}
{
  "id": "doc_abc123",
  "filename": "product-datasheet.pdf",
  "content_type": "application/pdf",
  "status": "processing",
  "file_size_bytes": 125000,
  "collection_id": null,
  "created_at": "2024-01-15T10:30:00Z"
}
```

Save the `id` from the response — you'll need it to reference this document in `/v1/chat` requests.

**Document Status:**

* `processing` - Being chunked and embedded
* `ready` - Available for search
* `failed` - Processing failed (check `error_message`)

### Use with Chat API

Once a document is `ready`, pass its `id` as `document_id` in a `/v1/chat` request to use it as context:

```bash theme={null}
curl -X POST https://api.withperf.pro/v1/chat \
  -H "Authorization: Bearer pk_live_abc123" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "user", "content": "Summarize the key points from this document"}
    ],
    "document_id": "doc_abc123"
  }'
```

You can also combine `document_id` with `schema_id` for structured data extraction. See [Document Context in Chat API](./chat#document-context) for full details.

### Query Documents

```
POST https://api.withperf.pro/v1/documents/query
```

```bash theme={null}
curl -X POST https://api.withperf.pro/v1/documents/query \
  -H "Authorization: Bearer pk_live_abc123" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What is the vacation policy?",
    "collection_id": "col_abc123",
    "top_k": 5,
    "threshold": 0.3
  }'
```

| Parameter       | Type    | Default  | Description                     |
| --------------- | ------- | -------- | ------------------------------- |
| `query`         | string  | required | Search query                    |
| `collection_id` | string  | none     | Filter to a specific collection |
| `top_k`         | integer | 5        | Maximum results                 |
| `threshold`     | number  | 0.3      | Minimum similarity score (0-1)  |

**Response:**

```json theme={null}
{
  "query": "What is the vacation policy?",
  "results": [
    {
      "chunk_id": "chunk_xyz789",
      "document_id": "doc_abc123",
      "filename": "company-handbook.pdf",
      "content": "Employees receive 20 days of paid vacation per year, accrued monthly...",
      "score": 0.94,
      "chunk_index": 15,
      "metadata": {
        "department": "HR"
      }
    }
  ],
  "metadata": {
    "latency_ms": 234,
    "cost_usd": 0.0001
  }
}
```

### List Documents

```
GET https://api.withperf.pro/v1/documents?collection_id=col_abc123
```

### Delete Document

```
DELETE https://api.withperf.pro/v1/documents/{documentId}
```

### Document Limits by Tier

| Tier       | Documents | Storage | Collections |
| ---------- | --------- | ------- | ----------- |
| Pro        | 500       | 1 GB    | 10          |
| Growth     | 5,000     | 10 GB   | 50          |
| Team       | 50,000    | 100 GB  | 500         |
| Enterprise | 500,000   | 1 TB    | 5,000       |

## Memory / Context

Persist conversation context across sessions. The AI remembers previous interactions without you managing conversation history.

### Using Memory with Chat

Add `session_id` to your chat requests to enable memory:

```bash theme={null}
curl -X POST https://api.withperf.pro/v1/chat \
  -H "Authorization: Bearer pk_live_abc123" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "user", "content": "Hi, my name is Sarah"}
    ],
    "session_id": "user_123_conversation",
    "memory": {
      "enabled": true,
      "include_last_n": 10
    }
  }'
```

| Parameter               | Type    | Description                         |
| ----------------------- | ------- | ----------------------------------- |
| `session_id`            | string  | Unique session identifier           |
| `memory.enabled`        | boolean | Enable memory for this request      |
| `memory.include_last_n` | integer | Include last N messages from memory |

Now in a subsequent request:

```bash theme={null}
curl -X POST https://api.withperf.pro/v1/chat \
  -H "Authorization: Bearer pk_live_abc123" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "user", "content": "What is my name?"}
    ],
    "session_id": "user_123_conversation",
    "memory": {"enabled": true}
  }'
```

The AI will remember: *"Your name is Sarah, as you mentioned earlier."*

### Memory Management

**List Sessions:**

```
GET https://api.withperf.pro/v1/memory
```

**Get Session:**

```
GET https://api.withperf.pro/v1/memory/{sessionId}
```

**Clear Session:**

```
POST https://api.withperf.pro/v1/memory/{sessionId}/clear
```

**Delete Session:**

```
DELETE https://api.withperf.pro/v1/memory/{sessionId}
```

### Memory Limits by Tier

| Tier       | Memory Tokens | Sessions | Retention |
| ---------- | ------------- | -------- | --------- |
| Pro        | 100,000       | 100      | 30 days   |
| Growth     | 500,000       | 1,000    | 90 days   |
| Team       | 2,000,000     | 10,000   | 1 year    |
| Enterprise | 10,000,000    | 100,000  | 2 years   |

### Auto-Summarization

When a session approaches its token limit, Perf automatically:

1. Summarizes older messages
2. Preserves recent messages intact
3. Continues conversation with summary + recent context

This ensures conversations can continue indefinitely within your tier limits.

## Combining Tools

Tools work together seamlessly. For example, search the web, store relevant information in documents, and use memory to maintain context:

```bash theme={null}
# 1. Search for current information
curl -X POST https://api.withperf.pro/v1/tools/search \
  -H "Authorization: Bearer pk_live_abc123" \
  -d '{"query": "latest AI news today"}'

# 2. Chat with memory and context
curl -X POST https://api.withperf.pro/v1/chat \
  -H "Authorization: Bearer pk_live_abc123" \
  -d '{
    "messages": [{"role": "user", "content": "Summarize the AI news I just searched"}],
    "session_id": "research_session",
    "memory": {"enabled": true}
  }'
```

## Pricing Summary

| Tool       | Pricing Model             |
| ---------- | ------------------------- |
| Web Search | Per search (\$0.01-0.015) |
| Documents  | Per embedding token       |
| Memory     | Included in tier          |

## Plan Availability

| Feature       | Starter | Pro | Growth | Team | Enterprise |
| ------------- | ------- | --- | ------ | ---- | ---------- |
| Web Search    | Yes     | Yes | Yes    | Yes  | Yes        |
| Documents/RAG | -       | Yes | Yes    | Yes  | Yes        |
| Memory        | -       | Yes | Yes    | Yes  | Yes        |

## Related

* [Chat API](./chat) - Core chat endpoint with tool integration
* [Streaming API](./streaming) - Real-time responses with tools
* [Policies API](./policies) - Control tool usage with policies
