Something went wrong. Try again.
A small AI buddy that lives in the bottom right-hand corner of your Mac that wakes when you press a keybind.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import Foundationimport OSLog
/// Web search through TinyFish's Search API (GET, `X-API-Key` header).struct TinyFishSearch: Sendable { let apiKey: String
static let toolName = "web_search"
static let tool = ChatTool( name: toolName, description: "Search the web for current information: news, recent events, prices, sports scores, weather, release notes or any fact you are unsure of or that may have changed since your training. Returns titles, URLs and snippets. Do not use it for things you already know well.", parameters: [ "type": "object", "properties": [ "query": [ "type": "string", "description": "A concise search query, as you would type into a search engine.", ], "recent": [ "type": "boolean", "description": "True to prefer results from the past week (news, live events).", ], ], "required": ["query"], ] )
/// Runs a search and returns a compact plain-text digest for the model. func search(_ query: String, recent: Bool = false) async throws -> String { guard !apiKey.isEmpty else { throw ProviderError.missingAPIKey } var components = URLComponents(string: "https://api.search.tinyfish.ai")! var items = [URLQueryItem(name: "query", value: query)] if recent { items.append(URLQueryItem(name: "recency_minutes", value: String(7 * 24 * 60))) } components.queryItems = items var req = URLRequest(url: components.url!) req.setValue(apiKey, forHTTPHeaderField: "X-API-Key") req.timeoutInterval = 20
let (data, response) = try await URLSession.shared.data(for: req) if let http = response as? HTTPURLResponse { Logger.api.info("TinyFish search HTTP status=\(http.statusCode, privacy: .public)") guard http.statusCode == 200 else { throw ProviderError.httpError(http.statusCode, String(decoding: data.prefix(300), as: UTF8.self)) } } guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any], let results = object["results"] as? [[String: Any]] else { throw ProviderError.decodingError("unexpected search response") }
let lines = results.prefix(6).enumerated().map { i, r -> String in let title = r["title"] as? String ?? "" let url = r["url"] as? String ?? "" let snippet = r["snippet"] as? String ?? "" let date = (r["date"] as? String).map { " (\($0))" } ?? "" return "\(i + 1). \(title)\(date) — \(url)\n\(snippet)" } return lines.isEmpty ? "No results." : lines.joined(separator: "\n\n") }}