Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Sources/WeiBeiCore/NativeAgentRuntime/NativeAgentEvents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ public struct NativeLLMFailure: Error, LocalizedError, Codable, Equatable, Senda
public var asAgentFailureKind: AgentFailureKind {
if let status {
switch status {
case 400: return .requestRejected
case 401, 403: return .unauthorized
case 429: return .rateLimited
case 408, 504: return .timedOut
Expand All @@ -140,6 +141,7 @@ public struct NativeLLMFailure: Error, LocalizedError, Codable, Equatable, Senda
}
}
switch code {
case "invalid_request": return .requestRejected
case "unauthorized": return .unauthorized
case "rate_limited": return .rateLimited
case "timeout": return .timedOut
Expand Down
31 changes: 29 additions & 2 deletions Sources/WeiBeiCore/NativeAgentRuntime/NativeAgentLoop.swift
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ public actor NativeAgentLoop {
var readItemIDs: [String] = []
var contentBlocks: [AgentMessageContentBlock] = []
var pendingUnstarted: [NativeToolCall] = []
var effectiveSystemPrompt = systemPrompt
var webSearchDisabled = false

do {
var step = 0
Expand All @@ -124,7 +126,7 @@ public actor NativeAgentLoop {
sources.append(source)
}
}
var messages = [NativeModelMessage(role: .system, content: systemPrompt)]
var messages = [NativeModelMessage(role: .system, content: effectiveSystemPrompt)]
messages.append(contentsOf: projection.messages)
if let invariant = NativeAgentInvariant.mismatch(
logged: projection.messages,
Expand All @@ -138,7 +140,7 @@ public actor NativeAgentLoop {
? request.id.uuidString.lowercased()
: request.projectScope.chatID.lowercased()
)
llmRequest.enableNativeWebSearch = tools.contains { $0.name == "weibei_course_map" }
llmRequest.enableNativeWebSearch = !webSearchDisabled && tools.contains { $0.name == "weibei_course_map" }
llmRequest.reasoningEffort = request.reasoningEffort
let effectiveContextWindow = contextWindow ?? adapter.contextWindow
if let effectiveContextWindow {
Expand Down Expand Up @@ -186,6 +188,7 @@ public actor NativeAgentLoop {
var recoveredOverflow = false
streamAttempt: while true {
do {
try checkCancelled()
// Apply this after compaction too: retained history can come from a checkpoint.
llmRequest.messages = llmRequest.messages.map { message in
var message = message
Expand Down Expand Up @@ -258,6 +261,30 @@ public actor NativeAgentLoop {
}
}
break streamAttempt
} catch let failure as NativeLLMFailure
where failure.code == "web_search_unsupported"
&& failure.status == 400
&& !failure.isContextOverflow
&& llmRequest.enableNativeWebSearch
&& !receivedChunk {
try checkCancelled()
webSearchDisabled = true
effectiveSystemPrompt = systemPrompt.replacingOccurrences(
of: NativePromptAssembler.webSearchCapability(available: true), with: ""
) + "\n\n" + NativePromptAssembler.webSearchUnavailable
llmRequest.enableNativeWebSearch = false
llmRequest.messages[0].content = effectiveSystemPrompt
let activity = AgentToolActivity(
id: "\(step):server:search-unavailable", name: "$web_search", state: .failed,
detail: request.language.text("当前服务不支持网页搜索", "Web search is unavailable from this service"),
resultSummary: request.language.text("已关闭本轮后续搜索,继续回答。", "Continuing with web search disabled for the rest of this turn."),
textOffset: collectedText.count
)
_ = try await ledger.append { seq, time in
NativeSessionEvent(type: .assistantChunk, seq: seq, timeMS: time,
turn: turn, step: step, chunk: .serverToolActivity(activity))
}
await progress?(.toolActivity(activity))
} catch let failure as NativeLLMFailure
where failure.isContextOverflow
&& !recoveredOverflow
Expand Down
2 changes: 2 additions & 0 deletions Sources/WeiBeiCore/NativeAgentRuntime/NativeAgentPrompt.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ public struct NativePromptAssembler: Sendable {
: "本服务不提供原生网页搜索;不能声称已搜索,需要外部核实时明确说明未联网。"
}

static let webSearchUnavailable = "本轮后续不提供原生网页搜索。向用户说明搜索不可用,继续依据已获得的资料和其他实际可用工具完成任务;需要新的搜索才能核实的内容应明确尚未核实,不得声称完成了新的联网核实或编造来源。"

/// Reference data is logged separately from the user's words and never changes the system prefix.
public static func turnContext(
for request: StudyAgentRequest,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,10 @@ public struct AnthropicMessagesProvider: NativeLLMAdapter {
NativeHTTPByteStream.start(
session: session,
request: makeURLRequest(request),
fallbackRequest: webSearchTool ? makeURLRequestWithoutSearch(request) : nil,
translate: Self.translate
)
}

private func makeURLRequestWithoutSearch(_ request: NativeLLMRequest) -> URLRequest {
var urlRequest = makeURLRequest(request)
if let body = try? JSONSerialization.data(
withJSONObject: Self.payload(for: request, webSearchTool: false), options: [.sortedKeys]
) {
urlRequest.httpBody = body
}
return urlRequest
}

func makeURLRequest(_ request: NativeLLMRequest) -> URLRequest {
var urlRequest = URLRequest(url: apiURL)
urlRequest.httpMethod = "POST"
Expand Down Expand Up @@ -116,8 +105,7 @@ public struct AnthropicMessagesProvider: NativeLLMAdapter {
"input_schema": tool.schema.object,
]
}
if webSearchTool, request.enableNativeWebSearch
|| request.tools.contains(where: { $0.name == "weibei_course_map" }) {
if webSearchTool, request.enableNativeWebSearch {
if !tools.contains(where: { $0["type"] as? String == "web_search_20250305" }) {
tools.append([
"type": "web_search_20250305",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,10 @@ public struct GoogleGenerativeAIProvider: NativeLLMAdapter {
NativeHTTPByteStream.start(
session: session,
request: makeURLRequest(request),
fallbackRequest: groundingSearch ? makeURLRequestWithoutSearch(request) : nil,
translate: Self.translate
)
}

private func makeURLRequestWithoutSearch(_ request: NativeLLMRequest) -> URLRequest {
var urlRequest = makeURLRequest(request)
if let body = try? JSONSerialization.data(
withJSONObject: Self.payload(for: request, groundingSearch: false), options: [.sortedKeys]
) {
urlRequest.httpBody = body
}
return urlRequest
}

func makeURLRequest(_ request: NativeLLMRequest) -> URLRequest {
let encodedModel = request.model.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? request.model
let root = rootURL.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
Expand Down Expand Up @@ -97,8 +86,7 @@ public struct GoogleGenerativeAIProvider: NativeLLMAdapter {
},
])
}
if groundingSearch, request.enableNativeWebSearch
|| request.tools.contains(where: { $0.name == "weibei_course_map" }) {
if groundingSearch, request.enableNativeWebSearch {
tools.append(["google_search": [:] as [String: Any]])
}
if !tools.isEmpty {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ enum NativeHTTPByteStream {
static func start(
session: URLSession,
request: URLRequest,
fallbackRequest: URLRequest? = nil,
translate: @escaping (String) throws -> [NativeStreamChunk]
) -> AsyncThrowingStream<NativeStreamChunk, Error> {
AsyncThrowingStream { continuation in
let task = Task {
func pump(_ request: URLRequest) async throws {
do {
var request = request
request.timeoutInterval = 300
let (bytes, response) = try await session.bytes(for: request)
Expand All @@ -36,20 +35,7 @@ enum NativeHTTPByteStream {
continuation.yield(chunk)
}
}
}
do {
do {
try await pump(request)
continuation.finish()
} catch let failure as NativeLLMFailure
where failure.status == 400
&& !failure.isContextOverflow
&& fallbackRequest != nil {
// 端点不认服务端搜索工具(如网关未透传):去掉搜索重试一次,
// 本次回答退化为不联网,不让整轮对话失败。
try await pump(fallbackRequest!)
continuation.finish()
}
continuation.finish()
} catch is CancellationError {
continuation.finish(throwing: NativeLLMFailure(code: "cancelled", message: "cancelled"))
} catch let error as URLError where error.code == .timedOut {
Expand All @@ -65,11 +51,25 @@ enum NativeHTTPByteStream {
static func httpFailure(_ status: Int, body: String) -> NativeLLMFailure {
let code: String
switch status {
case 400: code = rejectsWebSearch(body) ? "web_search_unsupported" : "invalid_request"
case 401, 403: code = "unauthorized"
case 429: code = "rate_limited"
case 408, 504: code = "timeout"
default: code = "server_error"
}
return NativeLLMFailure(code: code, status: status, message: "HTTP \(status) \(body)")
}

private static func rejectsWebSearch(_ body: String) -> Bool {
guard let object = try? JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any],
let error = object["error"] as? [String: Any],
let message = error["message"] as? String else { return false }
// ponytail: only explicit search rejection wording; extend when another service response is observed.
let normalized = message.lowercased().replacingOccurrences(of: #"[`'"]"#, with: "", options: .regularExpression)
let search = #"\b(?:web[_ ]search(?:_preview|_\d{8})?|google_search|enable_search)\b"#
return normalized.range(
of: "(?:^(?:(?:hosted )?tool(?: type)? )?\(search) is not supported\\b|^unsupported tool(?: type)?:? \(search)(?:$|[ .]))",
options: .regularExpression
) != nil
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,10 @@ public struct OpenAIChatCompletionsProvider: NativeLLMAdapter {

public func stream(_ request: NativeLLMRequest) -> AsyncThrowingStream<NativeStreamChunk, Error> {
do {
let primary = try makeURLRequest(request, webSearchStyle: webSearchStyle)
let fallback = webSearchStyle == .none
? nil
: try makeURLRequest(request, webSearchStyle: .none)
var textIndex = 0
return NativeHTTPByteStream.start(
session: session,
request: primary,
fallbackRequest: fallback,
request: try makeURLRequest(request),
translate: { try Self.translate(payload: $0, textIndex: &textIndex) }
)
} catch {
Expand All @@ -60,10 +55,6 @@ public struct OpenAIChatCompletionsProvider: NativeLLMAdapter {
}

func makeURLRequest(_ request: NativeLLMRequest) throws -> URLRequest {
try makeURLRequest(request, webSearchStyle: webSearchStyle)
}

func makeURLRequest(_ request: NativeLLMRequest, webSearchStyle style: ChatWebSearchStyle) throws -> URLRequest {
var urlRequest = URLRequest(url: baseURL.appendingPathComponent("chat/completions"))
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
Expand Down Expand Up @@ -122,10 +113,8 @@ public struct OpenAIChatCompletionsProvider: NativeLLMAdapter {
payload["stream_options"] = ["include_usage": true]
}
var allTools = tools
let enableSearch = request.enableNativeWebSearch
|| request.tools.contains(where: { $0.name == "weibei_course_map" })
if enableSearch {
switch style {
if request.enableNativeWebSearch {
switch webSearchStyle {
case .none:
break
case .zai:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,10 @@ public struct OpenAIResponsesProvider: NativeLLMAdapter {
return NativeHTTPByteStream.start(
session: session,
request: makeURLRequest(request),
fallbackRequest: webSearchSupported ? makeURLOrURLRequestWithoutSearch(request) : nil,
translate: { try Self.translate($0, completedItems: &completedItems) }
)
}

private func makeURLOrURLRequestWithoutSearch(_ request: NativeLLMRequest) -> URLRequest {
var urlRequest = makeURLRequest(request)
if let body = try? JSONSerialization.data(
withJSONObject: Self.payload(for: request, webSearchSupported: false), options: [.sortedKeys]
) {
urlRequest.httpBody = body
}
return urlRequest
}

func makeURLRequest(_ request: NativeLLMRequest) -> URLRequest {
var urlRequest = URLRequest(url: baseURL.appendingPathComponent("responses"))
urlRequest.httpMethod = "POST"
Expand Down Expand Up @@ -110,9 +99,7 @@ public struct OpenAIResponsesProvider: NativeLLMAdapter {
]
}
var include = ["reasoning.encrypted_content"]
let enableSearch = request.enableNativeWebSearch
|| request.tools.contains(where: { $0.name == "weibei_course_map" })
if enableSearch, webSearchSupported {
if request.enableNativeWebSearch, webSearchSupported {
if !tools.contains(where: { $0["type"] as? String == "web_search" }) {
tools.append(["type": "web_search"])
}
Expand Down
10 changes: 10 additions & 0 deletions Sources/WeiBeiCore/StudyAgentRuntime.swift
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,7 @@ public typealias StudyAgentSessionTitleHandler = @Sendable (String) async -> Voi
/// User-facing classification for Agent request failures.
public enum AgentFailureKind: String, Codable, Equatable, Sendable {
case offline
case requestRejected
case unauthorized
case rateLimited
case serverError
Expand All @@ -896,6 +897,8 @@ public enum AgentFailureKind: String, Codable, Equatable, Sendable {
switch self {
case .offline:
return language.text("网络不可用", "Network unavailable")
case .requestRejected:
return language.text("模型服务未接受请求", "Model service rejected the request")
case .unauthorized:
return language.text("认证已失效", "Authentication expired")
case .rateLimited:
Expand All @@ -921,6 +924,11 @@ public enum AgentFailureKind: String, Codable, Equatable, Sendable {
switch self {
case .offline:
return language.text("请检查本机网络后重试。", "Check your network connection, then retry.")
case .requestRejected:
return language.text(
"请检查所选模型、服务地址或请求内容后重试。",
"Check the selected model, service URL, or request content, then retry."
)
case .unauthorized:
return language.text(
"请到设置中重新登录,或重新保存 API Key。",
Expand Down Expand Up @@ -969,6 +977,8 @@ public enum AgentFailureKind: String, Codable, Equatable, Sendable {
}
if ns.domain == "WeiBei.OpenAI" || ns.domain == "WeiBei.NativeAgent" {
switch ns.code {
case 400:
return .requestRejected
case 401, 403:
return .unauthorized
case 429:
Expand Down
2 changes: 1 addition & 1 deletion Sources/WeiBeiSelfCheck/NativeAgentSelfChecks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ private func checkWebSearchPayloadInjection() throws {
schema: NativeJSONSchema(["type": "object"]),
execute: { _, _ in NativeToolExecutionResult(text: "") }
)
let request = NativeLLMRequest(model: "test", messages: [], tools: [courseMap])
let request = NativeLLMRequest(model: "test", messages: [], tools: [courseMap], enableNativeWebSearch: true)

let responsesOn = OpenAIResponsesProvider.payload(for: request, webSearchSupported: true)
try nativeRequire(
Expand Down
Loading
Loading