### List Contexts and Get Stats Source: https://github.com/superfly/contextwindow/blob/main/README.md Demonstrates how to retrieve all contexts and efficiently fetch statistics for each, including token counts and record numbers. This method is optimized for performance even with large histories. ```go // Get all contexts contexts, err := cw.ListContexts() if err != nil { log.Fatalf("Failed to list contexts: %v", err) } // Get efficient stats for each context (no table scans) for _, context := range contexts { stats, err := cw.GetContextStats(context) if err != nil { log.Printf("Failed to get stats for %s: %v", context.Name, err) continue } fmt.Printf("Context: %s\n", context.Name) fmt.Printf(" Created: %s\n", context.StartTime.Format("2006-01-02 15:04")) fmt.Printf(" Live tokens: %d\n", stats.LiveTokens) fmt.Printf(" Records: %d total, %d live\n", stats.TotalRecords, stats.LiveRecords) if stats.LastActivity != nil { fmt.Printf(" Last activity: %s\n", stats.LastActivity.Format("2006-01-02 15:04")) } else { fmt.Printf(" Last activity: never\n") } } ``` -------------------------------- ### Middleware for Tool Call Monitoring Source: https://context7.com/superfly/contextwindow/llms.txt Add middleware to intercept and log tool calls for debugging or analytics. This example defines a LoggingMiddleware to log tool call events. ```go package main import ( "context" "encoding/json" "fmt" "log" "github.com/openai/openai-go/v2/shared" "github.com/superfly/contextwindow" ) // LoggingMiddleware logs all tool calls type LoggingMiddleware struct{} func (m *LoggingMiddleware) OnToolCall(ctx context.Context, name, args string) { log.Printf("[TOOL CALL] %s(%s)", name, args) } func (m *LoggingMiddleware) OnToolResult(ctx context.Context, name, result string, err error) { if err != nil { log.Printf("[TOOL ERROR] %s: %v", name, err) } else { log.Printf("[TOOL RESULT] %s: %s", name, result[:min(100, len(result))]) } } func main() { ctx := context.Background() model, _ := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) db, _ := contextwindow.NewContextDB(":memory:") defer db.Close() cw, _ := contextwindow.NewContextWindow(db, model, "middleware-demo") // Add middleware cw.AddMiddleware(&LoggingMiddleware{}) // Define a tool timeTool := contextwindow.NewTool("get_time", "Get the current time") cw.AddTool(timeTool, contextwindow.ToolRunnerFunc( func(ctx context.Context, args json.RawMessage) (string, error) { return "2024-01-15 10:30:00 UTC", nil }, )) cw.AddPrompt("What time is it?") response, _ := cw.CallModel(ctx) fmt.Println(response) // Logs: // [TOOL CALL] get_time({}) // [TOOL RESULT] get_time: 2024-01-15 10:30:00 UTC } func min(a, b int) int { if a < b { return a } return b } ``` -------------------------------- ### Thread-Safe Reader for Concurrent Access Source: https://context7.com/superfly/contextwindow/llms.txt Use ContextReader for safe concurrent access to context data from multiple goroutines. This example demonstrates how UI and Metrics goroutines can safely read token usage and live records. ```go package main import ( "context" "fmt" "sync" "time" "github.com/openai/openai-go/v2/shared" "github.com/superfly/contextwindow" ) func main() { ctx := context.Background() model, _ := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) db, _ := contextwindow.NewContextDB(":memory:") defer db.Close() cw, _ := contextwindow.NewContextWindow(db, model, "concurrent-demo") cw.SetMaxTokens(4096) // Get a thread-safe reader reader := cw.Reader() var wg sync.WaitGroup // UI update goroutine wg.Add(1) go func() { defer wg.Done() for i := 0; i < 5; i++ { usage, _ := reader.TokenUsage() fmt.Printf("[UI] Token usage: %d/%d (%.1f%%)\n", usage.Live, usage.Max, usage.Percent*100) time.Sleep(100 * time.Millisecond) } }() // Metrics goroutine wg.Add(1) go func() { defer wg.Done() for i := 0; i < 5; i++ { records, _ := reader.LiveRecords() fmt.Printf("[Metrics] Live records: %d\n", len(records)) time.Sleep(100 * time.Millisecond) } }() // Main thread modifies state safely cw.AddPrompt("Hello!") cw.CallModel(ctx) cw.SwitchContext("another-context") cw.SetMaxTokens(8192) wg.Wait() } ``` -------------------------------- ### Initialize and Use OpenAI Model Source: https://github.com/superfly/contextwindow/blob/main/README.md Demonstrates initializing a ContextWindow with an OpenAI model and making a basic call. Ensure the OPENAI_API_KEY environment variable is set. The database can be persisted by using a file path instead of ":memory:". ```go package main import ( "context" "fmt" "log" "github.com/openai/openai-go/v2/shared" "github.com/superfly/contextwindow" ) var prompt = `how's the weather over there?` func main() { ctx := context.Background() // reads OPENAI_API_KEY model, err := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) if err != nil { log.Fatalf("Failed to create model: %v", err) } // Initialize the database (in-memory) // For persistence, use a file path instead of ":memory:" db, err := contextwindow.NewContextDB(":memory:") if err != nil { log.Fatalf("Failed to create database: %v", err) } defer db.Close() // Initialize the ContextWindow cw, err := contextwindow.NewContextWindow(db, model, "") if err != nil { log.Fatalf("Failed to create context window: %v", err) } defer cw.Close() if err := cw.AddPrompt(prompt); err != nil { log.Fatalf("Failed to add prompt: %v", err) } // Call the model to get a response response, err := cw.CallModel(ctx) if err != nil { log.Fatalf("Failed to call model: %v", err) } fmt.Printf("<- Model: %s\n", response) } ``` -------------------------------- ### Define and Add a Tool for LLM Source: https://github.com/superfly/contextwindow/blob/main/README.md Shows how to define a tool with parameters and attach it to a ContextWindow instance. Tool arguments are passed as JSON, and responses are strings. ```go lsTool := contextwindow.NewTool("list_files", ` This tool lists files in the specified directory. `).AddStringParameter("directory", "Directory to list", true) cw.AddTool(lsTool, contextwindow.ToolRunnerFunc(func context.Context, args json.RawMessage) (string, error) { var treq struct { Dir string `json:"directory"` } json.Unmarshal(args, &treq) // actually run ls, or pretend to return "here\nare\nsome\nfiles.exe\n", nil }) ``` -------------------------------- ### Initialize SQLite Database for ContextWindow Source: https://context7.com/superfly/contextwindow/llms.txt Initializes a SQLite database for storing context windows. Use ':memory:' for transient storage or a file path for persistent conversations. ```go package main import ( "log" "github.com/superfly/contextwindow" ) func main() { // In-memory database (transient) db, err := contextwindow.NewContextDB(":memory:") if err != nil { log.Fatalf("Failed to create database: %v", err) } defer db.Close() // Or persistent database db, err = contextwindow.NewContextDB("/path/to/conversations.db") if err != nil { log.Fatalf("Failed to create database: %v", err) } defer db.Close() } ``` -------------------------------- ### Create ContextWindow with OpenAI Model Source: https://context7.com/superfly/contextwindow/llms.txt Creates a ContextWindow using OpenAI's Responses API model for conversation management with automatic tool call support. Reads OPENAI_API_KEY from environment variables. ```go package main import ( "context" "fmt" "log" "github.com/openai/openai-go/v2/shared" "github.com/superfly/contextwindow" ) func main() { ctx := context.Background() // Create OpenAI Responses model (reads OPENAI_API_KEY from env) model, err := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) if err != nil { log.Fatalf("Failed to create model: %v", err) } // Initialize database db, err := contextwindow.NewContextDB(":memory:") if err != nil { log.Fatalf("Failed to create database: %v", err) } defer db.Close() // Create ContextWindow with auto-generated context name cw, err := contextwindow.NewContextWindow(db, model, "") if err != nil { log.Fatalf("Failed to create context window: %v", err) } defer cw.Close() // Add a user prompt and call the model if err := cw.AddPrompt("What is the capital of France?"); err != nil { log.Fatalf("Failed to add prompt: %v", err) } response, err := cw.CallModel(ctx) if err != nil { log.Fatalf("Failed to call model: %v", err) } fmt.Printf("Response: %s\n", response) // Output: Response: The capital of France is Paris. } ``` -------------------------------- ### Define and Call a File Listing Tool Source: https://context7.com/superfly/contextwindow/llms.txt Define a tool to list files in a directory using typed parameters and register it with a runner function. The model automatically calls the tool when appropriate. ```go package main import ( "context" "encoding/json" "fmt" "log" "os" "github.com/openai/openai-go/v2/shared" "github.com/superfly/contextwindow" ) func main() { ctx := context.Background() model, err := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) if err != nil { log.Fatalf("Failed to create model: %v", err) } db, err := contextwindow.NewContextDB(":memory:") if err != nil { log.Fatalf("Failed to create database: %v", err) } defer db.Close() cw, err := contextwindow.NewContextWindow(db, model, "tool-demo") if err != nil { log.Fatalf("Failed to create context window: %v", err) } // Define a tool with typed parameters listFilesTool := contextwindow.NewTool("list_files", " Lists files in the specified directory. Returns a newline-separated list of filenames. ").AddStringParameter("directory", "Directory path to list", true) // Register tool with a runner function err = cw.AddTool(listFilesTool, contextwindow.ToolRunnerFunc( func(ctx context.Context, args json.RawMessage) (string, error) { var params struct { Directory string `json:"directory"` } if err := json.Unmarshal(args, ¶ms); err != nil { return "", fmt.Errorf("invalid arguments: %w", err) } entries, err := os.ReadDir(params.Directory) if err != nil { return "", fmt.Errorf("failed to read directory: %w", err) } var result string for _, entry := range entries { result += entry.Name() + "\n" } return result, nil }, )) if err != nil { log.Fatalf("Failed to add tool: %v", err) } // The model will automatically call the tool when appropriate if err := cw.AddPrompt("What files are in the current directory?"); err != nil { log.Fatalf("Failed to add prompt: %v", err) } response, err := cw.CallModel(ctx) if err != nil { log.Fatalf("Failed to call model: %v", err) } fmt.Printf("Response: %s\n", response) } ``` -------------------------------- ### Track Token Usage with Context Window Source: https://context7.com/superfly/contextwindow/llms.txt Use this snippet to monitor live and total token consumption within your context window. Ensure the 'contextwindow' and 'openai-go' libraries are imported. ```go package main import ( "context" "fmt" "log" "github.com/openai/openai-go/v2/shared" "github.com/superfly/contextwindow" ) func main() { ctx := context.Background() model, err := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) if err != nil { log.Fatalf("Failed to create model: %v", err) } db, err := contextwindow.NewContextDB(":memory:") if err != nil { log.Fatalf("Failed to create database: %v", err) } defer db.Close() cw, err := contextwindow.NewContextWindow(db, model, "token-tracking") if err != nil { log.Fatalf("Failed to create context window: %v", err) } // Set maximum tokens for the context window cw.SetMaxTokens(8192) cw.AddPrompt("Explain quantum computing in detail.") cw.CallModel(ctx) // Get live tokens (currently in context) liveTokens, err := cw.LiveTokens() if err != nil { log.Fatalf("Failed to get live tokens: %v", err) } // Get total tokens used across all calls totalTokens := cw.TotalTokens() // Get comprehensive usage metrics usage, err := cw.TokenUsage() if err != nil { log.Fatalf("Failed to get token usage: %v", err) } fmt.Printf("Live tokens: %d\n", liveTokens) fmt.Printf("Total tokens used: %d\n", totalTokens) fmt.Printf("Token usage: %d/%d (%.1f%%)\n", usage.Live, usage.Max, usage.Percent*100) // Output: // Live tokens: 1523 // Total tokens used: 2847 // Token usage: 1523/8192 (18.6%) } ``` -------------------------------- ### Create ContextWindow with Claude Model Source: https://context7.com/superfly/contextwindow/llms.txt Creates a ContextWindow using Anthropic's Claude model with support for system prompts and tool calling. Reads ANTHROPIC_API_KEY from environment variables. ```go package main import ( "context" "fmt" "log" "github.com/superfly/contextwindow" ) func main() { ctx := context.Background() // Create Claude model (reads ANTHROPIC_API_KEY from env) model, err := contextwindow.NewClaudeModel(contextwindow.ModelClaudeSonnet45) if err != nil { log.Fatalf("Failed to create Claude model: %v", err) } db, err := contextwindow.NewContextDB(":memory:") if err != nil { log.Fatalf("Failed to create database: %v", err) } defer db.Close() cw, err := contextwindow.NewContextWindow(db, model, "claude-conversation") if err != nil { log.Fatalf("Failed to create context window: %v", err) } defer cw.Close() // Set a system prompt if err := cw.SetSystemPrompt("You are a helpful assistant that speaks like a pirate."); err != nil { log.Fatalf("Failed to set system prompt: %v", err) } if err := cw.AddPrompt("Tell me about the ocean."); err != nil { log.Fatalf("Failed to add prompt: %v", err) } response, err := cw.CallModel(ctx) if err != nil { log.Fatalf("Failed to call model: %v", err) } fmt.Printf("Response: %s\n", response) } ``` -------------------------------- ### Manage Multiple Contexts in Go Source: https://context7.com/superfly/contextwindow/llms.txt Switch between different conversation contexts within a single ContextWindow instance. This allows for separate conversation histories for different users or topics. Ensure the database and model are initialized before use. ```go package main import ( "context" "fmt" "log" "github.com/openai/openai-go/v2/shared" "github.com/superfly/contextwindow" ) func main() { ctx := context.Background() model, err := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) if err != nil { log.Fatalf("Failed to create model: %v", err) } db, err := contextwindow.NewContextDB("conversations.db") if err != nil { log.Fatalf("Failed to create database: %v", err) } defer db.Close() cw, err := contextwindow.NewContextWindow(db, model, "user-alice") if err != nil { log.Fatalf("Failed to create context window: %v", err) } // Conversation with Alice cw.AddPrompt("Hi, I'm Alice!") cw.CallModel(ctx) // Switch to Bob's context (creates if doesn't exist) if err := cw.SwitchContext("user-bob"); err != nil { log.Fatalf("Failed to switch context: %v", err) } // Conversation with Bob (separate from Alice) cw.AddPrompt("Hi, I'm Bob!") cw.CallModel(ctx) // List all contexts contexts, err := cw.ListContexts() if err != nil { log.Fatalf("Failed to list contexts: %v", err) } for _, c := range contexts { stats, _ := cw.GetContextStats(c) fmt.Printf("Context: %s, Records: %d, Live Tokens: %d\n", c.Name, stats.TotalRecords, stats.LiveTokens) } // Output: // Context: user-bob, Records: 2, Live Tokens: 45 // Context: user-alice, Records: 2, Live Tokens: 42 // Clone a context if err := cw.Clone("user-alice-backup"); err != nil { log.Fatalf("Failed to clone context: %v", err) } // Delete a context if err := cw.DeleteContext("user-bob"); err != nil { log.Fatalf("Failed to delete context: %v", err) } } ``` -------------------------------- ### Define Tools with Various Parameter Types Source: https://context7.com/superfly/contextwindow/llms.txt Define tools with string, number, boolean, array, and object parameters. The object parameter supports nested properties. ```go package main import ( "github.com/superfly/contextwindow" ) func main() { // String parameter searchTool := contextwindow.NewTool("search", "Search for content"). AddStringParameter("query", "Search query", true). AddNumberParameter("limit", "Maximum results", false) // Boolean parameter toggleTool := contextwindow.NewTool("toggle_feature", "Toggle a feature"). AddBooleanParameter("enabled", "Whether to enable", true) // Array parameter batchTool := contextwindow.NewTool("process_batch", "Process multiple items"). AddArrayParameter("items", "List of item IDs", true, contextwindow.ParameterTypeString) // Object parameter with nested properties createUserTool := contextwindow.NewTool("create_user", "Create a new user"). AddObjectParameter("user", "User details", true, map[string]*contextwindow.Parameter{ "name": { Name: "name", Type: contextwindow.ParameterTypeString, Description: "User's full name", Required: true, }, "age": { Name: "age", Type: contextwindow.ParameterTypeNumber, Description: "User's age", Required: false, }, }) // Convert to provider-specific format _ = searchTool.ToOpenAI() // OpenAI FunctionDefinitionParam _ = toggleTool.ToClaude() // Anthropic ToolParam _ = batchTool.ToGemini() // Google FunctionDeclaration _ = createUserTool } ``` -------------------------------- ### Manage Live Records in Go Source: https://context7.com/superfly/contextwindow/llms.txt Access and manipulate live records within the context window directly. Use `LiveRecords()` to retrieve all current records and `SetRecordLiveStateByRange` to mark records as live or not. This is useful for pruning the context. ```go package main import ( "context" "fmt" "log" "github.com/openai/openai-go/v2/shared" "github.com/superfly/contextwindow" ) func main() { ctx := context.Background() model, _ := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) db, _ := contextwindow.NewContextDB(":memory:") defer db.Close() cw, _ := contextwindow.NewContextWindow(db, model, "records-demo") // Add multiple prompts cw.AddPrompt("First message") cw.CallModel(ctx) cw.AddPrompt("Second message") cw.CallModel(ctx) cw.AddPrompt("Third message") cw.CallModel(ctx) // Get all live records records, err := cw.LiveRecords() if err != nil { log.Fatalf("Failed to get records: %v", err) } fmt.Printf("Live records: %d\n", len(records)) for i, rec := range records { sourceType := []string{"Prompt", "ModelResp", "ToolCall", "ToolOutput", "SystemPrompt"}[rec.Source] fmt.Printf("[%d] %s: %s... (%d tokens)\n", i, sourceType, rec.Content[:min(30, len(rec.Content))], rec.EstTokens) } // Mark records as not live (remove from context window) // This marks records at indices 0 and 1 as dead if err := cw.SetRecordLiveStateByRange(0, 1, false); err != nil { log.Fatalf("Failed to set record state: %v", err) } // Now only newer records are live records, _ = cw.LiveRecords() fmt.Printf("Live records after pruning: %d\n", len(records)) } func min(a, b int) int { if a < b { return a } return b } ``` -------------------------------- ### Summarize Context with LLM Source: https://context7.com/superfly/contextwindow/llms.txt Compress long conversations using a separate LLM summarizer to reduce token count while preserving essential information. This requires configuring a summarizer model and prompt. ```go package main import ( "context" "fmt" "log" "github.com/openai/openai-go/v2/shared" "github.com/superfly/contextwindow" ) func main() { ctx := context.Background() // Main model for conversation model, err := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) if err != nil { log.Fatalf("Failed to create model: %v", err) } // Cheaper model for summarization summarizer, err := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) if err != nil { log.Fatalf("Failed to create summarizer: %v", err) } db, err := contextwindow.NewContextDB(":memory:") if err != nil { log.Fatalf("Failed to create database: %v", err) } defer db.Close() cw, err := contextwindow.NewContextWindow(db, model, "summarization-demo") if err != nil { log.Fatalf("Failed to create context window: %v", err) } // Configure summarizer cw.SetSummarizer(summarizer) cw.SetSummarizerPrompt("Summarize this conversation, preserving key facts and decisions.") // Simulate a long conversation for i := 0; i < 10; i++ { cw.AddPrompt(fmt.Sprintf("Tell me about topic %d in great detail.", i)) cw.CallModel(ctx) } // Check token usage beforeTokens, _ := cw.LiveTokens() fmt.Printf("Tokens before summarization: %d\n", beforeTokens) // Generate summary (doesn't apply it yet) result, err := cw.SummarizeLiveContext(ctx) if err != nil { log.Fatalf("Failed to summarize: %v", err) } fmt.Printf("Original tokens: %d\n", result.OrigCount) fmt.Printf("Summary tokens: %d\n", result.SummaryCount) fmt.Printf("Compression ratio: %.1fx\n", float64(result.OrigCount)/float64(result.SummaryCount)) // Accept the summary (replaces live records with summary) if err := cw.AcceptSummary(result); err != nil { log.Fatalf("Failed to accept summary: %v", err) } afterTokens, _ := cw.LiveTokens() fmt.Printf("Tokens after summarization: %d\n", afterTokens) } ``` -------------------------------- ### Enhance Threading Logic in CallModelWithOpts Source: https://github.com/superfly/contextwindow/blob/main/plans/2025-09-17-resume-context-plan.md Enhance threading logic in CallModelWithOpts to gracefully handle broken response_id chains. It should prioritize server-side threading if a valid last_response_id is available, otherwise fall back to client-side threading with full history. ```go // If server-side threading is enabled AND we have a valid `last_response_id`, use server-side threading // Otherwise, gracefully fall back to client-side threading with full history ``` -------------------------------- ### Update CreateContextWithThreading Logic Source: https://github.com/superfly/contextwindow/blob/main/plans/2025-09-17-resume-context-plan.md Modify CreateContextWithThreading to return an existing context if the name already exists, instead of failing. This involves removing the name collision check and implementing a check for context existence. ```go // Remove the name collision check (lines 139-146) // Instead, check if context exists and return it ``` -------------------------------- ### Update SwitchContext Logic Source: https://github.com/superfly/contextwindow/blob/main/plans/2025-09-17-resume-context-plan.md Modify SwitchContext to create a context if it does not exist. This involves checking if GetContextByName fails with sql.ErrNoRows and creating the context in that scenario. ```go // If GetContextByName fails with sql.ErrNoRows, create the context // Otherwise, proceed as normal ``` -------------------------------- ### Enable Server-Side Threading for API Calls Source: https://context7.com/superfly/contextwindow/llms.txt Enable server-side threading for optimized API calls when using OpenAI's Responses API. This allows the server to maintain conversation state. ```go package main import ( "context" "fmt" "log" "github.com/openai/openai-go/v2/shared" "github.com/superfly/contextwindow" ) func main() { ctx := context.Background() model, _ := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) db, _ := contextwindow.NewContextDB(":memory:") defer db.Close() // Enable server-side threading on creation cw, err := contextwindow.NewContextWindowWithThreading(db, model, "threaded", true) if err != nil { log.Fatalf("Failed to create context window: %v", err) } // Or toggle threading on existing context if err := cw.SetServerSideThreading(true); err != nil { log.Fatalf("Failed to enable threading: %v", err) } // Check threading status enabled, _ := cw.IsServerSideThreadingEnabled() fmt.Printf("Server-side threading enabled: %v\n", enabled) // With threading enabled, only the latest prompt is sent // The server maintains conversation state via response_id cw.AddPrompt("Hello!") cw.CallModel(ctx) cw.AddPrompt("What did I just say?") response, _ := cw.CallModel(ctx) fmt.Println(response) // The model remembers the conversation via server-side state } ``` -------------------------------- ### Define ContextReader Struct Source: https://github.com/superfly/contextwindow/blob/main/plans/2025-09-18-contextreader-thread-safety.md Defines the ContextReader struct, which acts as a thin proxy for thread-safe read access to context window data. ```go // ContextReader provides thread-safe read access to context window data. // It's a thin proxy that forwards calls to safe read methods. type ContextReader struct { cw *ContextWindow // reference to underlying context window } ``` -------------------------------- ### Export and Import Contexts in Go Source: https://context7.com/superfly/contextwindow/llms.txt Export conversation contexts as structured data or JSON for backup, debugging, or transfer. The `ExportContextJSON` function saves the context to a file. Ensure the model and database are initialized. ```go package main import ( "fmt" "log" "os" "github.com/openai/openai-go/v2/shared" "github.com/superfly/contextwindow" ) func main() { model, _ := contextwindow.NewOpenAIResponsesModel(shared.ChatModelGPT5Mini) db, _ := contextwindow.NewContextDB(":memory:") defer db.Close() cw, _ := contextwindow.NewContextWindow(db, model, "exportable") cw.AddPrompt("This is a test conversation.") // Export as structured data export, err := cw.ExportContext("exportable") if err != nil { log.Fatalf("Failed to export: %v", err) } fmt.Printf("Context: %s\n", export.Context.Name) fmt.Printf("Records: %d\n", len(export.Records)) fmt.Printf("Tools: %d\n", len(export.Tools)) // Export as JSON jsonData, err := cw.ExportContextJSON("exportable") if err != nil { log.Fatalf("Failed to export JSON: %v", err) } // Save to file os.WriteFile("context-backup.json", jsonData, 0644) fmt.Printf("Exported JSON:\n%s\n", string(jsonData)) // Output: // { // "context": { // "id": "...", // "name": "exportable", // "start_time": "2024-01-15T10:30:00Z" // }, // "records": [...], // "tools": [] // } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.