SPB Git

Repository Public

Calculator.swift 10.9 KB 205 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatAgents/Sources/Calculator.swift3// Description: A small recursive-descent arithmetic evaluator (no NSExpression, no code execution) and the calculator / date tools.4import Foundation5import LocalChatCore67public enum CalculatorError: LocalizedError, Sendable, Equatable {8    case syntax(String), unknownIdentifier(String), arity(String), math(String), tooComplex9    public var errorDescription: String? {10        switch self {11        case .syntax(let m): "Syntax error: \(m)"12        case .unknownIdentifier(let n): "Unknown name: \(n)"13        case .arity(let m): m14        case .math(let m): "Math error: \(m)"15        case .tooComplex: "The expression is too long or too deeply nested."16        }17    }18}1920/// Grammar: expr := term (('+'|'-') term)* ; term := unary (('*'|'/'|'%') unary)* ; unary := ('-'|'+') unary | power ;21/// power := primary ('^' unary)? (right associative) ; primary := number | name | name '(' args ')' | '(' expr ')'.22public struct Calculator {23    private var chars: [Character]; private var i = 0; private var depth = 024    private init(_ s: String) { chars = Array(s) }2526    public static func evaluate(_ expression: String) throws -> Double {27        guard expression.count <= 2000 else { throw CalculatorError.tooComplex }28        var parser = Calculator(expression.replacingOccurrences(of: "×", with: "*").replacingOccurrences(of: "÷", with: "/")29            .replacingOccurrences(of: "**", with: "^").replacingOccurrences(of: "π", with: "pi").replacingOccurrences(of: "−", with: "-"))30        let value = try parser.expr()31        parser.skip()32        guard parser.i == parser.chars.count else { throw CalculatorError.syntax("unexpected \"\(parser.chars[parser.i])\" at position \(parser.i + 1)") }33        guard value.isFinite else { throw CalculatorError.math("the result is not a finite number") }34        return value35    }3637    public static func format(_ value: Double) -> String {38        if value.rounded() == value, abs(value) < 1e15 { return String(Int64(value)) }39        var s = String(format: "%.12g", value)40        if s.contains("."), !s.contains("e") { while s.hasSuffix("0") { s.removeLast() } }41        return s42    }4344    private mutating func skip() { while i < chars.count, chars[i].isWhitespace { i += 1 } }45    private mutating func peek() -> Character? { skip(); return i < chars.count ? chars[i] : nil }46    private mutating func eat(_ c: Character) -> Bool { if peek() == c { i += 1; return true }; return false }4748    private mutating func expr() throws -> Double {49        depth += 1; defer { depth -= 1 }50        guard depth < 64 else { throw CalculatorError.tooComplex }51        var v = try term()52        while true {53            if eat("+") { v += try term() } else if eat("-") { v -= try term() } else { return v }54        }55    }5657    private mutating func term() throws -> Double {58        var v = try unary()59        while true {60            if eat("*") { v *= try unary() }61            else if eat("/") { let d = try unary(); guard d != 0 else { throw CalculatorError.math("division by zero") }; v /= d }62            else if eat("%") { let d = try unary(); guard d != 0 else { throw CalculatorError.math("modulo by zero") }; v = v.truncatingRemainder(dividingBy: d) }63            else { return v }64        }65    }6667    private mutating func unary() throws -> Double {68        depth += 1; defer { depth -= 1 }69        guard depth < 64 else { throw CalculatorError.tooComplex }70        if eat("-") { return -(try unary()) }71        if eat("+") { return try unary() }72        return try power()73    }7475    private mutating func power() throws -> Double {76        let base = try primary()77        if eat("^") {78            let r = pow(base, try unary())79            guard !r.isNaN else { throw CalculatorError.math("invalid power") }80            return r81        }82        return base83    }8485    private mutating func primary() throws -> Double {86        guard let c = peek() else { throw CalculatorError.syntax("unexpected end of expression") }87        if eat("(") {88            let v = try expr()89            guard eat(")") else { throw CalculatorError.syntax("missing \")\"") }90            return v91        }92        if c.isNumber || c == "." {93            let start = i94            while i < chars.count, chars[i].isNumber || chars[i] == "." { i += 1 }95            if i < chars.count, chars[i] == "e" || chars[i] == "E" {96                var j = i + 197                if j < chars.count, chars[j] == "+" || chars[j] == "-" { j += 1 }98                if j < chars.count, chars[j].isNumber { i = j; while i < chars.count, chars[i].isNumber { i += 1 } }99            }100            guard let v = Double(String(chars[start..<i])) else { throw CalculatorError.syntax("invalid number \"\(String(chars[start..<i]))\"") }101            return v102        }103        if c.isLetter {104            let start = i105            while i < chars.count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" { i += 1 }106            let name = String(chars[start..<i]).lowercased()107            if eat("(") {108                var args: [Double] = []109                if !eat(")") {110                    repeat { args.append(try expr()) } while eat(",")111                    guard eat(")") else { throw CalculatorError.syntax("missing \")\" after arguments of \(name)") }112                }113                return try Self.call(name, args)114            }115            switch name {116            case "pi": return Double.pi117            case "e": return M_E118            case "tau": return 2 * Double.pi119            default: throw CalculatorError.unknownIdentifier(name)120            }121        }122        throw CalculatorError.syntax("unexpected \"\(c)\" at position \(i + 1)")123    }124125    private static func call(_ name: String, _ a: [Double]) throws -> Double {126        func one() throws -> Double {127            guard a.count == 1 else { throw CalculatorError.arity("\(name) takes exactly 1 argument.") }128            return a[0]129        }130        switch name {131        case "sqrt": let x = try one(); guard x >= 0 else { throw CalculatorError.math("square root of a negative number") }; return x.squareRoot()132        case "sin": return sin(try one())133        case "cos": return cos(try one())134        case "tan": return tan(try one())135        case "exp": return exp(try one())136        case "abs": return abs(try one())137        case "floor": return floor(try one())138        case "ceil": return ceil(try one())139        case "ln": let x = try one(); guard x > 0 else { throw CalculatorError.math("logarithm of a non-positive number") }; return log(x)140        case "log":   // log(x) = base 10, log(x, base)141            guard a.count == 1 || a.count == 2 else { throw CalculatorError.arity("log takes 1 or 2 arguments.") }142            guard a[0] > 0, a.count == 1 || (a[1] > 0 && a[1] != 1) else { throw CalculatorError.math("logarithm out of domain") }143            return a.count == 1 ? log10(a[0]) : log(a[0]) / log(a[1])144        case "round":145            guard a.count == 1 || a.count == 2 else { throw CalculatorError.arity("round takes 1 or 2 arguments.") }146            let scale = pow(10, a.count == 2 ? a[1].rounded() : 0)147            return (a[0] * scale).rounded(.toNearestOrAwayFromZero) / scale148        case "min": guard let m = a.min() else { throw CalculatorError.arity("min needs at least 1 argument.") }; return m149        case "max": guard let m = a.max() else { throw CalculatorError.arity("max needs at least 1 argument.") }; return m150        default: throw CalculatorError.unknownIdentifier(name)151        }152    }153}154155struct CalculatorTool: AgentTool {156    let risk: ToolRisk = .safe157    let definition = ToolDefinition(158        name: "calculator",159        summary: "Evaluates an arithmetic expression exactly. Supports + - * / ^ %, parentheses, sqrt sin cos tan log ln exp abs min max round floor ceil, and the constants pi and e.",160        parameters: ["type": "object", "properties": ["expression": ["type": "string", "description": "e.g. (3 + 4) * 2 ^ 3"]], "required": ["expression"]])161    func run(arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {162        let expression = arguments["expression"]?.stringValue ?? ""163        return ToolOutput(Calculator.format(try Calculator.evaluate(expression)))164    }165}166167struct DateTimeTool: AgentTool {168    let risk: ToolRisk = .safe169    let definition = ToolDefinition(170        name: "current_datetime", summary: "Returns the current date and time, optionally in a given IANA time zone.",171        parameters: ["type": "object", "properties": ["timezone": ["type": "string", "description": "IANA identifier such as America/Toronto. Defaults to the device time zone."]]])172    var now: @Sendable () -> Date = { Date() }173    func run(arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {174        var zone = TimeZone.current175        if let id = arguments["timezone"]?.stringValue, !id.isEmpty {176            guard let z = TimeZone(identifier: id) ?? TimeZone(abbreviation: id.uppercased()) else { throw ToolError("Unknown time zone \"\(id)\". Use an IANA identifier such as Europe/Paris.") }177            zone = z178        }179        let date = now()180        let iso = ISO8601DateFormatter(); iso.timeZone = zone; iso.formatOptions = [.withInternetDateTime]181        let human = DateFormatter(); human.locale = Locale(identifier: "en_US_POSIX"); human.timeZone = zone; human.dateFormat = "EEEE, d MMMM yyyy, HH:mm:ss"182        return ToolOutput("\(iso.string(from: date)) — \(human.string(from: date)) (\(zone.identifier))")183    }184}185186struct KnowledgeSearchTool: AgentTool {187    let risk: ToolRisk = .read188    let definition = ToolDefinition(189        name: "knowledge_search", summary: "Searches the user's private document collections attached to this agent and returns numbered passages to cite as [n].",190        parameters: ["type": "object", "properties": ["query": ["type": "string"], "limit": ["type": "integer", "description": "1 to 10, default 5"]], "required": ["query"]])191    func run(arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {192        guard let knowledge = context.knowledge, !context.collectionIDs.isEmpty else { throw ToolError("No document collection is attached to this agent.") }193        let query = arguments["query"]?.stringValue ?? ""194        guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { throw ToolError("The query is empty.") }195        let limit = max(1, min(10, arguments["limit"]?.intValue ?? 5))196        let hits = try await knowledge.search(query, collections: context.collectionIDs, limit: limit)197        guard !hits.isEmpty else { return ToolOutput("No passage matched \"\(query)\".") }198        var text = ""199        for (i, hit) in hits.enumerated() {200            text += "[\(i + 1)] \(hit.document.name)\(hit.page.map { ", p. \($0)" } ?? "")\n\(hit.text.trimmingCharacters(in: .whitespacesAndNewlines))\n\n"201        }202        return ToolOutput(text.trimmingCharacters(in: .newlines), sources: hits.map(\.reference))203    }204}205
Files main
Menu

Theme