Getting Started

Quick Start

Get up and running with Fold SDK in under 5 minutes.

1. Install the SDK

npm install @fold/sdk

2. Basic Usage

The easiest way to use Fold is with the fold() function:

import { fold } from '@fold/sdk'

const ctx = fold()  // That's it!

// Add content to your context
ctx.system("You are a helpful assistant")
ctx.think("I need to search for information...")
ctx.act({ tool: "search", query: "fold sdk" }, "search")
ctx.observe("Found 3 results about context optimization...", "search")

// Get optimized messages for your LLM
const messages = ctx.messages()
// Use with OpenAI, Anthropic, or any LLM API

3. With an LLM

Here's a complete example with OpenAI:

import OpenAI from 'openai'
import { fold } from '@fold/sdk'

const openai = new OpenAI()
const ctx = fold("coding")  // Use the coding preset

ctx.system("You are a coding assistant with access to tools.")

// Agent loop
while (true) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: ctx.messages(),  // Optimized!
    tools: myTools,
  })

  const message = response.choices[0].message

  if (message.tool_calls?.length) {
    for (const call of message.tool_calls) {
      ctx.act(JSON.parse(call.function.arguments), call.function.name)
      const result = await executeTool(call)
      ctx.observe(result, call.function.name)
    }
  } else {
    ctx.think(message.content)
  }

  // Stop on loops, failures, or goal completion
  if (ctx.stop()) {
    console.log("Stopping:", ctx.reason())
    break
  }
}

// Check your savings
console.log(ctx.saved())
// { tokens: 45000, percent: 68, cost: 0.45 }

4. Choose a Preset

Fold comes with presets optimized for different use cases:

fold()              // Default: 100K budget, 10 turn window
fold("chat")        // 32K budget, 20 turn window
fold("coding")      // 100K budget, 15 turn window
fold("research")    // 128K budget, 10 turn window
fold("long-running") // 200K budget, 8 turn window

// Or custom
fold({
  budget: 50_000,
  model: "gpt-4o",
  window: 15
})

5. Monitor Your Savings

Track how much Fold is saving you:

// Quick savings check
console.log(ctx.saved())
// { tokens: 5000, percent: 45, cost: 0.05 }

// Detailed stats
console.log(ctx.stats())
// {
//   turnCount: 25,
//   totalTokens: 12000,
//   maskedTokens: 7000,
//   summarizedTokens: 0,
//   compressionRatio: 0.58
// }

Next Steps