Skip to content

Commit c7426bd

Browse files
committed
add document content to support pdf
1 parent b3214b8 commit c7426bd

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//
2+
// DocumentContent.swift
3+
// AnthropicSwiftSDK
4+
//
5+
// Created by 伊藤史 on 2024/11/05.
6+
//
7+
import Foundation
8+
9+
public struct DocumentContent {
10+
public enum DocumentContentType: String, Codable {
11+
case base64
12+
}
13+
14+
public enum DocumentContentMediaType: String, Codable {
15+
case pdf = "application/pdf"
16+
}
17+
18+
public let type: DocumentContentType
19+
public let mediaType: DocumentContentMediaType
20+
public let data: Data
21+
22+
public init(type: DocumentContentType, mediaType: DocumentContentMediaType, data: Data) {
23+
self.type = type
24+
self.mediaType = mediaType
25+
self.data = data
26+
}
27+
}
28+
29+
extension DocumentContent: Codable {
30+
enum CodingKeys: String, CodingKey {
31+
case type
32+
case mediaType = "media_type"
33+
case data
34+
}
35+
36+
public init(from decoder: any Decoder) throws {
37+
let container = try decoder.container(keyedBy: CodingKeys.self)
38+
self.type = try container.decode(DocumentContent.DocumentContentType.self, forKey: .type)
39+
self.mediaType = try container.decode(DocumentContent.DocumentContentMediaType.self, forKey: .mediaType)
40+
self.data = try container.decode(Data.self, forKey: .data)
41+
}
42+
}

Tests/AnthropicSwiftSDKTests/Entity/ContentTests.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,26 @@ final class ContentTests: XCTestCase {
4040
)
4141
}
4242

43+
func testEncodeContentDocument() throws {
44+
let expect = Content.document(
45+
.init(
46+
type: .base64,
47+
mediaType: .pdf,
48+
data: "data".data(using: .utf8)!
49+
)
50+
)
51+
52+
let dictionary = try XCTUnwrap(expect.toDictionary(encoder))
53+
XCTAssertEqual(dictionary["type"] as! String, "document")
54+
let source = try XCTUnwrap(dictionary["source"] as? [String: Any])
55+
XCTAssertEqual(source["type"] as! String, "base64")
56+
XCTAssertEqual(source["media_type"] as! String, "application/pdf")
57+
XCTAssertEqual(
58+
source["data"] as! String,
59+
"data".data(using: .utf8)!.base64EncodedString()
60+
)
61+
}
62+
4363
func testEncodeContentToolResult() throws {
4464
let expect = Content.toolResult(
4565
.init(

0 commit comments

Comments
 (0)