Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@

import Foundation

// MARK: - ChatCompletionChunkObject

/// Represents a [streamed](https://platform.openai.com/docs/api-reference/chat/streaming) chunk of a chat completion response returned by model, based on the provided input.
public struct ChatCompletionChunkObject: Decodable {
public struct ChatChoice: Decodable {
public struct Delta: Decodable {
/// The contents of the chunk message.
public let content: String?
/// The reasoning content generated by the model, if available.
/// The reasoning content generated by the model, from `reasoning_content` or OpenRouter's `reasoning` field.
public let reasoningContent: String?
/// The tool calls generated by the model, such as function calls.
public let toolCalls: [ToolCall]?
Expand All @@ -28,11 +30,13 @@ public struct ChatCompletionChunkObject: Decodable {
enum CodingKeys: String, CodingKey {
case content
case reasoningContent = "reasoning_content"
case reasoning
case toolCalls = "tool_calls"
case functionCall = "function_call"
case role
case refusal
}

}

public struct LogProb: Decodable {
Expand Down Expand Up @@ -119,3 +123,17 @@ public struct ChatCompletionChunkObject: Decodable {
case usage
}
}

extension ChatCompletionChunkObject.ChatChoice.Delta {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try self.init(
content: container.decodeIfPresent(String.self, forKey: .content),
reasoningContent: container.decodeIfPresent(String.self, forKey: .reasoningContent)
?? container.decodeIfPresent(String.self, forKey: .reasoning),
toolCalls: container.decodeIfPresent([ToolCall].self, forKey: .toolCalls),
functionCall: container.decodeIfPresent(FunctionCall.self, forKey: .functionCall),
role: container.decodeIfPresent(String.self, forKey: .role),
refusal: container.decodeIfPresent(String.self, forKey: .refusal))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import Foundation

// MARK: - ChatCompletionObject

/// Represents a chat [completion](https://platform.openai.com/docs/api-reference/chat/object) response returned by model, based on the provided input.
public struct ChatCompletionObject: Decodable {
public struct ChatChoice: Decodable {
Expand Down Expand Up @@ -43,7 +45,7 @@ public struct ChatCompletionObject: Decodable {
public let functionCall: FunctionCall?
/// The role of the author of this message.
public let role: String?
/// The reasoning content generated by the model, if available.
/// The reasoning content generated by the model, from `reasoning_content` or OpenRouter's `reasoning` field.
public let reasoningContent: String?
/// Provided by the Vision API.
public let finishDetails: FinishDetails?
Expand All @@ -59,9 +61,11 @@ public struct ChatCompletionObject: Decodable {
case role
case finishDetails = "finish_details"
case reasoningContent = "reasoning_content"
case reasoning
case refusal
case audio
}

}

public struct LogProb: Decodable {
Expand Down Expand Up @@ -140,3 +144,19 @@ public struct ChatCompletionObject: Decodable {
case usage
}
}

extension ChatCompletionObject.ChatChoice.ChatMessage {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try self.init(
content: container.decodeIfPresent(String.self, forKey: .content),
toolCalls: container.decodeIfPresent([ToolCall].self, forKey: .toolCalls),
functionCall: container.decodeIfPresent(FunctionCall.self, forKey: .functionCall),
role: container.decodeIfPresent(String.self, forKey: .role),
reasoningContent: container.decodeIfPresent(String.self, forKey: .reasoningContent)
?? container.decodeIfPresent(String.self, forKey: .reasoning),
finishDetails: container.decodeIfPresent(FinishDetails.self, forKey: .finishDetails),
refusal: container.decodeIfPresent(String.self, forKey: .refusal),
audio: container.decodeIfPresent(Audio.self, forKey: .audio))
}
}
92 changes: 92 additions & 0 deletions Tests/OpenAITests/ChatReasoningDecodingTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import XCTest
@testable import SwiftOpenAI

final class ChatReasoningDecodingTests: XCTestCase {
func testStreamingOpenRouterReasoningIsPreserved() throws {
let delta = try decodeDelta(["reasoning": " Thinking...\n理由"])
XCTAssertEqual(delta.reasoningContent, " Thinking...\n理由")
}

func testNonStreamingOpenRouterReasoningIsPreserved() throws {
let message = try decodeMessage(["reasoning": " Thinking...\n理由"])
XCTAssertEqual(message.reasoningContent, " Thinking...\n理由")
}

func testExistingReasoningContentAndAliasPrecedence() throws {
let cases: [(fields: [String: Any], expected: String)] = [
(["reasoning_content": "Existing reasoning"], "Existing reasoning"),
(["reasoning_content": "Existing reasoning", "reasoning": "Alias"], "Existing reasoning"),
(["reasoning_content": "", "reasoning": "Alias"], ""),
(["reasoning_content": NSNull(), "reasoning": "Alias"], "Alias"),
]
for (fields, expected) in cases {
XCTAssertEqual(try decodeDelta(fields).reasoningContent, expected)
XCTAssertEqual(try decodeMessage(fields).reasoningContent, expected)
}
}

func testReasoningRemainsOptional() throws {
for fields: [String: Any] in [[:], ["reasoning": NSNull()], ["reasoning_content": NSNull()]] {
XCTAssertNil(try decodeDelta(fields).reasoningContent)
XCTAssertNil(try decodeMessage(fields).reasoningContent)
}
}

func testStreamingOtherFieldsArePreserved() throws {
let delta = try decodeDelta([
"content": "Answer",
"reasoning": "Reasoning",
"role": "assistant",
"refusal": "Refusal",
"tool_calls": [["id": "call_1", "type": "function", "function": ["name": "lookup", "arguments": "{}"]]],
"function_call": ["name": "legacy", "arguments": "{}"],
])
XCTAssertEqual(delta.content, "Answer")
XCTAssertEqual(delta.role, "assistant")
XCTAssertEqual(delta.refusal, "Refusal")
XCTAssertEqual(delta.toolCalls?.first?.id, "call_1")
XCTAssertEqual(delta.functionCall?.name, "legacy")
}

func testNonStreamingOtherFieldsArePreserved() throws {
let message = try decodeMessage([
"content": "Answer",
"reasoning": "Reasoning",
"role": "assistant",
"refusal": "Refusal",
"tool_calls": [["id": "call_1", "type": "function", "function": ["name": "lookup", "arguments": "{}"]]],
"function_call": ["name": "legacy", "arguments": "{}"],
"finish_details": ["type": "stop"],
"audio": ["id": "audio_1", "expires_at": 123, "data": "YQ==", "transcript": "Answer"],
])
XCTAssertEqual(message.content, "Answer")
XCTAssertEqual(message.role, "assistant")
XCTAssertEqual(message.refusal, "Refusal")
XCTAssertEqual(message.toolCalls?.first?.id, "call_1")
XCTAssertEqual(message.functionCall?.name, "legacy")
XCTAssertEqual(message.finishDetails?.type, "stop")
XCTAssertEqual(message.audio?.id, "audio_1")
XCTAssertEqual(message.audio?.expiresAt, 123)
XCTAssertEqual(message.audio?.data, "YQ==")
XCTAssertEqual(message.audio?.transcript, "Answer")
}

func testInvalidReasoningTypesAreRejected() {
for fields in [["reasoning": 42], ["reasoning_content": 42]] {
XCTAssertThrowsError(try decodeDelta(fields))
XCTAssertThrowsError(try decodeMessage(fields))
}
}

private func decodeDelta(_ fields: [String: Any]) throws -> ChatCompletionChunkObject.ChatChoice.Delta {
let data = try JSONSerialization.data(withJSONObject: ["choices": [["delta": fields]]])
let response = try JSONDecoder().decode(ChatCompletionChunkObject.self, from: data)
return try XCTUnwrap(response.choices?.first?.delta)
}

private func decodeMessage(_ fields: [String: Any]) throws -> ChatCompletionObject.ChatChoice.ChatMessage {
let data = try JSONSerialization.data(withJSONObject: ["choices": [["message": fields]]])
let response = try JSONDecoder().decode(ChatCompletionObject.self, from: data)
return try XCTUnwrap(response.choices?.first?.message)
}
}