Build AI Studio 1.1 for macOS #1
+35
-7
@@ -126,7 +126,7 @@ enum WebClipCapture {
|
||||
throw StudioError("The page contains no readable text.")
|
||||
}
|
||||
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] {
|
||||
@@ -330,10 +330,14 @@ enum ChatWebLookup {
|
||||
browserFallback = browser?.url
|
||||
}
|
||||
var seen = Set(choices + primary.pages.map(\.url))
|
||||
let terms = Set(LibraryImport.matchQuery(topic).components(separatedBy: " OR ")
|
||||
.map { $0.trimmingCharacters(in: CharacterSet(charactersIn: "\"")) }.filter { !$0.isEmpty })
|
||||
let hosts = Set(primary.pages.compactMap { $0.url.host }.flatMap { Self.words($0) })
|
||||
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 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)
|
||||
}.filter { $0.1 > 0 }.sorted { $0.1 > $1.1 }
|
||||
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
|
||||
failures += followed.failures
|
||||
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 notice = failures.isEmpty ? "" : "\n\nWeb lookup errors: \(failures.joined(separator: " "))"
|
||||
let reference = """
|
||||
@@ -349,12 +354,35 @@ enum ChatWebLookup {
|
||||
|
||||
\(references.joined(separator: "\n\n"))\(notice)
|
||||
"""
|
||||
let diagnostics = sources.map { page in
|
||||
"Fetched \(page.url.host ?? "")\(page.url.path) (\(page.text.count) characters)"
|
||||
let diagnostics = zip(sources, excerpts).map { page, excerpt in
|
||||
"Fetched \(page.url.host ?? "")\(page.url.path) · sent \(excerpt.count) of \(page.text.count) characters to the model"
|
||||
} + failures
|
||||
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]) {
|
||||
let results = await withTaskGroup(of: (Int, WebPage?, String?).self) { group in
|
||||
for (index, url) in urls.enumerated() {
|
||||
|
||||
@@ -616,6 +616,13 @@ final class BuiltInToolsetTests: 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 {
|
||||
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"],
|
||||
let base = URL(string: endpoint)?.deletingLastPathComponent() else {
|
||||
@@ -819,6 +826,29 @@ final class ConnectedChatTests: XCTestCase {
|
||||
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 {
|
||||
let env = ProcessInfo.processInfo.environment
|
||||
guard let path = env["AISTUDIO_TEST_REAL_MCP_CONFIG"], env["AISTUDIO_TEST_REAL_GITEA"] == "1" else {
|
||||
|
||||
Reference in New Issue
Block a user