|
| 1 | +// The Swift Programming Language |
| 2 | +// https://docs.swift.org/swift-book |
| 3 | + |
| 4 | +import FunctionCalling |
| 5 | +import AIProxy |
| 6 | + |
| 7 | +extension ToolContainer { |
| 8 | + // https://github.com/lzell/AIProxySwift?tab=readme-ov-file#how-to-use-openai-structured-outputs-json-schemas-in-a-tool-call |
| 9 | + func toOpenAITools(strict: Bool = false) -> [OpenAIChatCompletionTool] { |
| 10 | + guard let allTools else { return [] } |
| 11 | + |
| 12 | + return allTools.map { tool in |
| 13 | + OpenAIChatCompletionTool.function( |
| 14 | + name: tool.name, |
| 15 | + description: tool.description, |
| 16 | + parameters: tool.inputSchema.toJSONSchema(), |
| 17 | + strict: strict |
| 18 | + ) |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + // https://github.com/lzell/AIProxySwift?tab=readme-ov-file#how-to-use-streaming-tool-calls-with-anthropic |
| 23 | + func toAnthropicTools() -> [AnthropicTool] { |
| 24 | + guard let allTools else { return [] } |
| 25 | + |
| 26 | + return allTools.map { tool in |
| 27 | + AnthropicTool( |
| 28 | + description: tool.description, |
| 29 | + inputSchema: tool.inputSchema.toJSONSchema(), |
| 30 | + name: tool.name |
| 31 | + ) |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + // https://github.com/lzell/AIProxySwift?tab=readme-ov-file#how-to-make-a-tool-call-request-with-llama-and-togetherai |
| 36 | + func toTogetherAITools() -> [TogetherAITool] { |
| 37 | + guard let allTools else { return [] } |
| 38 | + |
| 39 | + return allTools.map { tool in |
| 40 | + TogetherAITool( |
| 41 | + function: .init( |
| 42 | + description: tool.description, |
| 43 | + name: tool.name, |
| 44 | + parameters: tool.inputSchema.toJSONSchema() |
| 45 | + ) |
| 46 | + ) |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +private extension FunctionCalling.InputSchema { |
| 52 | + func toJSONSchema() -> [String: AIProxyJSONValue] { |
| 53 | + var jsonSchema: [String: AIProxyJSONValue] = [ |
| 54 | + "type": .string(self.type.rawValue) |
| 55 | + ] |
| 56 | + |
| 57 | + if let format { |
| 58 | + jsonSchema["format"] = .string(format) |
| 59 | + } |
| 60 | + |
| 61 | + if let description { |
| 62 | + jsonSchema["description"] = .string(description) |
| 63 | + } |
| 64 | + |
| 65 | + if let nullable { |
| 66 | + jsonSchema["nullable"] = .bool(nullable) |
| 67 | + } |
| 68 | + |
| 69 | + if let enumValues { |
| 70 | + jsonSchema["enum"] = .array(enumValues.map { .string($0) }) |
| 71 | + } |
| 72 | + |
| 73 | + if let items { |
| 74 | + jsonSchema["items"] = .object(items.toJSONSchema()) |
| 75 | + } |
| 76 | + |
| 77 | + if let properties { |
| 78 | + jsonSchema["properties"] = .object(properties.mapValues { AIProxyJSONValue.object($0.toJSONSchema()) }) |
| 79 | + } |
| 80 | + |
| 81 | + if let requiredProperties { |
| 82 | + jsonSchema["required"] = .array(requiredProperties.map { .string($0) }) |
| 83 | + } |
| 84 | + |
| 85 | + return jsonSchema |
| 86 | + } |
| 87 | +} |
0 commit comments