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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ jobs:
- uses: actions/checkout@v4
- name: Set up Homebrew
id: set-up-homebrew
uses: Homebrew/actions/setup-homebrew@master
uses: Homebrew/actions/setup-homebrew@main
- name: Install swiftformat
run: brew install swiftformat
- name: Check formatting
Expand Down
76 changes: 75 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ An open-source Swift package designed for effortless interaction with OpenAI's p
- [Vector Stores](#vector-stores)
- [Vector store File](#vector-store-file)
- [Vector store File Batch](#vector-store-file-batch)
- [Agents](#agents)

## Getting an API Key

Expand Down Expand Up @@ -1622,6 +1623,7 @@ OpenAI's most advanced interface for generating model responses. Supports text a
- Support for reasoning summaries, web search, file search, and image generation events
- **NEW**: Support for GPT-5 models (gpt-5, gpt-5-mini, gpt-5-nano)
- **NEW**: Verbosity parameter for controlling response detail level
- **NEW**: Support for GPT-6 models (gpt-6-astra, gpt-6.1-sol) and the Ultrafast service tier

#### ModelResponseParameter

Expand All @@ -1641,17 +1643,33 @@ let parameters = ModelResponseParameter(
let response = try await service.responseCreate(parameters)
```

#### Available GPT-5 Models
#### Available GPT-5 and GPT-6 Models

```swift
public enum Model {
case gpt5 // Complex reasoning, broad world knowledge, and code-heavy or multi-step agentic tasks
case gpt5Mini // Cost-optimized reasoning and chat; balances speed, cost, and capability
case gpt5Nano // High-throughput tasks, especially simple instruction-following or classification
case gpt6Astra // Flagship model for complex reasoning and agentic tasks
case gpt61Sol // Near-Astra intelligence at a fifth of the price; 1M+ token context window
// ... other models
}
```

#### Ultrafast Service Tier

The [Ultrafast service tier](https://developers.openai.com/api/docs/guides/ultrafast-mode) offers up to 6x faster token generation at a premium price. It is available in the Responses API for `gpt-6-astra` (broadly available) and `gpt-5.6-sol` (preview access):

```swift
let parameters = ModelResponseParameter(
input: .text("Summarize this ticket in one sentence."),
model: .gpt6Astra,
serviceTier: ServiceTier.ultrafast.rawValue
)

let response = try await service.responseCreate(parameters)
```

#### TextConfiguration with Verbosity

```swift
Expand Down Expand Up @@ -4306,6 +4324,62 @@ let vectorStoreFiles = try await service.listVectorStoreFilesInABatch(vectorStor

⚠️ We currently support Only Assistants Beta 2. If you need support for Assistants V1, you can access it in the jroch-supported-branch-for-assistants-v1 branch or in the v2.3 release.. [Check OpenAI Documentation for details on migration.](https://platform.openai.com/docs/assistants/migration))

### Agents

The [Agents API](https://developers.openai.com/api/docs/guides/agents-api/quickstart) (public beta) gives access to the managed Codex harness: hosted execution, memory, tools, and multi-agent support, with OpenAI handling sessions, orchestration, context compaction and recovery. All requests are sent with the `OpenAI-Beta: agents=v1` header automatically.

Create a session and stream its events:

```swift
let parameters = AgentSessionParameters(
agent: .init(
model: .gpt6Astra,
instructions: "Write clean code, run it, and report the actual output.",
tools: [.computerUse(includeScreenshots: true)]),
environment: .init(type: .openAIHosted, desktop: .init(enabled: true)),
input: "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.")

var sessionID: String?
let stream = try await service.createAgentSessionStream(parameters)
for try await event in stream {
if sessionID == nil { sessionID = event.sessionId }
switch event.kind {
case .turnOutputTextDone:
print(event.text ?? "")
case .turnCompleted:
print("Task finished")
case .requiresAction:
print("Pending approval: \(event.requestId ?? "")")
case .unknown(let type):
print("Unhandled event: \(type)") // Full payload available in event.raw
default:
break
}
}
```

Send follow-up input to an existing session (reopen the event stream first to capture all events):

```swift
let sessionID = "sess_abc123"
let events = try await service.agentSessionEventStream(sessionID: sessionID)
try await service.submitAgentSessionEvents(
sessionID: sessionID,
parameters: .init(events: [.message("Now add unit tests.")]))
for try await event in events {
// Handle events as above.
}
```

List the session's saved items and delete the session when done:

```swift
let items = try await service.listAgentSessionItems(sessionID: sessionID, limit: 100, order: "asc", after: nil)
let deletion = try await service.deleteAgentSession(sessionID: sessionID)
```

⚠️ The Agents API is in public beta and OpenAI has not published the complete schemas. Response models decode the documented fields and keep the full payload in a `raw` member; unrecognized stream event types decode as `.unknown` instead of failing the stream. Use `.custom` tools and client events for shapes not yet modeled, such as MCP servers and approval responses.

## Anthropic

Anthropic provides OpenAI compatibility, for more, visit the [documentation](https://docs.anthropic.com/en/api/openai-sdk#getting-started-with-the-openai-sdk)
Expand Down
49 changes: 49 additions & 0 deletions Sources/OpenAI/AIProxy/AIProxyService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1427,6 +1427,55 @@ struct AIProxyService: OpenAIService {
fatalError("deleteConversationItem not implemented for AIProxy Service")
}

// MARK: Agents (Beta)

func createAgentSession(
_: AgentSessionParameters)
async throws -> AgentSessionObject
{
fatalError("createAgentSession not implemented for AIProxy Service")
}

func createAgentSessionStream(
_: AgentSessionParameters)
async throws -> AsyncThrowingStream<AgentSessionStreamEvent, Error>
{
fatalError("createAgentSessionStream not implemented for AIProxy Service")
}

func agentSessionEventStream(
sessionID _: String)
async throws -> AsyncThrowingStream<AgentSessionStreamEvent, Error>
{
fatalError("agentSessionEventStream not implemented for AIProxy Service")
}

@discardableResult
func submitAgentSessionEvents(
sessionID _: String,
parameters _: AgentSessionEventsParameter)
async throws -> OpenAIJSONValue
{
fatalError("submitAgentSessionEvents not implemented for AIProxy Service")
}

func listAgentSessionItems(
sessionID _: String,
limit _: Int?,
order _: String?,
after _: String?)
async throws -> OpenAIResponse<AgentSessionItem>
{
fatalError("listAgentSessionItems not implemented for AIProxy Service")
}

func deleteAgentSession(
sessionID _: String)
async throws -> DeletionStatus
{
fatalError("deleteAgentSession not implemented for AIProxy Service")
}

private static let assistantsBetaV2 = "assistants=v2"

/// Your partial key is provided during the integration process at dashboard.aiproxy.pro
Expand Down
49 changes: 49 additions & 0 deletions Sources/OpenAI/Azure/DefaultOpenAIAzureService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,55 @@ public final class DefaultOpenAIAzureService: OpenAIService {
fatalError("deleteConversationItem not implemented for Azure OpenAI Service")
}

// MARK: Agents (Beta)

public func createAgentSession(
_: AgentSessionParameters)
async throws -> AgentSessionObject
{
fatalError("createAgentSession not implemented for Azure OpenAI Service")
}

public func createAgentSessionStream(
_: AgentSessionParameters)
async throws -> AsyncThrowingStream<AgentSessionStreamEvent, Error>
{
fatalError("createAgentSessionStream not implemented for Azure OpenAI Service")
}

public func agentSessionEventStream(
sessionID _: String)
async throws -> AsyncThrowingStream<AgentSessionStreamEvent, Error>
{
fatalError("agentSessionEventStream not implemented for Azure OpenAI Service")
}

@discardableResult
public func submitAgentSessionEvents(
sessionID _: String,
parameters _: AgentSessionEventsParameter)
async throws -> OpenAIJSONValue
{
fatalError("submitAgentSessionEvents not implemented for Azure OpenAI Service")
}

public func listAgentSessionItems(
sessionID _: String,
limit _: Int?,
order _: String?,
after _: String?)
async throws -> OpenAIResponse<AgentSessionItem>
{
fatalError("listAgentSessionItems not implemented for Azure OpenAI Service")
}

public func deleteAgentSession(
sessionID _: String)
async throws -> DeletionStatus
{
fatalError("deleteAgentSession not implemented for Azure OpenAI Service")
}

private static let assistantsBetaV2 = "assistants=v2"

private let apiKey: Authorization
Expand Down
55 changes: 55 additions & 0 deletions Sources/OpenAI/LocalModelService/LocalModelService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,61 @@ struct LocalModelService: OpenAIService {
"Currently, this API is not supported. We welcome and encourage contributions to our open-source project. Please consider opening an issue or submitting a pull request to add support for this feature.")
}

// MARK: Agents (Beta)

func createAgentSession(
_: AgentSessionParameters)
async throws -> AgentSessionObject
{
fatalError(
"Currently, this API is not supported. We welcome and encourage contributions to our open-source project. Please consider opening an issue or submitting a pull request to add support for this feature.")
}

func createAgentSessionStream(
_: AgentSessionParameters)
async throws -> AsyncThrowingStream<AgentSessionStreamEvent, Error>
{
fatalError(
"Currently, this API is not supported. We welcome and encourage contributions to our open-source project. Please consider opening an issue or submitting a pull request to add support for this feature.")
}

func agentSessionEventStream(
sessionID _: String)
async throws -> AsyncThrowingStream<AgentSessionStreamEvent, Error>
{
fatalError(
"Currently, this API is not supported. We welcome and encourage contributions to our open-source project. Please consider opening an issue or submitting a pull request to add support for this feature.")
}

@discardableResult
func submitAgentSessionEvents(
sessionID _: String,
parameters _: AgentSessionEventsParameter)
async throws -> OpenAIJSONValue
{
fatalError(
"Currently, this API is not supported. We welcome and encourage contributions to our open-source project. Please consider opening an issue or submitting a pull request to add support for this feature.")
}

func listAgentSessionItems(
sessionID _: String,
limit _: Int?,
order _: String?,
after _: String?)
async throws -> OpenAIResponse<AgentSessionItem>
{
fatalError(
"Currently, this API is not supported. We welcome and encourage contributions to our open-source project. Please consider opening an issue or submitting a pull request to add support for this feature.")
}

func deleteAgentSession(
sessionID _: String)
async throws -> DeletionStatus
{
fatalError(
"Currently, this API is not supported. We welcome and encourage contributions to our open-source project. Please consider opening an issue or submitting a pull request to add support for this feature.")
}

/// [authentication](https://platform.openai.com/docs/api-reference/authentication)
private let apiKey: Authorization
/// Set this flag to TRUE if you need to print request events in DEBUG builds.
Expand Down
16 changes: 16 additions & 0 deletions Sources/OpenAI/Private/Networking/OpenAIAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Foundation
// MARK: - OpenAIAPI

enum OpenAIAPI {
case agent(AgentCategory) // https://developers.openai.com/api/docs/guides/agents-api/quickstart
case assistant(AssistantCategory) // https://platform.openai.com/docs/api-reference/assistants
case audio(AudioCategory) // https://platform.openai.com/docs/api-reference/audio
case chat /// https://platform.openai.com/docs/api-reference/chat
Expand All @@ -36,6 +37,13 @@ enum OpenAIAPI {
/// Create and manage conversations to store and retrieve conversation state across Response API calls.
case conversantions(ConversationCategory) // https://platform.openai.com/docs/api-reference/conversations

enum AgentCategory {
case createSession
case session(sessionID: String)
case events(sessionID: String)
case items(sessionID: String)
}

enum AssistantCategory {
case create
case list
Expand Down Expand Up @@ -191,6 +199,14 @@ extension OpenAIAPI: Endpoint {
}

switch self {
case .agent(let category):
switch category {
case .createSession: return "\(version)/agents/sessions"
case .session(let sessionID): return "\(version)/agents/sessions/\(sessionID)"
case .events(let sessionID): return "\(version)/agents/sessions/\(sessionID)/events"
case .items(let sessionID): return "\(version)/agents/sessions/\(sessionID)/items"
}

case .assistant(let category):
switch category {
case .create, .list: return "\(version)/assistants"
Expand Down
Loading
Loading