Project Structure

A typical SpinAI project is simple and focused:

my-spinai-app/
├── src/
│   ├── actions/         # Your AI actions
│   │   └── getWeather.ts
│   └── index.ts        # Agent configuration
├── .env                # Environment variables
└── package.json

Creating Actions

Actions are the building blocks of your AI agent. Each action is created using the createAction helper:

import { createAction } from "spinai";

export const getWeather = createAction({
  id: "getWeather",
  description: "Get the current weather for a location",
  dependsOn: [], // Optional dependencies
  async run(context) {
    // Implement your action logic
    context.state.weather = { temp: 72, condition: "sunny" };
    return context;
  },
});

Context and State

Each action receives a context object that includes:

  • input: The user’s original request
  • state: Shared state between actions
  • Access to results from previous actions

Creating an Agent

Agents coordinate actions to achieve user goals:

import { createAgent, createOpenAILLM } from "spinai";
import { getWeather } from "./actions/getWeather";

const weatherAgent = createAgent({
  instructions: "Help users with weather information",
  actions: [getWeather],
  llm: createOpenAILLM({
    apiKey: process.env.OPENAI_API_KEY,
  }),
});

Dependency Management

SpinAI automatically handles action dependencies using a DAG (Directed Acyclic Graph):

const createTicket = createAction({
  id: "createTicket",
  description: "Creates a support ticket",
  dependsOn: ["getCustomerInfo"], // This action runs after getCustomerInfo
  async run(context) {
    const { customerInfo } = context.state;
    // Create ticket using customer info...
    return context;
  },
});

Best Practices

  1. Clear Action Names: Use descriptive IDs and descriptions
  2. Single Responsibility: Each action should do one thing well
  3. State Management: Use context.state to share data between actions
  4. Error Handling: Add retries for unreliable operations
  5. Dependencies: Explicitly declare action dependencies

Next Steps