SpinAI Framework
repository·main·Indexed 43 days ago
https://github.com/fallomai/spinaiA 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.
What's inside SpinAI
- 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.
Understand the difference between State and Parameters
mainSpinAI 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
parametersschema. - 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.stateinside actions, and via thestateobject 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.
Feature Parameters State Determined by LLM (via schema) Actions (via code) Persistence Per-action/Message history Across entire interaction Access after run No (only in history) Yes (via returned state)Best for Dynamic inputs Static/Contextual data What are Actions in SpinAI?
mainActions 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.Use snippets to maintain DRY documentation
mainTo 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.How the SpinAI Task Loop works
mainThe 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
- 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.
- 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.
- 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
responseFormatconfiguration.
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]What are Agents in SpinAI
mainAgents 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.How Agents work in SpinAI
mainAn 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
createAgentfunction, 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"), });Compare Parameters vs. Context State
mainWhen designing actions, choose between using parameters or
context.statebased on how the data should be handled:Feature Parameters context.stateSource Dynamically determined by the LLM during the task loop. Provided in initial call or set by previous actions. Schema Defined by the action's parametersproperty.Unstructured/Dynamic object. Accessibility Accessible via the agent's message history. Accessible during runtime and after the agent call completes. Best Use Case Dynamic 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. Settingcontext.statemakes the value available to the system/runtime regardless of the message history.What metrics are tracked by SpinAI observability
mainWhen observability is enabled via
agentIdandspinApiKey, 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.
Technical components of the Task Loop
mainThe Task Loop relies on four primary technical pillars to manage agent behavior:
- Message History Management: Uses a structured conversation history containing
system,user,assistant, andaction resultmessage 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.
- Message History Management: Uses a structured conversation history containing
How Actions work in SpinAI
mainActions 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
createActionfunction. You must provide a uniqueid, adescriptionfor the LLM to understand when to use it, a JSON Schema forparameters, and an asynchronousrunfunction 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; }, });How MCP actions work in SpinAI
mainSpinAI integrates with the Model Context Protocol (MCP), allowing you to incorporate platform actions into your AI agents without writing custom code. MCP actions are treated as regular SpinAI actions and can be composed within an agent's toolkit alongside native SpinAI actions. SpinAI currently supports all MCPs available on the Smithery MCP registry.