SpinAI Framework

repository·main·Indexed 43 days ago

https://github.com/fallomai/spinai

A lightweight TypeScript framework for building AI agents. SpinAI provides scaffolding tools via the `create-spinai` CLI and templates for deploying agents with various LLM providers, including specialized templates for Machine Control Protocol (MCP) agents, GitHub code reviews, and Mintlify documentation updates.

Tokens
30K
Snippets
104
Records
134
Agent score
55%

What's inside SpinAI

  1. What is SpinAI?

    main
    SpinAI is a lightweight TypeScript framework designed for building action-oriented AI agents. It allows developers to create agents that can execute actions in a specific order, maintain state between those actions, and make decisions using any LLM supported by Vercel's AI SDK. The framework is designed to handle complex dependencies and provides observability into the agent's state, actions, and decision-making processes throughout its lifecycle.
  2. Understand the difference between State and Parameters

    main

    SpinAI provides two distinct ways to handle data within an agent's lifecycle: Parameters and State. Choosing the right one depends on whether the data is dynamic/LLM-driven or static/persistent.

    Parameters

    Parameters are values passed into actions by the LLM during the task loop.

    • Nature: Dynamic and per-action.
    • Source: Determined by the LLM based on the action's parameters schema.
    • Use Case: Best for inputs the LLM needs to decide on (e.g., a specific number to add, a search query, or a quantity).
    • Lifecycle: Derived from previous action results and current state.

    State

    State is a persistent object used for data that lives across the entire interaction.

    • Nature: Persistent and static.
    • Access: Accessed via context.state inside actions, and via the state object returned after the agent finishes.
    • Modification: Can only be modified by your Actions.
    • Use Case: Best for values that shouldn't be guessed by an LLM, such as userId, userEmail, or session-specific configuration.
    FeatureParametersState
    Determined byLLM (via schema)Actions (via code)
    PersistencePer-action/Message historyAcross entire interaction
    Access after runNo (only in history)Yes (via returned state)
    Best forDynamic inputsStatic/Contextual data
  3. What are Actions in SpinAI?

    main
    Actions are the fundamental building blocks of SpinAI agents. They represent discrete, modular, and type-safe tasks that an agent can perform. Actions are parameter-driven, meaning they rely on schemas to define what data they need, and they are state-aware, meaning they can interact with the agent's runtime context.
  4. Use snippets to maintain DRY documentation

    main
    To follow the DRY (Don't Repeat Yourself) principle in your documentation, use custom snippets when you find yourself repeating the same content in multiple places. Creating a snippet allows you to keep your content in sync across different parts of your documentation by managing it in a single location.
  5. How the SpinAI Task Loop works

    main

    The Task Loop is the core decision-making engine of a SpinAI agent. It orchestrates the workflow by managing planning, action execution, and response generation.

    The Workflow Lifecycle

    1. Planning and Reasoning: The agent analyzes user input, current state, and previous results to decide which actions to run. It provides explicit reasoning and returns a list of action IDs with their required parameters.
    2. Parallel Action Execution: If actions are required, the loop executes them in parallel. Each action receives the full context and specific parameters. Results are captured and added to the conversation history.
    3. Response Generation: Once no further actions are needed, the agent generates a final response using the accumulated context and state. This response can be plain text or structured data, depending on your responseFormat configuration.

    Key Features

    • State Management: Maintains state throughout the entire interaction.
    • Parallelism: Maximizes efficiency by running non-dependent actions simultaneously.
    • Observability: Provides comprehensive logging, including reasoning steps, token usage, cost, and duration.
    • Error Recovery: Gracefully handles action execution errors by feeding error information back to the agent for potential recovery.
    graph TD
        A[Agent Called] --> B[Initialize Context & State]
        B --> C[Generate Planning Decision]
        C --> D{Actions Needed?}
        D -->|Yes| E[Execute Actions in Parallel]
        E --> F[Capture Results]
        F --> C
        D -->|No| G[Generate Final Response]
        G --> H[Return Response with State]
  6. What are Agents in SpinAI

    main
    Agents are the core building blocks of SpinAI. They combine a Large Language Model (LLM) with a set of actions to solve tasks by coordinating decision-making, managing state, and maintaining execution history. They decide which actions to call and what parameters to pass to them, mimicking a human decision-maker.
  7. How Agents work in SpinAI

    main

    An Agent is a self-contained, stateful entity in SpinAI. It is responsible for receiving user input, deciding which actions or tools to call, maintaining state between those calls, and returning text or custom JSON responses. Agents are decoupled from specific models and can use any LLM supported by Vercel's AI SDK for decision-making.

    To create an agent, use the createAgent function, providing instructions, a list of actions, and a model.

    const calculatorAgent = createAgent({
      instructions: `You are a calculator agent that helps users perform mathematical calculations.`,
      actions: [sum, minus],
      model: openai("gpt-4o"),
    });
  8. Compare Parameters vs. Context State

    main

    When designing actions, choose between using parameters or context.state based on how the data should be handled:

    FeatureParameterscontext.state
    SourceDynamically determined by the LLM during the task loop.Provided in initial call or set by previous actions.
    SchemaDefined by the action's parameters property.Unstructured/Dynamic object.
    AccessibilityAccessible via the agent's message history.Accessible during runtime and after the agent call completes.
    Best Use CaseDynamic values the LLM needs to calculate or extract.Robust, shared values like userId, email, or session tokens.

    Key Distinction: Returning a value from run() makes it available to the LLM to use as a parameter for other actions, but that value only lives in the message history. Setting context.state makes the value available to the system/runtime regardless of the message history.

  9. What metrics are tracked by SpinAI observability

    main

    When observability is enabled via agentId and spinApiKey, SpinAI automatically tracks the following data points:

    • Interactions: Agent interactions and their outcomes.
    • Model Usage: Token consumption and model-specific metrics.
    • Costs: Cost metrics calculated per interaction.
    • Performance: Response times and latency.
    • Reasoning: Evaluation steps and the agent's reasoning process.
    • Actions: Execution of actions and their specific results.
    • Errors: Error logs and failure cases.
  10. Technical components of the Task Loop

    main

    The Task Loop relies on four primary technical pillars to manage agent behavior:

    • Message History Management: Uses a structured conversation history containing system, user, assistant, and action result message types to drive the planning process.
    • Planning Schema: Employs a structured JSON schema for decisions, which must include reasoning, the next actions to take, and the specific parameters for those actions.
    • Error Handling: Captures errors during action execution and returns them to the agent, allowing the LLM to attempt recovery.
    • Comprehensive Logging: Records every step of the loop, including planning decisions, execution details, and performance metrics like token usage and costs.
  11. How Actions work in SpinAI

    main

    Actions are the functions or tools that an agent can call to perform tasks.

    Key characteristics of Actions:

    • Inputs/Outputs: They have clearly defined inputs (via parameters) and outputs.
    • State Access: They can maintain and access state through a provided context.
    • Dependencies: Actions can depend on other actions.
    • Execution Order: Actions are executed in Directed Acyclic Graph (DAG) order.

    To define an action, use the createAction function. You must provide a unique id, a description for the LLM to understand when to use it, a JSON Schema for parameters, and an asynchronous run function to execute the logic.

    export const sum = createAction({
      id: "sum",
      description: "Adds two numbers together.",
      parameters: {
        type: "object",
        properties: {
          a: { type: "number", description: "First number to add" },
          b: { type: "number", description: "Second number to add" },
        },
        required: ["a", "b"],
      },
      async run({ parameters }): Promise<number> {
        const { a, b } = parameters || {};
        return a + b;
      },
    });