SPB Git

Repository Public

ReasoningParserTests.swift 10.3 KB 223 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraLocalTests/ReasoningParserTests.swift10// Module           : AstraLocalTests11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2213// Last Modified    : 2026-11-2214//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import Testing90@testable import AstraLocal9192@Suite struct ReasoningParserTests {93    typealias Segment = ReasoningParser.Segment9495    /// Feeds `text` in pieces of `size` characters and returns the joined reasoning, the joined answer and the end state.96    private func run(_ text: String, chunk size: Int, startsInside: Bool = false, markers: [ReasoningMarker] = [.think])97        -> (reasoning: String, answer: String, unterminated: Bool, parser: ReasoningParser) {98        var parser = ReasoningParser(markers: markers, startsInsideReasoning: startsInside)99        var reasoning = "", answer = ""100        func take(_ segments: [Segment]) { for s in segments { switch s { case .reasoning(let t): reasoning += t; case .answer(let t): answer += t } } }101        var rest = Substring(text)102        while !rest.isEmpty { take(parser.consume(String(rest.prefix(size)))); rest = rest.dropFirst(size) }103        let end = parser.finish(); take(end.segments)104        return (reasoning, answer, end.unterminated, parser)105    }106107    @Test func separatesAThinkBlockFromTheAnswerAtEveryChunkSize() {108        let text = "<think>\nFirst add 17 and 26.\nThat is 43.\n</think>\n\nThe answer is 43."109        for size in 1...text.count {110            let r = run(text, chunk: size)111            #expect(r.reasoning == "First add 17 and 26.\nThat is 43.", "chunk \(size)")112            #expect(r.answer == "The answer is 43.", "chunk \(size)")113            #expect(!r.unterminated && r.parser.closedReasoning && r.parser.separatedByParser)114        }115    }116117    @Test func leadingWhitespaceBeforeTheMarkerIsAccepted() {118        let r = run("\n \n<think>plan</think>done", chunk: 3)119        #expect(r.reasoning == "plan" && r.answer == "done")120    }121122    @Test func plainTextIsNeverReasoning() {123        for text in ["Hello there.", "  Indented answer", "<b>bold</b> text", "<thinking about it> no", "<", "<thin", "2 < 3 and <think> is a tag"] {124            for size in [1, 2, 5, 100] {125                let r = run(text, chunk: size)126                #expect(r.reasoning.isEmpty, "\(text) / \(size)")127                #expect(r.answer == text, "\(text) / \(size)")128                #expect(!r.parser.producedReasoning && !r.unterminated)129            }130        }131    }132133    @Test func aMarkerInsideTheAnswerStaysText() {134        let text = "Use the tag <think>like this</think> in your prompt."135        let r = run(text, chunk: 4)136        #expect(r.reasoning.isEmpty && r.answer == text)137        // After a real block, a second block is text as well: only the start of the turn can open reasoning.138        let two = run("<think>a</think>Answer with <think>b</think> inside", chunk: 3)139        #expect(two.reasoning == "a" && two.answer == "Answer with <think>b</think> inside")140    }141142    @Test func anUnterminatedBlockEndsAsReasoningWithNoAnswer() {143        for size in [1, 3, 7, 200] {144            let r = run("<think>\nLet me consider the options. First, </thi", chunk: size)145            #expect(r.unterminated)146            #expect(r.answer.isEmpty, "nothing of an open block may become answer text")147            #expect(r.reasoning == "Let me consider the options. First, </thi")148            #expect(!r.parser.producedAnswer && r.parser.producedReasoning && !r.parser.closedReasoning)149        }150    }151152    @Test func anEmptyBlockProducesNoReasoning() {153        let r = run("<think>\n\n</think>\n\nHi Sam.", chunk: 2)154        #expect(r.reasoning.isEmpty && r.answer == "Hi Sam." && !r.parser.producedReasoning && r.parser.closedReasoning)155    }156157    @Test func aPromptThatOpensTheBlockStartsInsideReasoning() {158        // DeepSeek-R1: the template ends the prompt with "<think>\n", the model writes only the closing marker.159        for size in [1, 4, 300] {160            let r = run("Okay, 2 + 2.\nIt is 4.\n</think>\n\n4", chunk: size, startsInside: true)161            #expect(r.reasoning == "Okay, 2 + 2.\nIt is 4." && r.answer == "4" && !r.unterminated)162            // Some checkpoints repeat the opening marker anyway: it is dropped, not shown.163            let repeated = run("<think>\nOkay.</think>4", chunk: size, startsInside: true)164            #expect(repeated.reasoning == "Okay." && repeated.answer == "4")165        }166        let cut = run("Okay, so the user", chunk: 5, startsInside: true)167        #expect(cut.unterminated && cut.answer.isEmpty && cut.reasoning == "Okay, so the user")168    }169170    @Test func reasoningReportedByTheRuntimeIsPassedThrough() {171        var parser = ReasoningParser(markers: [.think])172        #expect(parser.runtimeReasoning("thinking… ") == [.reasoning("thinking… ")])173        #expect(parser.runtimeReasoning("more") == [.reasoning("more")])174        // The runtime already removed the markers: what follows is the answer, even if it happens to start like a marker.175        #expect(parser.consume("<think") == [.answer("<think")])176        #expect(parser.consume("ing> done") == [.answer("ing> done")])177        let end = parser.finish()178        #expect(end.segments.isEmpty && !end.unterminated)179        #expect(parser.producedReasoning && parser.producedAnswer && !parser.separatedByParser && parser.reasoningCharacters == 14)180    }181182    @Test func runtimeReasoningOverridesAPromptOpenedBlock() {183        var parser = ReasoningParser(markers: [.think], startsInsideReasoning: false)184        _ = parser.runtimeReasoning("r")185        #expect(parser.consume("answer") == [.answer("answer")])186    }187188    @Test func noMarkersMeansEverythingIsAnswer() {189        let r = run("<think>x</think>y", chunk: 2, markers: [])190        #expect(r.reasoning.isEmpty && r.answer == "<think>x</think>y")191    }192193    @Test func otherMarkerPairsWork() {194        let marker = ReasoningMarker(open: "<|begin_of_thought|>", close: "<|end_of_thought|>")195        for size in [1, 6, 500] {196            let r = run("<|begin_of_thought|>hmm<|end_of_thought|>ok", chunk: size, markers: [.think, marker])197            #expect(r.reasoning == "hmm" && r.answer == "ok")198        }199    }200201    @Test func nothingIsLostOrDuplicated() {202        // Property: for any split, reasoning + answer contain exactly the non-marker characters, in order.203        let text = "<think>alpha </ beta <think> gamma</think>\n\ndelta </think> epsilon"204        for size in 1...text.count {205            let r = run(text, chunk: size)206            #expect(r.reasoning == "alpha </ beta <think> gamma")207            #expect(r.answer == "delta </think> epsilon")208        }209    }210211    @Test func heldSuffixIsTheLongestMarkerPrefix() {212        #expect(ReasoningParser.heldSuffix("abc</thi", "</think>") == 5)213        #expect(ReasoningParser.heldSuffix("abc<", "</think>") == 1)214        #expect(ReasoningParser.heldSuffix("abc", "</think>") == 0)215        #expect(ReasoningParser.heldSuffix("</think", "</think>") == 7)216    }217218    @Test func whitespaceOnlyOutputProducesNothing() {219        let r = run("  \n ", chunk: 1)220        #expect(r.reasoning.isEmpty && r.answer.isEmpty && !r.unterminated)221    }222}223
Files main
Menu

Theme