{"id":30719852,"url":"https://github.com/dankinsoid/openaimacros","last_synced_at":"2025-09-03T10:42:28.268Z","repository":{"id":303851187,"uuid":"1016868351","full_name":"dankinsoid/OpenAIMacros","owner":"dankinsoid","description":"Macros for OpenAI repo","archived":false,"fork":false,"pushed_at":"2025-07-09T19:28:27.000Z","size":26,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-10T03:33:55.940Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dankinsoid.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-09T16:44:17.000Z","updated_at":"2025-07-09T19:28:31.000Z","dependencies_parsed_at":"2025-07-10T03:42:56.677Z","dependency_job_id":"19666644-d0c1-432a-ade8-a729c1d05a62","html_url":"https://github.com/dankinsoid/OpenAIMacros","commit_stats":null,"previous_names":["dankinsoid/openaimacros"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/dankinsoid/OpenAIMacros","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dankinsoid%2FOpenAIMacros","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dankinsoid%2FOpenAIMacros/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dankinsoid%2FOpenAIMacros/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dankinsoid%2FOpenAIMacros/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dankinsoid","download_url":"https://codeload.github.com/dankinsoid/OpenAIMacros/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dankinsoid%2FOpenAIMacros/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273431361,"owners_count":25104491,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-03T02:00:09.631Z","response_time":76,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-09-03T10:42:27.376Z","updated_at":"2025-09-03T10:42:28.253Z","avatar_url":"https://github.com/dankinsoid.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"# OpenAI Macros\n\nA Swift package that provides macros for seamless integration with OpenAI's function calling API. Instead of manually creating `FunctionDeclaration` structs, simply annotate your Swift functions with `@openAIFunction` and let the macro generate everything automatically.\n\n## Installation\n\nAdd this package to your Swift project:\n\n```swift\ndependencies: [\n    .package(url: \"https://github.com/yourusername/OpenAIMacros\", from: \"1.0.0\")\n]\n```\n\n## Quick Start\n\n### 1. Define Your Functions\n\n```swift\nimport OpenAIMacros\n\nstruct WeatherService {\n    /// Get the current weather for a given location\n    /// - Parameters:\n    ///   - location: The city and state, e.g. San Francisco, CA\n    ///   - unit: Temperature unit (celsius or fahrenheit)\n    @openAIFunction\n    func getCurrentWeather(location: String, unit: TemperatureUnit = .celsius) async throws -\u003e WeatherResponse {\n        // Your implementation here\n        return WeatherResponse(temperature: 22.5, unit: unit, description: \"Sunny\")\n    }\n}\n\nenum TemperatureUnit: String, CaseIterable, Codable {\n    case celsius\n    case fahrenheit\n}\n\nstruct WeatherResponse: Codable {\n    let temperature: Double\n    let unit: TemperatureUnit\n    let description: String\n}\n```\n\n### 2. Use with OpenAI\n\n```swift\nimport OpenAI\nimport OpenAIMacros\n\nlet openAI = OpenAI(apiToken: \"your-api-key\")\nlet weatherService = WeatherService()\n\n// The macro automatically generates getCurrentWeatherCall\nlet result = try await openAI.chatsWith(\n    functions: [weatherService.getCurrentWeatherCall],\n    query: ChatQuery(\n        messages: [.user(.init(content: .string(\"What's the weather like in Boston?\")))],\n        model: \"gpt-4o\"\n    )\n)\n\n// prints \"The current temperature in Boston is 22.5°C.\"\nprint(result.choices[0].message.content ?? \"No response\")\n```\n\n## What the Macro Generates\n\nThe `@openAIFunction` macro automatically generates:\n\n1. **Parameter Struct**: `GetCurrentWeatherParameters` with proper `Codable` support\n2. **Function Wrapper**: `getCurrentWeatherCall` that bridges OpenAI ↔ Swift\n3. **JSON Schema**: Complete parameter validation with types and descriptions\n4. **Custom Decoder**: Handles default values (e.g., `unit` parameter is optional in JSON)\n\n### Generated Code Example\n\n```swift\n// Generated by @openAIFunction\nstruct GetCurrentWeatherParameters: Decodable {\n    let location: String\n    let unit: TemperatureUnit\n    \n    init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        self.location = try container.decode(String.self, forKey: .location)\n        self.unit = try container.decodeIfPresent(TemperatureUnit.self, forKey: .unit) ?? .celsius\n    }\n    \n    private enum CodingKeys: String, CodingKey {\n        case location\n        case unit\n    }\n}\n\nvar getCurrentWeatherCall: OpenAIFunctionWrapper {\n    OpenAIFunctionWrapper(\n        difinition: ChatQuery.ChatCompletionToolParam.FunctionDefinition(\n            name: \"getCurrentWeather\",\n            description: \"Get the current weather for a given location\",\n            parameters: AnyJSONSchema(fields: [\n                .type(.object),\n                .properties([\n                    \"location\": AnyJSONSchema.forType(String.self, description: \"The city and state, e.g. San Francisco, CA\"),\n                    \"unit\": AnyJSONSchema.forType(TemperatureUnit.self, description: \"Temperature unit (celsius or fahrenheit)\")\n                ]),\n                .required([\"location\"])\n            ])\n        )\n    ) { [self] decoder, data, encoder in\n        let parameters = try decoder.decode(GetCurrentWeatherParameters.self, from: data)\n        let result = try await getCurrentWeather(location: parameters.location, unit: parameters.unit)\n        return try encoder.encode(result)\n    }\n}\n```\n\n## Features\n\n### ✅ **Automatic Code Generation**\n- Parameter structs with proper `Codable` support\n- JSON schema generation with type validation\n- Function wrappers that handle the OpenAI ↔ Swift bridge\n\n### ✅ **Smart Type Detection**\n- **Primitives**: `String`, `Int`, `Double`, `Bool`\n- **Enums**: `CaseIterable` types → JSON schema with enum values\n- **Collections**: `Array`, `Dictionary`, `Set` → appropriate JSON types\n- **Custom Types**: `Codable` structs/classes → JSON objects\n- **Optionals**: Proper handling of optional parameters\n\n### ✅ **Default Values Support**\n- Parameters with defaults are optional in JSON\n- Custom decoders handle missing values gracefully\n- `nil` defaults are treated as required parameters\n\n### ✅ **Documentation Integration**\n- Function descriptions from doc comments\n- Parameter descriptions from `@param` documentation\n- Automatic cleanup of doc comment markers\n\n### ✅ **Async/Throws Support**\n- Detects `async` and `throws` in function signatures\n- Generates appropriate `await` and `try` keywords\n- Full support for async throwing functions\n\n### ✅ **Complete Function Calling Workflow**\n- `chatsWith()` method handles the entire OpenAI function calling flow\n- Recursive execution of multiple function calls\n- Proper error handling and result processing\n\n## Advanced Usage\n\n### Multiple Functions (TODO - Future Version)\n\n```swift\n// TODO: This pattern will be supported in a future version\nstruct MyAPI {\n    @openAIFunction\n    func getWeather(location: String) async throws -\u003e WeatherResponse {\n        // Implementation\n    }\n    \n    @openAIFunction\n    func searchRestaurants(location: String, cuisine: String? = nil) async throws -\u003e [Restaurant] {\n        // Implementation\n    }\n    \n    // TODO: Auto-generate this with @OpenAIFunctionsCollection macro\n    var allFunctions: [OpenAIFunctionWrapper] {\n        [getWeatherCall, searchRestaurantsCall]\n    }\n}\n\n// Use all functions\nlet api = MyAPI()\nlet result = try await openAI.chatsWith(\n    functions: api.allFunctions,\n    query: query\n)\n```\n\n**Current workaround**: For now, you need to manually create the `allFunctions` array or call each function wrapper individually.\n\n### Error Handling\n\n```swift\ndo {\n    let result = try await openAI.chatsWith(functions: functions, query: query)\n    // Handle result\n} catch let error as UnknownFunctionCall {\n    print(\"Unknown function: \\(error.functionName)\")\n} catch let error as InvalidString {\n    print(\"String conversion error: \\(error.message)\")\n} catch {\n    print(\"Other error: \\(error)\")\n}\n```\n\n## Requirements\n\n- Swift 5.9+ (for macro support)\n- macOS 10.15+, iOS 13+, tvOS 13+, watchOS 6+\n- [MacPaw's OpenAI Swift library](https://github.com/MacPaw/OpenAI)\n\n## What's Next\n\nThis is the first version of OpenAI Macros. Future versions may include:\n- `@OpenAIFunctionsCollection` macro for automatic function grouping\n- Support for more complex parameter types\n- Integration with other OpenAI Swift libraries\n- Enhanced error handling and debugging\n\n## License\n\nMIT License - see LICENSE file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdankinsoid%2Fopenaimacros","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdankinsoid%2Fopenaimacros","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdankinsoid%2Fopenaimacros/lists"}