Getting Started

Multi-Context Agent

This guide will walk you through creating an AI agent that can respond to multiple contexts.

Prerequisites

  • OPENAI_API_KEY: Your OpenAI API key
agent.ts
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();

Run your agent

Ensure your OPENAI_API_KEY environment variable is set, then run:

run-agent.sh
node agent.ts