### Quick Start
Source: https://github.com/daydreamsai/daydreams/blob/main/packages/chroma/README.md
A basic example demonstrating how to initialize the ChromaDB memory system and create a DaydreamsAI agent.
```APIDOC
## Quick Start
```typescript
import { createDreams } from "@daydreamsai/core";
import { createChromaMemory } from "@daydreamsai/chroma";
// Create memory system
const memory = createChromaMemory({
path: "http://localhost:8000", // ChromaDB server URL
collectionName: "my_agents", // optional, defaults to "daydreams_vectors"
});
// Initialize the memory system
await memory.initialize();
// Create agent with ChromaDB memory
const agent = createDreams({
memory,
// ... other config
});
```
```
--------------------------------
### Install Dependencies with Bun
Source: https://github.com/daydreamsai/daydreams/blob/main/examples/x402/nanoservice/README.md
Installs project dependencies using the Bun package manager. This is a prerequisite for running the server and client examples.
```bash
bun install
```
--------------------------------
### Install LLM Provider SDK (Manual Install)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/installation.mdx
Add an SDK for a specific LLM provider to your project. Example shows installing the OpenAI SDK, with support for Anthropic, Google Gemini, and others available.
```bash
# pnpm
pnpm add @ai-sdk/openai
```
```bash
# npm
npm install @ai-sdk/openai
```
```bash
# bun
bun add @ai-sdk/openai
```
```bash
# yarn
yarn add @ai-sdk/openai
```
--------------------------------
### Create Daydreams Agent (Easy Install)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/installation.mdx
Use the 'create-agent' command for a quick setup. This command initializes a new agent directory, sets up dependencies, creates an index.ts file, generates a .env.example, and installs packages.
```bash
npx @daydreamsai/create-agent my-agent
```
--------------------------------
### ChromaDB Setup Options
Source: https://github.com/daydreamsai/daydreams/blob/main/packages/chroma/README.md
Instructions for setting up and running ChromaDB, including Docker, Python installation, and embedded mode.
```APIDOC
## Setup
### 1. ChromaDB Installation & Setup
Choose one of the following options to run ChromaDB:
#### Option A: Docker (Recommended)
```bash
# Run ChromaDB server
docker run -p 8000:8000 chromadb/chroma
```
#### Option B: Python Installation
```bash
pip install chromadb
chroma run --host 0.0.0.0 --port 8000
```
#### Option C: Embedded Mode (Client-only)
ChromaDB can run embedded within your Node.js application (no separate server needed).
```
--------------------------------
### Quick Start: Running a Daydreams AI Agent (TypeScript)
Source: https://github.com/daydreamsai/daydreams/blob/main/readme.md
Set up and run a basic Daydreams AI agent in under 60 seconds. This example demonstrates installing necessary packages, defining a simple weather context with an action, creating the agent with an OpenAI model, and sending an initial message to the agent.
```bash
npm install @daydreamsai/core @ai-sdk/openai zod
```
```typescript
import { createDreams, context, action } from "@daydreamsai/core";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
// Define a simple weather context
const weatherContext = context({
type: "weather",
create: () => ({ lastQuery: null }),
}).setActions([
action({
name: "getWeather",
schema: z.object({ city: z.string() }),
handler: async ({ city }, ctx) => {
ctx.memory.lastQuery = city;
// Your weather API logic here
return { weather: `Sunny, 72°F in ${city}` };
},
}),
]);
// Create your agent
const agent = createDreams({
model: openai("gpt-4o"),
contexts: [weatherContext],
});
// Start chatting!
await agent.send({
context: weatherContext,
input: "What's the weather in San Francisco?",
});
```
--------------------------------
### Configure Environment Variables
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/installation.mdx
Copy the example environment file and add your obtained API keys. This step is crucial for authentication with LLM providers.
```bash
# Create .env file
cp .env.example .env
```
```env
OPENAI_API_KEY=your_openai_api_key_here
# ANTHROPIC_API_KEY=your_anthropic_api_key_here
# GEMINI_API_KEY=your_gemini_api_key_here
```
--------------------------------
### Complete MongoDB Agent Setup Example
Source: https://github.com/daydreamsai/daydreams/blob/main/packages/mongo/README.md
Provides a comprehensive TypeScript example for setting up an agent using the new MongoDB memory system. It includes initialization, connectivity testing, and agent creation.
```typescript
import { createMongoMemory } from "@daydreamsai/mongo";
import { createDreams } from "@daydreamsai/core";
async function setupAgent() {
// Create MongoDB memory system
const memory = createMongoMemory({
uri: process.env.MONGODB_URI!,
dbName: "my_agent_memory",
collectionName: "agent_kv_data"
});
// Initialize the memory system
await memory.initialize();
// Test connectivity
const health = await memory.kv.health();
if (health.status !== "healthy") {
throw new Error(`MongoDB unhealthy: ${health.message}`);
}
// Create agent
const agent = createDreams({
memory,
// ... other configuration
});
return agent;
}
// Usage
const agent = await setupAgent();
```
--------------------------------
### SDK Integration
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/router/quickstart.mdx
Guides for integrating with the Daydreams API using compatible SDKs, including OpenAI-compatible SDKs and the specific Dreams SDK.
```APIDOC
## SDK Integration
### OpenAI SDK Compatible
The Daydreams Router is designed to be compatible with the OpenAI SDKs. You can use your existing OpenAI client by configuring the `base_url` to point to the Daydreams API endpoint.
#### Python Example
```python
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://router.daydreams.systems/v1"
)
response = client.chat.completions.create(
model="google-vertex/gemini-2.5-flash",
messages=[{"role": "user", "content": "Hello!"}]
)
```
#### JavaScript Example
```javascript
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "YOUR_API_KEY",
baseURL: "https://router.daydreams.systems/v1",
});
const response = await client.chat.completions.create({
model: "google-vertex/gemini-2.5-flash",
messages: [{ role: "user", content: "Hello!" }],
});
```
### Dreams SDK Integration
For TypeScript projects, especially those using the Vercel AI SDK, refer to the [Dreams SDK guide](./dreams-sdk) for detailed integration instructions, including payment support.
```
--------------------------------
### Initialize Project and Install Dependencies
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/tutorials/x402/server.mdx
Sets up the project directory and installs necessary packages for the AI nanoservice, including Daydreams, OpenAI SDK, Hono, and x402 middleware. Requires Bun to be installed.
```bash
mkdir ai-nanoservice
cd ai-nanoservice
bun init -y
bun add @daydreamsai/core @ai-sdk/openai hono @hono/node-server x402-hono dotenv zod
```
--------------------------------
### Fetch Available Models via cURL
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/router/quickstart.mdx
This command retrieves a list of all available models supported by the Dreams Router. It requires an authorization header with your API key and sends a GET request to the /v1/models endpoint.
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api-beta.daydreams.systems/v1/models
```
--------------------------------
### Daydreams Development Setup (Bash)
Source: https://github.com/daydreamsai/daydreams/blob/main/CONTRIBUTING.md
Commands to set up the Daydreams development environment. This includes cloning the repository, installing dependencies, building packages, running tests, linting, and type checking.
```bash
git clone https://github.com/YOUR_USERNAME/daydreams.git
cd daydreams
git remote add upstream https://github.com/daydreamsai/daydreams.git
pnpm install
pnpm build:packages
pnpm test
pnpm lint
pnpm typecheck
```
--------------------------------
### Initialize Project and Install Core Packages (Manual Install)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/installation.mdx
Manually set up a Daydreams project by initializing the package manager, then adding core TypeScript and Daydreams packages. Supports pnpm, npm, bun, and yarn.
```bash
# pnpm
pnpm init -y
pnpm add typescript tsx @types/node @daydreamsai/core @daydreamsai/cli
```
```bash
# npm
npm init -y
npm install typescript tsx @types/node @daydreamsai/core @daydreamsai/cli
```
```bash
# bun
bun init -y
bun add typescript tsx @types/node @daydreamsai/core @daydreamsai/cli
```
```bash
# yarn
yarn init -y
yarn add typescript tsx @types/node @daydreamsai/core @daydreamsai/cli
```
--------------------------------
### Configuration Examples
Source: https://github.com/daydreamsai/daydreams/blob/main/packages/chroma/README.md
Illustrative examples of configuring the memory system for different scenarios like embedded mode, remote server with authentication, and custom embedding functions.
```APIDOC
## Configuration Examples
### Embedded Mode (No Server)
```typescript
const memory = createChromaMemory({
// No path specified - runs embedded
collectionName: "my_collection"
});
```
### Remote Server with Auth
```typescript
const memory = createChromaMemory({
path: "https://my-chroma-server.com",
auth: {
provider: "token",
credentials: process.env.CHROMA_TOKEN
}
});
```
### Custom Embedding Function
```typescript
import { OpenAIEmbeddingFunction } from "chromadb";
const memory = createChromaMemory({
path: "http://localhost:8000",
embeddingFunction: new OpenAIEmbeddingFunction({
openai_api_key: process.env.OPENAI_API_KEY!,
openai_model: "text-embedding-3-large" // Higher quality embeddings
})
});
```
```
--------------------------------
### Run Development Server (Bash)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/README.md
Commands to start the development server for the DaydreamsAI project using npm, pnpm, or yarn. Assumes Node.js and a package manager are installed.
```bash
npm run dev
# or
pnpm dev
# or
yarn dev
```
--------------------------------
### Install and Use @daydreamsai/create-agent CLI
Source: https://github.com/daydreamsai/daydreams/blob/main/packages/create-agent/README.md
Demonstrates how to install and use the @daydreamsai/create-agent CLI tool. It shows the recommended npx method and global installation via npm. This tool is used to bootstrap new Daydreams agents.
```bash
# Using npx (recommended)
npx @daydreamsai/create-agent my-agent
# Or install globally
npm install -g @daydreamsai/create-agent
create-agent my-agent
```
--------------------------------
### Generate x402 Payment Header with Node.js SDK
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/router/quickstart.mdx
This example demonstrates how to generate an x402-compliant payment header using the Daydreams AI SDK for Node.js. It requires a private key and specifies the amount and network for the USDC micropayment.
```javascript
import { generateX402Payment } from "@daydreamsai/ai-sdk-provider";
import { privateKeyToAccount } from "viem/accounts";
const account = privateKeyToAccount("0x...your-private-key");
// Generate x402-compliant payment header
const paymentHeader = await generateX402Payment(account, {
amount: "100000", // $0.10 USDC (6 decimals)
network: "base-sepolia", // or "base" for mainnet
});
// Make request with X-Payment header
const response = await fetch(
"https://router.daydreams.systems/v1/chat/completions",
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Payment": paymentHeader, // x402-compliant payment
},
body: JSON.stringify({
model: "google-vertex/gemini-2.5-flash",
messages: [{ role: "user", content: "Hello!" }],
}),
}
);
```
--------------------------------
### Create First Agent File (index.ts)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/installation.mdx
Define your first Daydreams agent using the core SDK. This example initializes an agent with OpenAI's GPT-4o model and the CLI extension, setting the log level to DEBUG.
```typescript
import { createDreams, LogLevel } from "@daydreamsai/core";
import { cliExtension } from "@daydreamsai/cli";
import { openai } from "@ai-sdk/openai";
const agent = createDreams({
logLevel: LogLevel.DEBUG,
model: openai("gpt-4o"),
extensions: [cliExtension],
});
// Start the agent
await agent.start();
```
--------------------------------
### Generate x402 Payment Header in Browser with Wagmi
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/router/quickstart.mdx
This example shows how to generate an x402 payment header in a browser environment using wagmi hooks and the Daydreams AI SDK. It requires the user's address and the `signTypedDataAsync` function for signing.
```javascript
import { generateX402PaymentBrowser } from "@daydreamsai/ai-sdk-provider";
import { useAccount, useSignTypedData } from "wagmi";
const { address } = useAccount();
const { signTypedDataAsync } = useSignTypedData();
const paymentHeader = await generateX402PaymentBrowser(
address,
signTypedDataAsync,
{ amount: "100000", network: "base-sepolia" }
);
// Use paymentHeader in X-Payment header
```
--------------------------------
### Quick Start: Create Agent with Firebase Memory
Source: https://github.com/daydreamsai/daydreams/blob/main/packages/firebase/README.md
Demonstrates the complete setup process, from initializing Firebase memory with optional configurations like collection name to creating a DaydreamsAI agent using this memory.
```typescript
import { createDreams } from "@daydreamsai/core";
import { createFirebaseMemory } from "@daydreamsai/firebase";
// Create memory system
const memory = createFirebaseMemory({
serviceAccount: {
projectId: "your-project-id",
clientEmail: "your-service-account@your-project.iam.gserviceaccount.com",
privateKey: process.env.FIREBASE_PRIVATE_KEY!
},
collectionName: "daydreams_kv", // optional, defaults to "kv_store"
});
// Initialize the memory system
await memory.initialize();
// Create agent with Firebase memory
const agent = createDreams({
memory,
// ... other config
});
```
--------------------------------
### Install @daydreamsai/core
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/api/api-reference.md
Installs the core framework package using npm. This is the first step to integrate the library into your project.
```bash
npm install @daydreamsai/core
```
--------------------------------
### Install Dreams SDK Provider (Bash)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/router/dreams-sdk.mdx
Installs the necessary packages for the Dreams AI SDK provider, including '@daydreamsai/ai-sdk-provider', 'viem', and 'x402'.
```bash
npm install @daydreamsai/ai-sdk-provider viem x402
```
--------------------------------
### Installation
Source: https://github.com/daydreamsai/daydreams/blob/main/packages/chroma/README.md
Install the @daydreamsai/chroma package along with chromadb.
```APIDOC
## Installation
```bash
pnpm add @daydreamsai/chroma chromadb
```
```
--------------------------------
### Install @daydreamsai/chroma and chromadb
Source: https://github.com/daydreamsai/daydreams/blob/main/packages/chroma/README.md
Installs the necessary packages for integrating ChromaDB with the DaydreamsAI memory system using pnpm.
```bash
pnpm add @daydreamsai/chroma chromadb
```
--------------------------------
### Chat Completions Response Format Example
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/router/quickstart.mdx
This JSON object shows the standard response format for the chat completions endpoint, which mirrors the OpenAI format. It includes fields for the completion ID, model, creation timestamp, message choices, and token usage statistics.
```json
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"model": "google-vertex/gemini-2.5-flash",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Quantum computing is a type of computing that uses quantum mechanical phenomena..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 20,
"completion_tokens": 150,
"total_tokens": 170
}
}
```
--------------------------------
### Providing Examples for Output Usage
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/concepts/outputs.mdx
Provides example usage strings for an output, demonstrating how it might be invoked in different scenarios. This aids developers in understanding how to correctly format calls to the output.
```string
examples: [
'',
'',
];
```
--------------------------------
### Install and Run ChromaDB with Python
Source: https://github.com/daydreamsai/daydreams/blob/main/packages/chroma/README.md
Installs ChromaDB using pip and then runs the server process, making it accessible on host 0.0.0.0 and port 8000. This is an alternative to using Docker.
```bash
pip install chromadb
chroma run --host 0.0.0.0 --port 8000
```
--------------------------------
### Configuring OpenAI Models in Daydreams
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/providers/ai-sdk.mdx
Provides examples of how to configure different OpenAI models (gpt-4o-mini, gpt-4o, gpt-3.5-turbo) within the Daydreams AI SDK. It includes the installation command and links to get API keys.
```typescript
// Install: npm install @ai-sdk/openai
import { openai } from "@ai-sdk/openai";
model: openai("gpt-4o-mini"); // Fast, cheap
model: openai("gpt-4o"); // Most capable
model: openai("gpt-3.5-turbo"); // Legacy but cheap
```
--------------------------------
### OpenRouter Provider Setup (TypeScript)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/providers/ai-sdk.mdx
Demonstrates how to set up and use the OpenRouter provider with the AI SDK. It requires installing the '@openrouter/ai-sdk-provider' package and provides examples for initializing models like Claude 3 Opus, Gemini Pro, and Llama 3.
```typescript
// Install: npm install @openrouter/ai-sdk-provider
import { openrouter } from "@openrouter/ai-sdk-provider";
model: openrouter("anthropic/claude-3-opus");
model: openrouter("google/gemini-pro");
model: openrouter("meta-llama/llama-3-70b");
// And 100+ more models!
```
--------------------------------
### Running the Multi-Context Wallet Example
Source: https://github.com/daydreamsai/daydreams/blob/main/examples/CDP/server-wallet/README.md
Executes the multi-context wallet example using the Bun runtime. This command initiates the server wallet application, allowing for wallet creation, management, and transactions across different EVM networks.
```bash
bun run examples/CDP/server-wallet/multi-context-wallet.tsx
```
--------------------------------
### Configuring Google (Gemini) Models in Daydreams
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/providers/ai-sdk.mdx
Details the setup for using Google's Gemini models (Gemini 1.5 Flash, Gemini 1.5 Pro) within Daydreams via the AI SDK. Includes the installation command and instructions for getting Google API keys.
```typescript
// Install: npm install @ai-sdk/google
import { google } from "@ai-sdk/google";
model: google("gemini-1.5-flash"); // Fast, cheap
model: google("gemini-1.5-pro"); // More capable
```
--------------------------------
### Daydreams AI Agent: Full-Featured Example (TypeScript)
Source: https://context7.com/daydreamsai/daydreams/llms.txt
This TypeScript code defines a complete Daydreams AI agent. It includes defining custom contexts for analytics and customer support, composing contexts, setting up actions, installing extensions like logging, and managing the agent's lifecycle from start to stop. The example also demonstrates sending messages to the agent, accessing results and memory, and retrieving conversation history.
```typescript
import { createDreams, context, action, extension } from "@daydreamsai/core";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
// 1. Define analytics context
const analyticsContext = context({
type: "analytics",
schema: z.object({ userId: z.string() }),
create: () => ({
events: [],
sessionStart: Date.now(),
}),
}).setActions([
action({
name: "trackEvent",
schema: z.object({
event: z.string(),
properties: z.record(z.any()).optional(),
}),
async handler({ event, properties }, ctx) {
ctx.memory.events.push({
event,
properties,
timestamp: Date.now(),
});
return { tracked: true };
},
}),
]);
// 2. Define customer support context with composition
const supportContext = context({
type: "support",
schema: z.object({
customerId: z.string(),
tier: z.enum(["free", "premium"]),
}),
create: () => ({
tickets: [],
satisfaction: null,
}),
instructions: (state) => `
You are a ${state.args.tier} customer support agent.
Be helpful and track all interactions.
For premium customers, offer advanced solutions.
`,
})
.use((state) => [
// Compose with analytics
{ context: analyticsContext, args: { userId: state.args.customerId } },
])
.setActions([
action({
name: "createTicket",
schema: z.object({
title: z.string(),
description: z.string(),
priority: z.enum(["low", "medium", "high"]),
}),
async handler({ title, description, priority }, ctx, agent) {
const ticketId = `ticket-${Date.now()}`;
ctx.memory.tickets.push({
id: ticketId,
title,
description,
priority,
status: "open",
createdAt: Date.now(),
});
// Track event in composed analytics context
await ctx.callAction("trackEvent", {
event: "ticket_created",
properties: { ticketId, priority },
});
return { ticketId, created: true };
},
}),
action({
name: "searchKnowledgeBase",
schema: z.object({ query: z.string() }),
async handler({ query }, ctx, agent) {
const results = await agent.memory.vector.search({
query,
namespace: "knowledge-base",
topK: 5,
});
return { results: results.map((r) => r.content) };
},
}),
]);
// 3. Define custom extension
const loggingExtension = extension({
name: "logging",
async install(agent) {
agent.logger.info("Logging extension installed");
// Subscribe to all context events
agent.on("context:created", (ctx) => {
agent.logger.info(`Context created: ${ctx.id}`);
});
},
});
// 4. Create agent with full configuration
const agent = createDreams({
model: openai("gpt-4o"),
modelSettings: {
temperature: 0.7,
maxTokens: 2000,
},
contexts: [supportContext],
extensions: [loggingExtension],
tasks: {
concurrency: { default: 5, llm: 2 },
},
});
// 5. Start and run
await agent.start();
// 6. Handle customer support request
const result = await agent.send({
context: supportContext,
args: { customerId: "cust-123", tier: "premium" },
input: {
type: "text",
data: "I need help with my billing, I was charged twice this month.",
},
});
// 7. Access results
console.log("Response:", result.outputs);
console.log("Actions called:", result.workingMemory.calls);
console.log("Context state:", result.state.memory);
// 8. Continue conversation
await agent.send({
context: supportContext,
args: { customerId: "cust-123", tier: "premium" },
input: {
type: "text",
data: "Can you create a ticket for this issue?",
},
});
// 9. Retrieve conversation history
const workingMemory = await agent.getWorkingMemory("support:cust-123");
console.log("Full conversation:", {
inputs: workingMemory.inputs.length,
outputs: workingMemory.outputs.length,
actions: workingMemory.calls.length,
});
// 10. Search similar issues
const similarIssues = await agent.memory.recall("billing charged twice", {
contextId: "support:cust-123",
topK: 5,
});
// 11. Cleanup
await agent.stop();
```
--------------------------------
### Run Client Examples with Bun
Source: https://github.com/daydreamsai/daydreams/blob/main/examples/x402/nanoservice/README.md
Executes example client requests to interact with the AI assistant service. This command is used for testing the service's functionality and API endpoints.
```bash
bun run client:examples
```
--------------------------------
### Start Server (Command Line)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/tutorials/x402/server.mdx
This bash command initiates the server using the Bun runtime. It's the standard way to start the Daydreams AI nanoservice application, making it available for incoming requests.
```bash
bun run server.ts
```
--------------------------------
### Best Practices
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/router/quickstart.mdx
Recommended guidelines for effectively using the Daydreams AI API to improve performance, manage costs, and enhance user experience.
```APIDOC
## Best Practices
1. **Use System Messages**: Define the AI's behavior and context by including a system message at the beginning of the `messages` array.
2. **Set Max Tokens**: Specify the `max_tokens` parameter to control the length of the generated response and manage costs.
3. **Handle Streaming**: For potentially long responses, implement streaming to provide a better user experience by displaying content as it's generated.
4. **Implement Retries**: For transient network or server errors, implement an exponential backoff strategy for retrying requests.
5. **Monitor Usage**: Regularly check your token usage to effectively manage and control associated costs.
6. **Cache Responses**: Consider implementing a caching mechanism for frequently asked questions or identical queries to reduce redundant API calls and save costs.
```
--------------------------------
### JavaScript Example: Paid AI Request with x402-fetch
Source: https://github.com/daydreamsai/daydreams/blob/main/examples/x402/nanoservice/README.md
Demonstrates making a paid request to the AI assistant using `x402-fetch`. This example shows how to wrap the standard `fetch` API with payment handling capabilities, including automatic payment processing and retrieving payment details from response headers.
```javascript
import { wrapFetchWithPayment } from "x402-fetch";
import { privateKeyToAccount } from "viem/accounts";
// Create payment-enabled fetch
const account = privateKeyToAccount(privateKey);
const fetchWithPayment = wrapFetchWithPayment(fetch, account);
// Make a paid request - payment is handled automatically
const response = await fetchWithPayment("http://localhost:4021/assistant", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query: "Hello AI!" }),
});
// Get payment details
const paymentInfo = decodeXPaymentResponse(
response.headers.get("x-payment-response")
);
console.log("Payment:", paymentInfo);
```
--------------------------------
### LLM Response Example (XML)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/concepts/prompting.mdx
Shows the structured XML response format from an LLM, including reasoning, action calls, and output messages. This response guides the Daydreams system's subsequent actions.
```xml
The user is asking about weather in Boston. I should:
1. Call the getWeather action to get current conditions
2. Send the result to Discord
{"city": "Boston"}
```
--------------------------------
### Run the Daydreams AI Assistant Server
Source: https://github.com/daydreamsai/daydreams/blob/main/examples/x402/nanoservice/README.md
Starts the Daydreams AI assistant service. The server will be accessible on port 4021 by default, enabling API requests.
```bash
bun run dev
```
--------------------------------
### Quick Start: Create and Run an AI Agent
Source: https://github.com/daydreamsai/daydreams/blob/main/packages/core/README.md
Demonstrates how to create and run a basic AI agent using @daydreamsai/core. It includes defining a chat context, a search action, initializing the agent with a language model, and sending a message.
```typescript
import { createDreams, context, action } from "@daydreamsai/core";
import { openai } from "@ai-sdk/openai";
import * as z from "zod";
// Define a context
const chatContext = context({
type: "chat",
schema: z.object({
userId: z.string(),
}),
});
// Define an action
const searchAction = action({
name: "search",
description: "Search the web",
schema: z.object({
query: z.string(),
}),
handler: async ({ call }) => {
// Implement search logic
return { results: ["result1", "result2"] };
},
});
// Create agent
const agent = createDreams({
model: openai("gpt-4"),
contexts: [chatContext],
actions: [searchAction],
});
// Start the agent
await agent.start();
// Send a message
const response = await agent.send({
context: chatContext,
args: { userId: "user123" },
input: { type: "text", data: "Search for AI news" },
});
```
--------------------------------
### Setting up Daydreams Router for 100+ Models
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/providers/ai-sdk.mdx
Demonstrates how to set up the Daydreams Router, which provides access to over 100 AI models through a single interface. It includes the installation command and an example of specifying a Google Gemini model.
```typescript
// Install: npm install @daydreamsai/ai-sdk-provider
import { dreamsrouter } from "@daydreamsai/ai-sdk-provider";
model: dreamsrouter("google/gemini-pro");
```
--------------------------------
### Quick Start: Create and Run an AI Agent
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/api/api-reference.md
Demonstrates how to create a stateful AI agent using @daydreamsai/core. It includes defining a chat context, a web search action, initializing the agent with a model and actions, starting it, and sending a message for a response.
```typescript
import { createDreams, context, action } from '@daydreamsai/core';
import { openai } from '@ai-sdk/openai';
import * as z from 'zod';
// Define a context
const chatContext = context({
type: 'chat',
schema: z.object({
userId: z.string()
})
});
// Define an action
const searchAction = action({
name: 'search',
description: 'Search the web',
schema: z.object({
query: z.string()
}),
handler: async ({ call }) => {
// Implement search logic
return { results: ['result1', 'result2'] };
}
});
// Create agent
const agent = createDreams({
model: openai('gpt-4'),
contexts: [chatContext],
actions: [searchAction]
});
// Start the agent
await agent.start();
// Send a message
const response = await agent.send({
context: chatContext,
args: { userId: 'user123' },
input: { type: 'text', data: 'Search for AI news' }
});
```
--------------------------------
### Format of Streaming Responses (SSE)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/router/quickstart.mdx
This example illustrates the structure of Server-Sent Events (SSE) when streaming responses. Each 'data' line contains a JSON object representing a chunk of the completion, with the final chunk indicating completion.
```text
data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677652288,"model":"google-vertex/gemini-2.5-flash","choices":[{"index":0,"delta":{"content":"Once"},"finish_reason":null}]}
data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677652288,"model":"google-vertex/gemini-2.5-flash","choices":[{"index":0,"delta":{"content":" upon"},"finish_reason":null}]}
data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677652288,"model":"google-vertex/gemini-2.5-flash","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
```
--------------------------------
### Chat Completions Request Schema Example
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/router/quickstart.mdx
This JSON object illustrates a complete request payload for the chat completions endpoint. It includes required fields like `model` and `messages`, as well as optional parameters such as `temperature` and `max_tokens`.
```json
{
"model": "google-vertex/gemini-2.5-flash",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Explain quantum computing in simple terms."
}
],
"temperature": 0.7,
"max_tokens": 500,
"stream": false
}
```
--------------------------------
### Create Production Environment File
Source: https://github.com/daydreamsai/daydreams/blob/main/examples/x402/nanoservice/README.md
Copies the development environment file to a production environment file. This is a common practice to separate configurations for different deployment stages.
```bash
# Create production environment file
cp .env .env.production
# Edit .env.production with your production keys
vim .env.production
```
--------------------------------
### Development Commands for @daydreamsai/create-agent
Source: https://github.com/daydreamsai/daydreams/blob/main/packages/create-agent/README.md
Provides essential commands for developers working on the @daydreamsai/create-agent package. Includes installing dependencies, building the package, and running the CLI locally for testing.
```bash
# Install dependencies
pnpm install
# Build the package
pnpm run build
# Test the CLI locally
pnpm run start
```
--------------------------------
### Configuring Groq (Ultra-Fast) Models in Daydreams
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/providers/ai-sdk.mdx
Explains how to integrate Groq's ultra-fast models, such as Llama and Mixtral, into Daydreams using the AI SDK. Provides the installation command, a factory function example, and links for Groq API keys.
```typescript
// Install: npm install @ai-sdk/groq
import { createGroq } from "@ai-sdk/groq";
const groq = createGroq();
model: groq("llama3-70b-8192"); // Fast Llama
model: groq("mixtral-8x7b-32768"); // Fast Mixtral
```
--------------------------------
### Bash Script for Daydreams Development Setup
Source: https://github.com/daydreamsai/daydreams/blob/main/readme.md
This bash script automates the process of cloning the Daydreams repository, installing dependencies using pnpm, initiating a watch build, and running tests with bun. It's essential for developers setting up the project locally.
```bash
git clone https://github.com/daydreamsai/daydreams.git
cd daydreams
pnpm install
./scripts/build.sh --watch
bun run packages/core # Run tests
```
--------------------------------
### Example package.json for DaydreamsAI Extension
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/concepts/extensions.mdx
A sample package.json file for a DaydreamsAI extension, specifying the package name, version, main entry points, and peer dependencies on the DaydreamsAI core library.
```json
{
"name": "@yourorg/daydreams-weather",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"peerDependencies": {
"@daydreamsai/core": "^1.0.0"
}
}
```
--------------------------------
### Develop Documentation Site
Source: https://github.com/daydreamsai/daydreams/blob/main/CLAUDE.md
Starts a local development server for the documentation site, which is built using Next.js. Allows for live previewing of documentation changes.
```bash
cd docs && bun run dev
```
--------------------------------
### Inefficient Action Without Services (TypeScript)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/concepts/services.mdx
Shows an example of an action handler in TypeScript that inefficiently manages its own connections. It demonstrates creating a new Discord client and logging in on every execution, leading to slow performance and repetitive setup. This highlights the problem that services aim to solve.
```typescript
// ❌ Actions manage their own connections (slow, repetitive)
const sendMessageAction = action({
handler: async ({ channelId, message }) => {
// Create new client every time!
const client = new Discord.Client({ token: process.env.DISCORD_TOKEN });
await client.login(); // Slow connection each time
await client.channels.get(channelId).send(message);
await client.destroy();
},
});
```
--------------------------------
### List Available Models API
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/router/quickstart.mdx
Retrieve a comprehensive list of all available AI models supported by Daydreams Router, including details on their capabilities and pricing.
```APIDOC
## GET /v1/models
### Description
Retrieves a list of all available models supported by the Daydreams Router, along with their capabilities and pricing information.
### Method
GET
### Endpoint
`https://api-beta.daydreams.systems/v1/models`
### Parameters
No parameters are required for this endpoint.
### Request Example
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api-beta.daydreams.systems/v1/models
```
### Response
#### Success Response (200)
- **`data`** (array of objects) - A list of model objects, each containing details like model ID, capabilities, and pricing.
#### Response Example
```json
{
"data": [
{
"id": "google-vertex/gemini-2.5-flash",
"object": "model",
"created": 1677652288,
"owned_by": "google",
"capabilities": {
"chat": true,
"completions": true,
"streaming": true
},
"pricing": {
"prompt_tokens": 0.000125,
"completion_tokens": 0.000375
}
}
// ... other models
]
}
```
```
--------------------------------
### Complete Agent Flow Example (TypeScript)
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/core/concepts/building-blocks.mdx
This TypeScript snippet illustrates the complete flow of a Daydreams agent, starting with sending an input to a specific context and demonstrating the subsequent steps of input processing, context preparation, LLM reasoning, action execution, and output generation.
```typescript
// 1. Input creates InputRef and triggers agent.send()
await agent.send({
context: chatContext,
args: { userId: "alice" },
input: { type: "text", data: "What's the weather in NYC?" }
});
```
--------------------------------
### Deploy AI Assistant Manually with Daydreams CLI
Source: https://github.com/daydreamsai/daydreams/blob/main/examples/x402/nanoservice/README.md
Provides instructions for manually deploying the AI assistant service using the Daydreams deploy CLI. This method offers more control over deployment parameters such as name, project, region, and resource allocation.
```bash
# Install the Daydreams deploy CLI
pnpm add -g @daydreamsai/deploy
# Deploy the service
daydreams-deploy deploy \
--name ai-assistant \
--project your-gcp-project \
--region us-central1 \
--file server.ts \
--env .env.production \
--memory 512Mi \
--max-instances 10
```
--------------------------------
### Run Daydreams AI Agent using Bash Script
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/tutorials/basic/multi-context-agent.mdx
This bash script is used to execute the TypeScript agent code. Ensure that your OPENAI_API_KEY environment variable is properly set before running this script. The command assumes Node.js is installed and the agent file is named 'agent.ts'.
```bash
node agent.ts
```
--------------------------------
### Create Multi-Context AI Agent with TypeScript
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/tutorials/basic/multi-context-agent.mdx
This TypeScript code defines an AI agent that can handle multiple contexts, specifically an 'echo' context and a 'fetch' context for interacting with the JSONPlaceholder API. It utilizes @daydreamsai/core, @daydreamsai/cli, and @ai-sdk/openai. The agent is configured with a model and extensions, and its contexts are registered before being started and run.
```typescript
import { createDreams, context, input, output } from "@daydreamsai/core";
import { cliExtension } from "@daydreamsai/cli";
import { openai } from "@ai-sdk/openai";
import * as z from "zod";
const fetchContext = context({
type: "fetch",
schema: z.object({}),
instructions:
"You are a helpful assistant that can fetch data from a test API. When asked, fetch and display data from the JSONPlaceholder API.",
actions: {
fetchPosts: {
schema: z.object({
limit: z.number().optional().default(5),
}),
description: "Fetch posts from the test API",
handler: async ({ limit }) => {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
const posts = await response.json();
return posts.slice(0, limit);
},
},
fetchUser: {
schema: z.object({
userId: z.number(),
}),
description: "Fetch a specific user by ID",
handler: async ({ userId }) => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`
);
return response.json();
},
},
},
});
// 1. Define the main context for our agent
const echoContext = context({
type: "echo",
// No specific arguments needed for this simple context
schema: z.object({}),
instructions:
"You are a simple echo bot. Repeat the user's message back to them.",
});
// 2. Create the agent instance
const agent = createDreams({
// Configure the LLM model to use
model: openai("gpt-4o-mini"),
// Include the CLI extension for input/output handling
extensions: [cliExtension],
// Register our custom context
contexts: [echoContext, fetchContext],
});
// 3. Start the agent and run the context
async function main() {
// Initialize the agent (sets up services like readline)
await agent.start();
console.log("Multi-context agent started. Type 'exit' to quit.");
console.log("Available contexts:");
console.log("1. Echo context - repeats your messages");
console.log("2. Fetch context - fetches data from JSONPlaceholder test API");
console.log("");
// You can run different contexts based on user choice
// For this example, we'll run the fetch context
await agent.run({
context: fetchContext,
args: {}, // Empty object since our schema requires no arguments
});
// Agent stops when the input loop breaks
console.log("Agent stopped.");
}
// Start the application
main();
```
--------------------------------
### Make First API Call to Chat Completions Endpoint
Source: https://github.com/daydreamsai/daydreams/blob/main/docs/content/docs/router/quickstart.mdx
This cURL command demonstrates how to make a POST request to the `/v1/chat/completions` endpoint. It includes the necessary headers for content type and authorization, along with a JSON payload for the request.
```bash
curl -X POST https://router.daydreams.systems/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "google-vertex/gemini-2.5-flash",
"messages": [
{
"role": "user",
"content": "Hello, how are you?"
}
],
"stream": false
}'
```