Skip to content
Merged
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
4 changes: 2 additions & 2 deletions Sources/AnyLanguageModel/Models/AnthropicLanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ public struct AnthropicLanguageModel: LanguageModel, ProfileRequestIdentifiedLan
)
let message: AnthropicMessageResponse = try await transport.fetch(
HTTPRequest(method: .post, url: url, headerFields: headers),
body: try JSONEncoder().encode(params)
body: try encodeRequestBody(params)
)
usage.add(message.usage?.reportedUsage)

Expand Down Expand Up @@ -732,7 +732,7 @@ public struct AnthropicLanguageModel: LanguageModel, ProfileRequestIdentifiedLan
options: requestContext.options
)
params["stream"] = .bool(true)
let body = try JSONEncoder().encode(params)
let body = try encodeRequestBody(params)
let events: AsyncThrowingStream<AnthropicStreamEvent, any Error> =
transport.fetchEventStream(
HTTPRequest(method: .post, url: url, headerFields: headers),
Expand Down
4 changes: 2 additions & 2 deletions Sources/AnyLanguageModel/Models/GeminiLanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ public struct GeminiLanguageModel: LanguageModel, ProfileRequestIdentifiedLangua
jsonMode: effectiveJsonMode
)

let body = try JSONEncoder().encode(params)
let body = try encodeRequestBody(params)

let response: GeminiGenerateContentResponse = try await transport.fetch(
HTTPRequest(method: .post, url: url, headerFields: headers),
Expand Down Expand Up @@ -505,7 +505,7 @@ public struct GeminiLanguageModel: LanguageModel, ProfileRequestIdentifiedLangua
thinking: effectiveThinking,
jsonMode: effectiveJsonMode
)
let body = try JSONEncoder().encode(params)
let body = try encodeRequestBody(params)
let stream: AsyncThrowingStream<GeminiGenerateContentResponse, any Error> =
transport.fetchEventStream(
HTTPRequest(method: .post, url: url, headerFields: headers),
Expand Down
12 changes: 2 additions & 10 deletions Sources/AnyLanguageModel/Models/OllamaLanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ public struct OllamaLanguageModel: LanguageModel, ProfileRequestIdentifiedLangua
)
let reply: ChatReply = try await transport.fetch(
HTTPRequest(method: .post, url: url, headerFields: headerFields),
body: try encodeChatParams(params),
body: try encodeRequestBody(params),
dateDecodingStrategy: .iso8601WithFractionalSeconds
)
let chatResponse = try reply.response()
Expand Down Expand Up @@ -460,7 +460,7 @@ public struct OllamaLanguageModel: LanguageModel, ProfileRequestIdentifiedLangua
format: format,
parameters: extractTopLevelChatParameters(requestContext.options)
)
let body = try encodeChatParams(params)
let body = try encodeRequestBody(params)
let chunks: AsyncThrowingStream<ChatReply, any Error> = transport.fetchStream(
HTTPRequest(method: .post, url: url, headerFields: headerFields),
body: body,
Expand Down Expand Up @@ -693,14 +693,6 @@ private func convertToolToOllamaFormat(_ tool: any Tool) throws -> [String: JSON
]
}

private func encodeChatParams(_ params: [String: JSONValue]) throws -> Data {
let encoder = JSONEncoder()
// Ollama reuses prompt prefixes only when their serialized bytes match.
// Dictionary iteration order must not vary between equivalent requests.
encoder.outputFormatting = [.sortedKeys]
return try encoder.encode(params)
}

private func convertSchemaToOllamaFormat(_ schema: GenerationSchema) throws -> JSONSchema {
// Ollama's documentation doesn't list `const`.
try schema.inlinedJSONSchema(constantsAsEnums: true)
Expand Down
16 changes: 3 additions & 13 deletions Sources/AnyLanguageModel/Models/OpenAILanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,6 @@ public struct OpenAILanguageModel: LanguageModel, ProfileRequestIdentifiedLangua
/// The default base URL for OpenAI's API.
public static let defaultBaseURL = URL(string: "https://api.openai.com/v1/")!

/// Encodes a request body with its object keys sorted at every level,
/// so the same request encodes to the same bytes every time.
/// This keeps the prompt prefix stable,
/// which lets a provider's prompt cache hit when it matches on that prefix.
static func encodeBody(_ value: some Encodable) throws -> Data {
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
return try encoder.encode(value)
}

/// The OpenAI API variant to use.
public enum APIVariant: Sendable {
/// When selected, use the Chat Completions API.
Expand Down Expand Up @@ -601,7 +591,7 @@ public struct OpenAILanguageModel: LanguageModel, ProfileRequestIdentifiedLangua
)

let url = baseURL.appendingPathComponent("chat/completions")
let body = try Self.encodeBody(params)
let body = try encodeRequestBody(params)
let resp: ChatCompletions.Response = try await transport.fetch(
HTTPRequest(method: .post, url: url, headerFields: buildHeaders()),
body: body
Expand Down Expand Up @@ -778,7 +768,7 @@ public struct OpenAILanguageModel: LanguageModel, ProfileRequestIdentifiedLangua
stream: false
)

let body = try Self.encodeBody(params)
let body = try encodeRequestBody(params)
let resp: Responses.Response = try await transport.fetch(
HTTPRequest(method: .post, url: url, headerFields: buildHeaders()),
body: body
Expand Down Expand Up @@ -982,7 +972,7 @@ public struct OpenAILanguageModel: LanguageModel, ProfileRequestIdentifiedLangua
includeUsage: baseURL.host == Self.defaultBaseURL.host
)
}
let body = try Self.encodeBody(params)
let body = try encodeRequestBody(params)
let url = baseURL.appendingPathComponent(path)
let headers: HTTPFields = buildHeaders()
var toolCalls: [OpenAIToolCall] = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ public struct OpenResponsesLanguageModel: LanguageModel, ProfileRequestIdentifie
options: requestContext.options,
stream: true
)
let body = try JSONEncoder().encode(params)
let body = try encodeRequestBody(params)
let events: AsyncThrowingStream<OpenResponsesStreamEvent, any Error> =
transport.fetchEventStream(
HTTPRequest(
Expand Down Expand Up @@ -756,7 +756,7 @@ public struct OpenResponsesLanguageModel: LanguageModel, ProfileRequestIdentifie
options: requestContext.options,
stream: false
)
let body = try JSONEncoder().encode(params)
let body = try encodeRequestBody(params)
let resp: OpenResponsesAPI.Response = try await transport.fetch(
HTTPRequest(method: .post, url: url, headerFields: buildHeaders()),
body: body
Expand Down
10 changes: 10 additions & 0 deletions Sources/AnyLanguageModel/Shared/HTTPTransport+Fetch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,16 @@ public struct HTTPTransportError: Error, Sendable, CustomStringConvertible {
}
}

/// Encodes a request body with its object keys sorted at every level,
/// so the same request encodes to the same bytes every time.
/// This keeps the prompt prefix stable,
/// which lets a provider's prompt cache hit when it matches on that prefix.
func encodeRequestBody(_ value: some Encodable) throws -> Data {
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
return try encoder.encode(value)
}

/// What every transport's requests to a model's provider are made of, written once on top of
/// ``HTTPTransport/send(request:body:timeout:responseHandler:)``: an answer decoded from JSON,
/// one decoded from each line of a stream as it arrives, and one from each event of a stream
Expand Down
212 changes: 212 additions & 0 deletions Tests/AnyLanguageModelTests/ProviderRequestBodySortingTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
import Foundation
import Testing

@testable import AnyLanguageModel

/// Every remote provider encodes request bodies with keys sorted at every level,
/// so equivalent requests produce identical bytes for prompt-cache prefix matching.
@Suite("Provider request body key sorting")
struct ProviderRequestBodySortingTests {
private static let nestedExtraBody: [String: JSONValue] = [
"vendor_options": .object([
"zeta": .int(1),
"alpha": .object(["omega": .bool(true), "beta": .string("b")]),
"mu": .array([.object(["y": .null, "b": .double(0.5)])]),
])
]

@Test(arguments: [false, true])
func anthropicRequestBodyKeysAreSortedAtEveryLevel(streaming: Bool) async throws {
let transport = FakeTransport(replies: [try Self.anthropicReply(streaming: streaming)])
let model = AnthropicLanguageModel(apiKey: "test", model: "test", transport: transport)
var options = GenerationOptions()
options[custom: AnthropicLanguageModel.self] = .init(extraBody: Self.nestedExtraBody)
let session = LanguageModelSession(
model: model,
tools: [MultiFieldTool()],
instructions: "Be concise."
)

try await Self.respond(in: session, options: options, streaming: streaming)

let body = try #require(transport.bodies.last)
let json = try Self.jsonObject(body)
#expect(json["vendor_options"] is [String: Any])
#expect((json["tools"] as? [[String: Any]])?.count == 1)
try Self.expectKeysSortedAtEveryLevel(body)
}

@Test(arguments: [false, true])
func geminiRequestBodyKeysAreSortedAtEveryLevel(streaming: Bool) async throws {
let transport = FakeTransport(replies: [try Self.geminiReply(streaming: streaming)])
let model = GeminiLanguageModel(apiKey: "test", model: "test", transport: transport)
var options = GenerationOptions(temperature: 0.2, maximumResponseTokens: 128)
options[custom: GeminiLanguageModel.self] = .init(thinking: .budget(256))
let session = LanguageModelSession(
model: model,
tools: [MultiFieldTool()],
instructions: "Be concise."
)

try await Self.respond(in: session, options: options, streaming: streaming)

let body = try #require(transport.bodies.last)
let json = try Self.jsonObject(body)
#expect(json["generationConfig"] is [String: Any])
#expect((json["tools"] as? [[String: Any]])?.count == 1)
try Self.expectKeysSortedAtEveryLevel(body)
}

@Test(arguments: [false, true])
func openResponsesRequestBodyKeysAreSortedAtEveryLevel(streaming: Bool) async throws {
let transport = FakeTransport(replies: [try Self.openResponsesReply(streaming: streaming)])
let model = OpenResponsesLanguageModel(
baseURL: URL(string: "https://example.com/v1")!,
apiKey: "test",
model: "test",
transport: transport
)
var options = GenerationOptions()
options[custom: OpenResponsesLanguageModel.self] = .init(extraBody: Self.nestedExtraBody)
let session = LanguageModelSession(
model: model,
tools: [MultiFieldTool()],
instructions: "Be concise."
)

try await Self.respond(in: session, options: options, streaming: streaming)

let body = try #require(transport.bodies.last)
let json = try Self.jsonObject(body)
#expect(json["vendor_options"] is [String: Any])
#expect((json["tools"] as? [[String: Any]])?.count == 1)
try Self.expectKeysSortedAtEveryLevel(body)
}

@Test(arguments: [false, true])
func ollamaRequestBodyKeysAreSortedAtEveryLevel(streaming: Bool) async throws {
let transport = FakeTransport(replies: [try Self.ollamaReply(streaming: streaming)])
let model = OllamaLanguageModel(model: "test", transport: transport)
var options = GenerationOptions(temperature: 0.2, maximumResponseTokens: 128)
options[custom: OllamaLanguageModel.self] = [
"top_p": .double(0.9),
"repeat_penalty": .double(1.1),
"seed": .int(42),
]
let session = LanguageModelSession(
model: model,
tools: [MultiFieldTool()],
instructions: "Be concise."
)

try await Self.respond(in: session, options: options, streaming: streaming)

let body = try #require(transport.bodies.last)
let json = try Self.jsonObject(body)
#expect(json["options"] is [String: Any])
#expect((json["tools"] as? [[String: Any]])?.count == 1)
try Self.expectKeysSortedAtEveryLevel(body)
}

// MARK: - Helpers

private static func respond(
in session: LanguageModelSession,
options: GenerationOptions,
streaming: Bool
) async throws {
if streaming {
_ = try await session.streamResponse(to: "Weather in Paris?", options: options).collect()
} else {
_ = try await session.respond(to: "Weather in Paris?", options: options)
}
}

private static func jsonObject(_ data: Data) throws -> [String: Any] {
try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any])
}

/// Re-encoding the body with sorted keys changes no byte only if every object,
/// at every level, already has its keys sorted.
private static func expectKeysSortedAtEveryLevel(_ body: Data) throws {
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let sorted = try encoder.encode(try JSONDecoder().decode(JSONValue.self, from: body))
#expect(String(decoding: body, as: UTF8.self) == String(decoding: sorted, as: UTF8.self))
}

private static func encode(_ object: [String: Any]) throws -> String {
String(decoding: try JSONSerialization.data(withJSONObject: object), as: UTF8.self)
}

// MARK: - Fixtures

struct MultiFieldTool: Tool {
let name = "getWeather"
let description = "Weather for a city"

@Generable
struct Arguments {
var city: String
var unit: String
var days: Int
}

func call(arguments: Arguments) async throws -> String { "Sunny" }
}

private static func anthropicReply(streaming: Bool) throws -> FakeTransport.Reply {
func message(_ content: [[String: Any]]) -> [String: Any] {
[
"id": "m", "type": "message", "role": "assistant", "model": "test",
"content": content, "stop_reason": "end_turn",
"usage": ["input_tokens": 1, "output_tokens": 1],
]
}
guard streaming else {
return .init(chunks: [try encode(message([["type": "text", "text": "Done."]]))])
}
let events: [[String: Any]] = [
["type": "message_start", "message": message([])],
["type": "content_block_start", "index": 0, "content_block": ["type": "text", "text": ""]],
["type": "content_block_delta", "index": 0, "delta": ["type": "text_delta", "text": "Done."]],
["type": "content_block_stop", "index": 0],
["type": "message_stop"],
]
return .init(chunks: try events.map { "data: \(try encode($0))\n\n" })
}

private static func geminiReply(streaming: Bool) throws -> FakeTransport.Reply {
let object: [String: Any] = [
"candidates": [["content": ["role": "model", "parts": [["text": "Done."]]], "finishReason": "STOP"]]
]
let body = try encode(object)
return .init(chunks: [streaming ? "data: \(body)\n\n" : body])
}

private static func openResponsesReply(streaming: Bool) throws -> FakeTransport.Reply {
let response: [String: Any] = [
"id": "resp_1",
"output": [["type": "message", "content": [["type": "output_text", "text": "Done."]]]],
]
guard streaming else {
return .init(chunks: [try encode(response)])
}
let events: [[String: Any]] = [
["type": "response.output_text.delta", "delta": "Done."],
["type": "response.completed", "response": response],
]
return .init(chunks: try events.map { "data: \(try encode($0))\n\n" })
}

private static func ollamaReply(streaming: Bool) throws -> FakeTransport.Reply {
let reply: [String: Any] = [
"model": "test",
"created_at": "2026-09-11T00:00:00.000Z",
"message": ["role": "assistant", "content": "Done."],
"done": true,
]
let body = try encode(reply)
return .init(chunks: [streaming ? "\(body)\n" : body])
}
}
Loading