Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/content/docs/ai-search/get-started/api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: REST API
pcx_content_type: get-started
sidebar:
order: 2
order: 5
description: Create AI Search instances programmatically using the REST API.
products:
- ai-search
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/ai-search/get-started/dashboard.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Dashboard
pcx_content_type: get-started
sidebar:
order: 1
order: 4
description: Create and configure AI Search using the Cloudflare dashboard.
products:
- ai-search
Expand Down
28 changes: 17 additions & 11 deletions src/content/docs/ai-search/get-started/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,30 +13,36 @@ products:
- ai-search
---

import { DashButton, CardGrid, LinkCard } from "~/components";
import { CardGrid, LinkCard } from "~/components";

AI Search is a managed search service. Connect a website, an R2 bucket, or upload your own documents, and AI Search indexes your content for natural language queries.

## Prerequisites

If you plan to use an R2 bucket as your data source, you must have an active [R2 subscription](/r2/get-started/) before creating your AI Search instance. If you plan to use a website or upload files directly, no additional setup is required.

## Choose your setup method

<CardGrid>
<LinkCard
title="Workers API"
description="Create, populate, and query an AI Search instance from a Cloudflare Worker."
href="/ai-search/get-started/workers/"
/>
<LinkCard
title="Python SDK"
description="Create, populate, and query an AI Search instance from Python."
href="/ai-search/get-started/python/"
/>
<LinkCard
title="CLI"
description="Create and manage AI Search instances from the command line."
href="/ai-search/get-started/wrangler/"
/>
<LinkCard
title="Dashboard"
description="Create and configure AI Search using the Cloudflare dashboard."
href="/ai-search/get-started/dashboard/"
/>
<LinkCard
title="API"
title="REST API"
description="Create AI Search instances programmatically using the REST API."
href="/ai-search/get-started/api/"
/>
<LinkCard
title="Wrangler commands"
description="Create and manage AI Search instances from the command line."
href="/ai-search/get-started/wrangler/"
/>
</CardGrid>
152 changes: 152 additions & 0 deletions src/content/docs/ai-search/get-started/python.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
---
title: Python SDK
pcx_content_type: get-started
sidebar:
order: 2
description: Create, populate, and query an AI Search instance from Python.
products:
- ai-search
---

import { LinkCard, DashButton } from "~/components";

This guide walks you through creating an AI Search instance, uploading content, and querying it from a Python application using the [Cloudflare Python SDK](https://github.com/cloudflare/cloudflare-python).

## Prerequisites

- [Python](https://www.python.org/downloads/) 3.8 or later.
- Your [account ID](/fundamentals/account/find-account-and-zone-ids/).

This guide uses the `default` [namespace](/ai-search/concepts/namespaces/), which exists automatically on every account. To group instances into your own namespace, create one with `client.aisearch.namespaces.create()`.

## 1. Create an API token

You need an API token with **AI Search:Edit** and **AI Search:Run** permissions.

1. In the Cloudflare dashboard, go to **My Profile** > **API Tokens**.

<DashButton url="/profile/api-tokens" />

2. Select **Create Token**.
3. Select **Create Custom Token**.
4. Enter a **Token name**, for example `AI Search Python`.
5. Under **Permissions**, add two permissions:
- **Account** > **AI Search:Edit**
- **Account** > **AI Search:Run**
6. Select **Continue to summary**, then select **Create Token**.
7. Copy and save the token value. This is your `API_TOKEN`.

## 2. Set up your Python environment

Create a project directory and a virtual environment to isolate your dependencies.

```sh
mkdir ai-search-python && cd ai-search-python
python3 -m venv .venv
source .venv/bin/activate
```

On Windows, activate the virtual environment with `.venv\Scripts\activate` instead.

## 3. Install the Cloudflare Python SDK

Install the official `cloudflare` package:

```sh
pip install cloudflare
```

## 4. Set your credentials

Export your account ID and API token as environment variables.

```sh
export CLOUDFLARE_ACCOUNT_ID="<ACCOUNT_ID>"
export CLOUDFLARE_API_TOKEN="<API_TOKEN>"
```

## 5. Create an AI Search instance

Create a file named `quickstart.py`. The following code sets up a client and creates an instance named `my-instance` in the `default` namespace. Because no data source is specified, the instance uses [built-in storage](/ai-search/configuration/data-source/built-in-storage/), so you can upload files to it directly.

```python title="quickstart.py"
import os

from cloudflare import Cloudflare

client = Cloudflare(api_token=os.environ["CLOUDFLARE_API_TOKEN"])
account_id = os.environ["CLOUDFLARE_ACCOUNT_ID"]

instance = client.aisearch.namespaces.instances.create(
name="default",
account_id=account_id,
id="my-instance",
)

print(f"Created instance: {instance.id}")
```

:::note
Creating an instance is a one-time action. If you run the script again, remove this step, because an instance name must be unique within a namespace.
:::

## 6. Upload content

Add the following to `quickstart.py` to upload a document. Setting `wait_for_completion` to `True` waits for indexing before returning so the file is ready to search. If indexing is still finishing, `item.status` may be `running`; the file continues indexing in the background and becomes searchable shortly after.

```python title="quickstart.py"
item = client.aisearch.namespaces.instances.items.upload(
id="my-instance",
account_id=account_id,
name="default",
file={
"file": (
"getting-started.md",
b"AI Search indexes uploaded content for retrieval.",
"text/markdown",
),
"wait_for_completion": True,
},
Comment thread
aninibread marked this conversation as resolved.
)

print(f"Uploaded item status: {item.status}")
```

## 7. Search your instance

Add the following to `quickstart.py` to run a query against your indexed content.

```python title="quickstart.py"
results = client.aisearch.namespaces.instances.search(
id="my-instance",
account_id=account_id,
name="default",
query="How does AI Search handle uploaded content?",
)

if results.chunks:
print(results.chunks[0].text)
else:
print("No results yet — your content may still be indexing. Try again in a moment.")
```

Run the script:

```sh
python quickstart.py
```

If the search returns no results, the content may still be indexing. Wait a moment, then run the search again.

## Next steps

<LinkCard
title="REST API"
description="Query AI Search using HTTP requests."
href="/ai-search/api/search/rest-api/"
/>
<LinkCard
title="Workers API"
description="Query AI Search from within a Cloudflare Worker."
href="/ai-search/get-started/workers/"
/>
147 changes: 147 additions & 0 deletions src/content/docs/ai-search/get-started/workers.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
---
title: Workers binding
pcx_content_type: get-started
sidebar:
order: 1
description: Create, populate, and query an AI Search instance from a Cloudflare Worker.
products:
- ai-search
---

import {
Render,
PackageManagers,
WranglerConfig,
TypeScriptExample,
LinkCard,
} from "~/components";

This guide walks you through creating and querying an AI Search instance from a [Cloudflare Worker](/workers/) using the Workers Binding. The Workers Binding uses a runtime [API](/ai-search/api/search/workers-binding/) that runs inside a Worker and calls AI Search without managing API tokens.

<Render file="prereqs" product="workers" />

## 1. Create a Worker project

Create a new Worker project using the `create-cloudflare` CLI (C3). [C3](https://github.com/cloudflare/workers-sdk/tree/main/packages/create-cloudflare) is a command-line tool designed to help you set up and deploy new applications to Cloudflare.

Create a new project named `ai-search-tutorial` by running:

<PackageManagers type="create" pkg="cloudflare@latest" args={"ai-search-tutorial"} />

<Render
file="c3-post-run-steps"
product="workers"
params={{
category: "hello-world",
type: "Worker only",
lang: "TypeScript",
}}
/>

Go to your application directory:

```sh
cd ai-search-tutorial
```

## 2. Connect your Worker to AI Search

Create a binding between your Worker and your AI Search instance. [Bindings](/workers/runtime-apis/bindings/) allow your Worker to interact with resources on the Cloudflare Developer Platform.

Add the following to your [Wrangler configuration file](/workers/wrangler/configuration/):

<WranglerConfig>

```toml
[[ai_search_namespaces]]
binding = "AI_SEARCH"
namespace = "default"
remote = true
```

</WranglerConfig>

This binds the `default` namespace to `env.AI_SEARCH`. Instances that you create without specifying a namespace belong to the `default` namespace. The `remote` option lets `wrangler dev` proxy requests to your deployed instance, since AI Search does not run locally. For all binding options, refer to the [Workers binding reference](/ai-search/api/search/workers-binding/).

## 3. Create and query AI Search from your Worker

Update the `src/index.ts` file in your `ai-search-tutorial` directory with the following code. It exposes two routes: `/setup` creates an instance named `my-instance` and indexes a sample document, and the default route queries it.

<TypeScriptExample filename="src/index.ts">

```ts
export interface Env {
AI_SEARCH: AiSearchNamespace;
}

export default {
async fetch(request, env): Promise<Response> {
const url = new URL(request.url);

// Visit /setup once to create an instance and index a sample document.
if (url.pathname === "/setup") {
const instance = await env.AI_SEARCH.create({ id: "my-instance" });
const item = await instance.items.uploadAndPoll(
"getting-started.md",
"AI Search indexes uploaded content for retrieval.",
);
return Response.json({ created: "my-instance", status: item.status });
}

// Query the instance.
const query = url.searchParams.get("q") ?? "What does AI Search do?";

const results = await env.AI_SEARCH.get("my-instance").search({
messages: [{ role: "user", content: query }],
ai_search_options: {
retrieval: { max_num_results: 3 },
},
});

return Response.json(results.chunks);
},
} satisfies ExportedHandler<Env>;
```

</TypeScriptExample>

## 4. Develop locally

Start a local development server:

```sh
npx wrangler dev
```

Wrangler gives you a URL (usually `localhost:8787`). Visit `/setup` once to create your instance and index the sample document, then query it at `/?q=your+search+terms`.

## 5. Deploy your Worker

Log in with your Cloudflare account:

```sh
npx wrangler login
```

Deploy your Worker to make it accessible on the Internet:

```sh
npx wrangler deploy
```

```txt
https://ai-search-tutorial.<YOUR_SUBDOMAIN>.workers.dev
```

## Next steps

<LinkCard
title="Search Workers binding"
description="Full reference for searching and chatting from a Worker."
href="/ai-search/api/search/workers-binding/"
/>
<LinkCard
title="Items Workers binding"
description="Upload, list, and manage documents from a Worker."
href="/ai-search/api/items/workers-binding/"
/>
2 changes: 1 addition & 1 deletion src/content/docs/ai-search/get-started/wrangler.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: Wrangler commands
title: CLI
pcx_content_type: get-started
sidebar:
order: 3
Expand Down
Loading