Select web passages by topic and verify live Ollama chat

This commit is contained in:
Mark Gregory
2026-11-16 17:01:26 +00:00
parent 74c726e2d5
commit a2ccafa613
2 changed files with 65 additions and 7 deletions
+35 -7
View File
@@ -126,7 +126,7 @@ enum WebClipCapture {
throw StudioError("The page contains no readable text.") throw StudioError("The page contains no readable text.")
} }
let links = type == "text/plain" ? [] : pageLinks(raw, base: resource.url) let links = type == "text/plain" ? [] : pageLinks(raw, base: resource.url)
return WebPage(url: resource.url, text: String(content.prefix(12_000)), links: links) return WebPage(url: resource.url, text: String(content.prefix(80_000)), links: links)
} }
static func pageLinks(_ html: String, base: URL) -> [WebSearchResult] { static func pageLinks(_ html: String, base: URL) -> [WebSearchResult] {
@@ -330,10 +330,14 @@ enum ChatWebLookup {
browserFallback = browser?.url browserFallback = browser?.url
} }
var seen = Set(choices + primary.pages.map(\.url)) var seen = Set(choices + primary.pages.map(\.url))
let terms = Set(LibraryImport.matchQuery(topic).components(separatedBy: " OR ") let hosts = Set(primary.pages.compactMap { $0.url.host }.flatMap { Self.words($0) })
.map { $0.trimmingCharacters(in: CharacterSet(charactersIn: "\"")) }.filter { !$0.isEmpty }) let terms = Self.words(topic).subtracting(hosts).subtracting([
"about", "find", "follow", "link", "links", "read", "page", "documentation",
"docs", "search", "look", "browse", "web", "online", "please", "https", "http",
"the", "for", "with", "from", "you", "can", "show", "what", "how", "and"
])
let ranked = primary.pages.flatMap(\.links).map { link in let ranked = primary.pages.flatMap(\.links).map { link in
let words = Set((link.title + " " + link.url.path).lowercased().split { !$0.isLetter }.map(String.init)) let words = Self.words(link.title + " " + link.url.lastPathComponent)
return (link.url, words.intersection(terms).count) return (link.url, words.intersection(terms).count)
}.filter { $0.1 > 0 }.sorted { $0.1 > $1.1 } }.filter { $0.1 > 0 }.sorted { $0.1 > $1.1 }
let related = Array(ranked.map(\.0).filter { seen.insert($0).inserted }.prefix(3)) let related = Array(ranked.map(\.0).filter { seen.insert($0).inserted }.prefix(3))
@@ -341,7 +345,8 @@ enum ChatWebLookup {
let sources = primary.pages + followed.pages let sources = primary.pages + followed.pages
failures += followed.failures failures += followed.failures
let budget = max(1500, 18_000 / max(1, sources.count)) let budget = max(1500, 18_000 / max(1, sources.count))
references = sources.map { "Source: \($0.url.absoluteString)\n\($0.text.prefix(budget))" } let excerpts = sources.map { Self.excerpt($0.text, matching: terms, limit: budget) }
references = zip(sources, excerpts).map { "Source: \($0.url.absoluteString)\n\($1)" }
let status = references.isEmpty ? failures.joined(separator: " ") : "Retrieved \(references.count) web source(s)." let status = references.isEmpty ? failures.joined(separator: " ") : "Retrieved \(references.count) web source(s)."
let notice = failures.isEmpty ? "" : "\n\nWeb lookup errors: \(failures.joined(separator: " "))" let notice = failures.isEmpty ? "" : "\n\nWeb lookup errors: \(failures.joined(separator: " "))"
let reference = """ let reference = """
@@ -349,12 +354,35 @@ enum ChatWebLookup {
\(references.joined(separator: "\n\n"))\(notice) \(references.joined(separator: "\n\n"))\(notice)
""" """
let diagnostics = sources.map { page in let diagnostics = zip(sources, excerpts).map { page, excerpt in
"Fetched \(page.url.host ?? "")\(page.url.path) (\(page.text.count) characters)" "Fetched \(page.url.host ?? "")\(page.url.path) · sent \(excerpt.count) of \(page.text.count) characters to the model"
} + failures } + failures
return (reference, status, browserFallback, diagnostics) return (reference, status, browserFallback, diagnostics)
} }
private static func words(_ text: String) -> Set<String> {
Set(text.lowercased().split { !$0.isLetter }.map(String.init).filter { $0.count > 2 })
}
static func excerpt(_ text: String, matching terms: Set<String>, limit: Int) -> String {
guard text.count > limit, !terms.isEmpty else { return String(text.prefix(limit)) }
let lines = text.split(separator: "\n")
var best = 0
var bestScore = 0
for index in lines.indices {
let matches = words(String(lines[index])).intersection(terms).count
guard matches > 0 else { continue }
let end = min(index + 5, lines.count)
let context = words(lines[index..<end].joined(separator: " "))
let score = matches * 2 + context.intersection(terms).count
if score > bestScore {
best = index
bestScore = score
}
}
return String(lines[max(0, best - 1)...].joined(separator: "\n").prefix(limit))
}
private static func fetch(_ urls: [URL]) async throws -> (pages: [WebPage], failures: [String]) { private static func fetch(_ urls: [URL]) async throws -> (pages: [WebPage], failures: [String]) {
let results = await withTaskGroup(of: (Int, WebPage?, String?).self) { group in let results = await withTaskGroup(of: (Int, WebPage?, String?).self) { group in
for (index, url) in urls.enumerated() { for (index, url) in urls.enumerated() {
+30
View File
@@ -616,6 +616,13 @@ final class BuiltInToolsetTests: XCTestCase {
} }
final class ToolboxRepairTests: XCTestCase { final class ToolboxRepairTests: XCTestCase {
func testWebExcerptIncludesRelevantSectionAfterNavigation() {
let navigation = String(repeating: "Home · Releases · Upgrade\n", count: 100)
let passage = "Service Container\nThe container resolves dependencies."
let excerpt = ChatWebLookup.excerpt(navigation + passage, matching: ["service", "container"], limit: 100)
XCTAssertTrue(excerpt.contains(passage))
}
func testChatWebLookupResolvesTypedURLAndExplicitSearch() async throws { func testChatWebLookupResolvesTypedURLAndExplicitSearch() async throws {
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"], guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"],
let base = URL(string: endpoint)?.deletingLastPathComponent() else { let base = URL(string: endpoint)?.deletingLastPathComponent() else {
@@ -819,6 +826,29 @@ final class ConnectedChatTests: XCTestCase {
XCTAssertEqual(studio.messages.last?.content, "Page received.") XCTAssertEqual(studio.messages.last?.content, "Page received.")
} }
@MainActor
func testLiveOllamaChatUsesRetrievedPage() async throws {
guard let model = ProcessInfo.processInfo.environment["AISTUDIO_TEST_REAL_OLLAMA_MODEL"] else {
throw XCTSkip("Choose a local Ollama model to verify live chat.")
}
let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
defer { try? FileManager.default.removeItem(at: directory) }
let studio = StudioModel()
studio.open(databaseURL: directory.appending(path: "studio.sqlite"))
studio.prompt = "Read https://laravel.com and reply with the name of the framework and the source URL."
var settings = GenerationSettings()
settings.maxTokens = "128"
studio.send(endpoint: "http://127.0.0.1:11434", model: model, mlxPath: "",
thinking: .off, failover: false, mlxOnly: false, compatible: false,
recall: false, useDocuments: false, instructions: "", settings: settings)
let deadline = ContinuousClock.now + .seconds(60)
while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(100)) }
XCTAssertFalse(studio.running)
XCTAssertTrue(studio.webDiagnostics.contains { $0.contains("Fetched laravel.com") })
XCTAssertEqual(studio.messages.last?.role, .assistant)
XCTAssertTrue(studio.messages.last?.content.contains("https://laravel.com") == true, studio.status)
}
func testLiveConnectedGiteaRepositoryLookup() async throws { func testLiveConnectedGiteaRepositoryLookup() async throws {
let env = ProcessInfo.processInfo.environment let env = ProcessInfo.processInfo.environment
guard let path = env["AISTUDIO_TEST_REAL_MCP_CONFIG"], env["AISTUDIO_TEST_REAL_GITEA"] == "1" else { guard let path = env["AISTUDIO_TEST_REAL_MCP_CONFIG"], env["AISTUDIO_TEST_REAL_GITEA"] == "1" else {