### Clone and build Gemini sample Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Clones the generative-ai-js repository, installs sample dependencies, and builds the Docker image. ```bash git clone https://github.com/google/generative-ai-js npm install --prefix generative-ai-js/samples docker --debug build -t node_docker_sandbox . ``` -------------------------------- ### Make a tool call with OpenRouter using AIProxy Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Shows how to call OpenRouter with tool definitions and fallback routing. Uncomment the appropriate service initialization for BYOK or production use. The example prints the tool call, usage, and handles errors. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let openRouterService = AIProxy.openRouterDirectService( // unprotectedAPIKey: "your-openRouter-key" // ) /* Uncomment for all other production use cases */ // let openRouterService = AIProxy.openRouterService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) do { let completion = try await openRouterService.chatCompletionRequest(body: .init( messages: [ .user( content: .text("What is the weather in SF?") ) ], models: [ "cohere/command-r7b-12-2024", "meta-llama/llama-3.3-70b-instruct", // ... ], route: .fallback, tools: [ .function( name: "get_weather", description: "Get current temperature for a given location.", parameters: [ "type": "object", "properties": [ "location": [ "type": "string", "description": "City and country e.g. Bogotá, Colombia" ] ], "required": ["location"], "additionalProperties": false ], strict: true ) ] )) if let toolCall = completion.choices.first?.message.toolCalls?.first { print(""" The model wants us to call function: \(toolCall.function?.name ?? "") With arguments: \(toolCall.function?.arguments ?? [:]) Served by \(completion.provider ?? "unspecified") using model \(completion.model ?? "unspecified") """ ) } if let usage = completion.usage { print( """ Used: \(usage.promptTokens ?? 0) prompt tokens \(usage.completionTokens ?? 0) completion tokens \(usage.totalTokens ?? 0) total tokens """ ) } } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received non-200 status code: \(statusCode) with response body: \(responseBody)") } catch { print("Could not get first chat completion: \(error)") } ``` -------------------------------- ### Run mitmproxy on port 9090 Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Starts mitmproxy to listen for traffic on port 9090. Run this before starting the Docker container. ```bash mitmproxy --listen-port 9090 ``` -------------------------------- ### Use prompt templates with the OpenAI Responses API Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Requires a prompt ID from OpenAI's guide and fills in prompt variables (e.g., 'topic'). Shows both buffered and streaming response handling, with streaming commented out. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let openAIService = AIProxy.openAIDirectService( // unprotectedAPIKey: "your-openai-key" // ) /* Uncomment for all other production use cases */ // let openAIService = AIProxy.openAIService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) let templateID = "" let requestBody = OpenAICreateResponseRequestBody( model: "gpt-5", prompt: .init( id: templateID, variables: [ "topic": .text("sandwiches") ], version: "1" ) ) do { // Uncomment for the buffered case: let response = try await openAIService.createResponse( requestBody: requestBody, secondsToWait: 60 ) print(response.outputText) // Uncomment for the streaming case: // let stream = try await openAIService.createStreamingResponse( // requestBody: requestBody, // secondsToWait: 60 // ) // for try await event in stream { // switch event { // case .outputTextDelta(let outputTextDelta): // print(outputTextDelta.delta) // default: // break // } // } } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not get a text response from OpenAI: \(error)") } } ``` -------------------------------- ### Generate images with your own Flux fine-tune using ReplicateFluxFineTuneInputSchema Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Use the `` string returned from the previous snippet, omitting the model owner and name. Configure the service for BYOK or production use by uncommenting the appropriate block. The example creates a prediction with 28 inference steps for `.dev` (4 for `.schnell`) and polls for output, printing the result or handling errors. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let replicateService = AIProxy.replicateDirectService( // unprotectedAPIKey: "your-replicate-key" // ) /* Uncomment for all other production use cases */ // let replicateService = AIProxy.replicateService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) let input = ReplicateFluxFineTuneInputSchema( prompt: "an oil painting of my face on a blimp", model: .dev, numInferenceSteps: 28 // Replicate recommends around 28 steps for `.dev` and 4 for `.schnell` ) do { let predictionResponse = try await replicateService.createPrediction( version: "", input: input, output: ReplicatePrediction<[URL]>.self ) let predictionOutput: [URL] = try await replicateService.pollForPredictionOutput( predictionResponse: predictionResponse, pollAttempts: 30, secondsBetweenPollAttempts: 5 ) print("Done creating predictionOutput: \(predictionOutput)") } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not create replicate prediction: \(error)") } ``` -------------------------------- ### List OpenAI conversation items with pagination using openAIService.listItems Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Creates a conversation with four input messages, then lists items in pages of two using the limit, order, and after parameters. The example prints the item count and hasMore flag for each page. Requires an initialized openAIService. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let openAIService = AIProxy.openAIDirectService( // unprotectedAPIKey: "your-openai-key" // ) /* Uncomment for all other production use cases */ // let openAIService = AIProxy.openAIService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) let createConversationBody = OpenAICreateConversationRequestBody( items: [ .item(.inputMessage(OpenAIInputMessage(content: "Page 1 - Item 1", role: .user))), .item(.inputMessage(OpenAIInputMessage(content: "Page 1 - Item 2", role: .user))), .item(.inputMessage(OpenAIInputMessage(content: "Page 2 - Item 1", role: .user))), .item(.inputMessage(OpenAIInputMessage(content: "Page 2 - Item 2", role: .user))) ], metadata: ["purpose": "pagination_test"] ) do { let conversation = try await openAIService.createConversation( requestBody: createConversationBody, secondsToWait: 120 ) print("Created conversation: \(conversation.id)") let page1 = try await openAIService.listItems( conversationID: conversation.id, limit: 2, order: .asc, secondsToWait: 120 ) print("Page 1: \(page1.data.count) items") print("Has more: \(page1.hasMore)") if page1.hasMore { let page2 = try await openAIService.listItems( conversationID: conversation.id, after: page1.lastID, limit: 2, order: .asc, secondsToWait: 120 ) print("Page 2: \(page2.data.count) items") print("Has more: \(page2.hasMore)") } } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not paginate conversation items: \(error)") } ``` -------------------------------- ### Upload training data for Flux fine tune using replicateService.uploadTrainingZipFile Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Uploads a zip file named 'training.zip' from Xcode assets as training data for a Flux fine tune. Requires the zip file to be added to Assets and follows the 'Prepare your training data' guide. Prints the file URL and expiration date, or handles AIProxyError.unsuccessfulRequest and other errors. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let replicateService = AIProxy.replicateDirectService( // unprotectedAPIKey: "your-replicate-key" // ) /* Uncomment for all other production use cases */ // let replicateService = AIProxy.replicateService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) guard let trainingData = NSDataAsset(name: "training") else { print(""" Drop training.zip file into Assets first. See the 'Prepare your training data' of this guide: https://replicate.com/blog/fine-tune-flux """) return } do { let fileUploadResponse = try await replicateService.uploadTrainingZipFile( zipData: trainingData.data, name: "training.zip" ) print(""" Training file uploaded. Find it at \(fileUploadResponse.urls.get) You you can train with this file until \(fileUploadResponse.expiresAt ?? "") """) } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not upload file to replicate: \(error)") } ``` -------------------------------- ### Get a streaming chat completion from OpenAI Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Streams chat completion chunks from OpenAI using the streamingChatCompletionRequest method. Configure the service as in the non-streaming example. Prints each delta content as it arrives. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let openAIService = AIProxy.openAIDirectService( // unprotectedAPIKey: "your-openai-key" // ) /* Uncomment for all other production use cases */ // let openAIService = AIProxy.openAIService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) let requestBody = OpenAIChatCompletionRequestBody( model: "gpt-5.2", messages: [.user(content: .text("hello world"))] reasoningEffort: .noReasoning ) do { let stream = try await openAIService.streamingChatCompletionRequest( body: requestBody, secondsToWait: 60 ) for try await chunk in stream { print(chunk.choices.first?.delta.content ?? "") } } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not create OpenAI streaming chat completion: \(error)") } ``` -------------------------------- ### Set up Docker sandbox for Gemini client Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Creates a directory, copies the mitmproxy CA certificate, pulls Node 22, and opens a Dockerfile for editing. The Dockerfile configures the container to trust the mitmproxy certificate and run the Gemini sample. ```bash mkdir ~/dev/node_docker_sandbox cd ~/dev/node_docker_sandbox cp ~/.mitmproxy/mitmproxy-ca-cert.pem . docker pull node:22 vim Dockerfile ``` -------------------------------- ### Run Docker container with volume mount Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Runs the built container, mounting the current directory to /entrypoint so the sample code is available. Requires manual proxy configuration in Docker Desktop. ```bash docker run --volume "$(pwd)/:/entrypoint/" node_docker_sandbox ``` -------------------------------- ### ElevenLabs TTS request with timestamps Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Calls `ttsRequestWithTimestamps` to get timing information for the spoken text. The response provides `res.alignment` and `res.normalizedAlignment` for timing, and `res.audioData` for audio playback. Requires an existing `elevenLabsService` and `body` from the previous example. ```swift let res = try await elevenLabsService.ttsRequestWithTimestamps( voiceID: "EXAVITQu4vr4xnSDxMaL", body: body, secondsToWait: 120 ) // Timing information is available as `res.alignment` and `res.normalizedAlignment` // Audio to pass to the AVAudioPlayer is available as `res.audioData` ``` -------------------------------- ### TogetherAI tool call request with Llama Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Make a tool call request using TogetherAIFunction. The example is a Swift port of the linked guide. Note that the tool call result is not currently extracted from the response; open a GitHub issue if you need this use case. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let togetherAIService = AIProxy.togetherAIDirectService( // unprotectedAPIKey: "your-togetherAI-key" // ) /* Uncomment for all other production use cases */ // let togetherAIService = AIProxy.togetherAIService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) do { let function = TogetherAIFunction( description: "Call this when the user wants the weather", name: "get_weather", parameters: [ "type": "object", "properties": [ "location": [ "type": "string", "description": "The city and state, e.g. San Francisco, CA", ], "num_days": [ "type": "integer", "description": "The number of days to get the forecast for", ], ], "required": ["location", "num_days"], ] ) let toolPrompt = """ You have access to the following functions: Use the function '\(function.name)' to '\(function.description)': \(try function.serialize()) If you choose to call a function ONLY reply in the following format with no prefix or suffix: {{"example_name": "example_value"}} Reminder: - Function calls MUST follow the specified format, start with - Required parameters MUST be specified - Only call one function at a time - Put the entire function call reply on one line - If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls """ } ``` -------------------------------- ### Initialize OpenAI service for Azure deployment Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Use this initialization to run any of the OpenAI snippets with an Azure deployment. Requires your partial key and service URL, and sets the request format to azureDeployment with a specific API version. ```swift import AIProxy let openAIService = AIProxy.openAIService( partialKey: "partial-key-from-your-developer-dashboard", serviceURL: "service-url-from-your-developer-dashboard", requestFormat: .azureDeployment(apiVersion: "2024-06-01") ) ``` -------------------------------- ### TogetherAI JSON mode chat completion with schema Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Use JSON mode to enforce a structured response from the model. Only some models support JSON mode; see the linked guide for a list. The example defines a schema for a color palette and sends a chat completion request with responseFormat .json(schema:). ```swift import AIProxy /* Uncomment for BYOK use cases */ // let togetherAIService = AIProxy.togetherAIDirectService( // unprotectedAPIKey: "your-togetherAI-key" // ) /* Uncomment for all other production use cases */ // let togetherAIService = AIProxy.togetherAIService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) do { let schema: [String: AIProxyJSONValue] = [ "type": "object", "properties": [ "colors": [ "type": "array", "items": [ "type": "object", "properties": [ "name": [ "type": "string", "description": "A descriptive name to give the color" ], "hex_code": [ "type": "string", "description": "The hex code of the color" ] ], "required": ["name", "hex_code"], "additionalProperties": false ] ] ], "required": ["colors"], "additionalProperties": false ] let requestBody = TogetherAIChatCompletionRequestBody( messages: [ TogetherAIMessage( content: "You are a helpful assistant that answers in JSON", role: .system ), TogetherAIMessage( content: "Create a peaches and cream color palette", role: .user ) ], model: "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo", responseFormat: .json(schema: schema) ) let response = try await togetherAIService.chatCompletionRequest(body: requestBody) print(response.choices.first?.message.content ?? "") } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not create TogetherAI JSON chat completion: \(error)") } ``` -------------------------------- ### Whisper word-level timestamps with OpenAI transcription Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Records an audio file, adds it to the Xcode target, and runs this snippet to get word-level timestamps. Uses OpenAICreateTranscriptionRequestBody with model "whisper-1", responseFormat "verbose_json", and timestampGranularities [.word, .segment]. Prints each word with its start and end time; handles AIProxyError.unsuccessfulRequest and other errors. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let openAIService = AIProxy.openAIDirectService( // unprotectedAPIKey: "your-openai-key" // ) /* Uncomment for all other production use cases */ // let openAIService = AIProxy.openAIService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) guard let url = Bundle.main.url(forResource: "helloworld", withExtension: "m4a"), let fileContents = try? Data(contentsOf: url) else { print("Could not read file contents of helloworld.m4a") return } do { let requestBody = OpenAICreateTranscriptionRequestBody( file: fileContents, model: "whisper-1", responseFormat: "verbose_json", timestampGranularities: [.word, .segment] ) let response = try await openAIService.createTranscriptionRequest(body: requestBody) if let words = response.words { for word in words { print("\(word.word) from \(word.start) to \(word.end)") } } } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not get word-level timestamps from OpenAI: \(error)") } ``` -------------------------------- ### Create Veo 3 Fast video from image on EachAI Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Use this Swift snippet to generate a video from an image via EachAI's Veo 3 Fast model. The image must be hosted at a public URL because the model does not accept data URLs. The example uses a sample image URL and a detailed prompt, then polls up to 60 times with 10-second intervals. It prints the output URL on success or handles non-200 responses and other errors. For BYOK, uncomment the direct service initializer with your EachAI key; for production, use the partial key and service URL from your developer dashboard. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let eachAIService = AIProxy.eachAIDirectService( // unprotectedAPIKey: "your-eachAI-key" // ) /* Uncomment for all other production use cases */ // let eachAIService = AIProxy.eachAIService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) // This model on EachAI does not currently accept a data URL. So you have to host the image somewhere first. let imageURL = URL(string: "https://storage.googleapis.com/magicpoint/inputs/veo3-fast-i2v-input.jpeg")! let input = EachAIVeoInput( imageURL: imageURL, prompt: """ Cinematic video set in a bioluminescent underwater cave system on an alien ocean world, illuminated by glowing turquoise and violet corals. The scene opens with a smooth tracking shot through a tunnel of shimmering water, revealing a vast cavern where a swarm of robotic fish, each engraved with the 'eachlabs.ai' logo, swims in synchronized patterns. The camera follows the swarm as they weave through towering coral structures, their metallic bodies reflecting the cave’s radiant glow. A faint, rhythmic pulse of light emanates from the corals, creating a hypnotic effect. Suddenly, a massive, bioluminescent jellyfish-like creature drifts into view, its tentacles gently pulsating as it emits a low, resonant hum. The audio includes the soft gurgle of water, a futuristic ambient soundtrack with ethereal tones, and the jellyfish’s hum synced with its movements. The video ends with a slow zoom-out, showing the swarm of robotic fish forming the shape of the 'eachlabs.ai' logo against the glowing cave backdrop, followed by a gentle fade to black. The style is photorealistic, with realistic fluid dynamics, vibrant lighting, and an immersive, otherworldly aesthetic. """ ) do { let url = try await eachAIService.createVeo3FastVideo( input: input, pollAttempts: 60, secondsBetweenPollAttempts: 10 ) print("Your veo3 output is available at: \(url)") } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received non-200 status code: \(statusCode) with response body: \(responseBody)") } catch { print("Could not run Veo3 on EachAI: \(error)") } ``` -------------------------------- ### Streaming DeepSeek R1 completion with OpenRouter Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Use this Swift code to make a streaming chat completion request to OpenRouter's DeepSeek R1 model via AIProxy. It includes commented options for BYOK (direct service) and production (partial key) setups. The example prints reasoning and message chunks, token usage, and handles errors like non-200 status, timeout, and network issues. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let openRouterService = AIProxy.openRouterDirectService( // unprotectedAPIKey: "your-openRouter-key" // ) /* Uncomment for all other production use cases */ // let openRouterService = AIProxy.openRouterService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) let requestBody = OpenRouterChatCompletionRequestBody( messages: [ .system(content: .text("You are a math assistant.")), .user(content: .text("Here's why burgers' equation leads to a breaking nonlinearity in shallow water")) ], models: [ "deepseek/deepseek-r1", ], reasoning: .init(effort: .low), temperature: 0.0 /* Set this based on your use case: https://api-docs.deepseek.com/quick_start/parameter_settings*/ ) do { let stream = try await openRouterService.streamingChatCompletionRequest( body: requestBody ) for try await chunk in stream { if let reasoningContent = chunk.choices.first?.delta.reasoning { print("Reasoning chunk: \(reasoningContent)") } if let messageContent = chunk.choices.first?.delta.content { print("Message chunk: \(messageContent)") } if let usage = chunk.usage { print( """ Served by \(chunk.provider ?? "unspecified") using model \(chunk.model ?? "unspecified") Used: \(usage.promptTokens ?? 0) prompt tokens \(usage.completionTokens ?? 0) completion tokens \(usage.totalTokens ?? 0) total tokens """ ) } } } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received non-200 status code: \(statusCode) with response body: \(responseBody)") } catch let err as URLError where err.code == URLError.timedOut { print("Request for OpenRouter buffered chat completion timed out") } catch let err as URLError where [.notConnectedToInternet, .networkConnectionLost].contains(err.code) { print("Could not make OpenRouter streaming R1 chat request. Please check your internet connection") } catch { print("Could not get OpenRouter streaming R1 chat completion: \(error)") } ``` -------------------------------- ### Make a Gemini tool call with AIProxy Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Shows how to configure a Gemini service (BYOK or production), define a function declaration with parameters, send a generateContentRequest, and handle text or functionCall responses. Includes commented options for direct API key or partial key/service URL, and an optional toolConfig to enforce a function call. Prints token usage metadata and handles unsuccessfulRequest errors. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let geminiService = AIProxy.geminiDirectService( // unprotectedAPIKey: "your-gemini-key" // ) /* Uncomment for all other production use cases */ // let geminiService = AIProxy.geminiService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) let functionParameters: [String: AIProxyJSONValue] = [ "type": "OBJECT", "properties": [ "brightness": [ "description": "Light level from 0 to 100. Zero is off and 100 is full brightness.", "type": "NUMBER" ], "colorTemperature": [ "description": "Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.", "type": "STRING" ] ], "required": [ "brightness", "colorTemperature" ] ] let requestBody = GeminiGenerateContentRequestBody( contents: [ .init( parts: [.text("Dim the lights so the room feels cozy and warm.")], role: "user" ) ], /* Uncomment this to enforce that a function is called regardless of prompt contents. */ // toolConfig: .init( // functionCallingConfig: .init( // allowedFunctionNames: ["controlLight"], // mode: .anyFunction // ) // ), tools: [ .functionDeclarations( [ .init( name: "controlLight", description: "Set the brightness and color temperature of a room light.", parameters: functionParameters ) ] ) ] ) do { let response = try await geminiService.generateContentRequest( body: requestBody, model: "gemini-2.5-flash", secondsToWait: 60 ) for part in response.candidates?.first?.content?.parts ?? [] { switch part { case .text(let text): print("Gemini sent: \(text)") case .functionCall(name: let functionName, args: let arguments): print("Gemini wants us to call function \(functionName) with arguments: \(arguments ?? [:])") } } if let usage = response.usageMetadata { print( """ Used: \(usage.promptTokenCount ?? 0) prompt tokens \(usage.cachedContentTokenCount ?? 0) cached tokens \(usage.candidatesTokenCount ?? 0) candidate tokens \(usage.totalTokenCount ?? 0) total tokens """ ) } } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not create Gemini tool (function) call: \(error)") } ``` -------------------------------- ### Create a Flux fine-tune training job with ReplicateFluxTrainingInput Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Creates a Replicate training job for the flux-dev-lora-trainer model using the AIProxy Swift SDK. Configure the service with either a direct BYOK key or the production partialKey/serviceURL pair. The training input uses a trigger word and an optional layersToOptimizeRegex to speed training for faces. Replace with the URL from the previous snippet and / with your destination. Prints the training status URL or an error. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let replicateService = AIProxy.replicateDirectService( // unprotectedAPIKey: "your-replicate-key" // ) /* Uncomment for all other production use cases */ // let replicateService = AIProxy.replicateService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) do { // You should experiment with the settings in `ReplicateFluxTrainingInput.swift` to // find what works best for your use case. // // The `layersToOptimizeRegex` argument here speeds training and works well for faces. // You could could optionally remove that argument to see if the final trained model // works better for your user case. let trainingInput = ReplicateFluxTrainingInput( inputImages: URL(string: "")!, layersToOptimizeRegex: "transformer.single_transformer_blocks.(7|12|16|20).proj_out", steps: 200, triggerWord: "face" ) let reqBody = ReplicateTrainingRequestBody(destination: "/", input: trainingInput) // Find valid version numbers here: https://replicate.com/ostris/flux-dev-lora-trainer/train let training = try await replicateService.createTraining( modelOwner: "ostris", modelName: "flux-dev-lora-trainer", versionID: "d995297071a44dcb72244e6c19462111649ec86a9646c32df56daa7f14801944", body: reqBody ) print("Get training status at: \(training.urls?.get?.absoluteString ?? "unknown")") } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not create replicate training: \(error)") } ``` -------------------------------- ### OpenAI Realtime GA session with web search tool Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Configures an OpenAI Realtime GA session using outputModalities [.audio], the builtin 'alloy' voice, a .webSearch tool with .medium search context size, and .auto toolChoice. The session is created with model 'gpt-realtime' and .info log level. Note that GA uses output_modalities instead of modalities, and .auto lets the model decide when to use the web search tool. ```swift let configuration = OpenAIRealtimeSessionConfiguration( outputModalities: [.audio], voice: .builtin("alloy"), tools: [.webSearch(.init(searchContextSize: .medium))], toolChoice: .auto ) let session = try await openAIService.realtimeSession( model: "gpt-realtime", configuration: configuration, logLevel: .info ) ``` -------------------------------- ### Create a vector store with specific chunking on OpenAI Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Configure the AIProxy OpenAI service, then create a vector store using a static chunking strategy with 300 token overlap and 700 max chunk size. Waits up to 60 seconds. Prints the new vector store's id or an error. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let openAIService = AIProxy.openAIDirectService( // unprotectedAPIKey: "your-openai-key" // ) /* Uncomment for all other production use cases */ // let openAIService = AIProxy.openAIService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) let requestBody = OpenAICreateVectorStoreRequestBody( chunkingStrategy: .static(chunkOverlapTokens: 300, maxChunkSizeTokens: 700), name: "my-vector-store" ) do { let vectorStore = try await openAIService.createVectorStore( requestBody: requestBody, secondsToWait: 60 ) print("Created vector store with id: \(vectorStore.id)") } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not create an OpenAI vector store: \(error)") } ``` -------------------------------- ### ElevenLabs streaming TTS with timestamps Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Streams text-to-speech audio with timing information using `streamingTTSWithTimestampsRequest`. Each chunk provides `chunk.alignment` and `chunk.normalizedAlignment` for timing, and `chunk.audioData` for audio playback. Requires an existing `elevenLabsService` and `body` from the previous example. ```swift let stream = try await elevenLabsService.streamingTTSWithTimestampsRequest( voiceID: "EXAVITQu4vr4xnSDxMaL", body: body, secondsToWait: 120 ) for try await chunk in stream { // Timing information is available as `chunk.alignment` and `chunk.normalizedAlignment` // Audio to pass to the AVAudioPlayer is available as `chunk.audioData` } ``` -------------------------------- ### ElevenLabs Speech-to-Speech with AIProxy Swift Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Use AIProxy's ElevenLabs service to convert speech to speech. Requires an audio file named helloworld.m4a added to the Xcode target. Uncomment the appropriate service initialization for BYOK or production use. The snippet plays the returned MPEG data with AVAudioPlayer, noting that the player must have a long-lived lifecycle. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let elevenLabsService = AIProxy.elevenLabsDirectService( // unprotectedAPIKey: "your-elevenLabs-key" // ) /* Uncomment for all other production use cases */ // let elevenLabsService = AIProxy.elevenLabsService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) guard let localAudioURL = Bundle.main.url(forResource: "helloworld", withExtension: "m4a") else { print("Could not find an audio file named helloworld.m4a in your app bundle") return } do { let body = ElevenLabsSpeechToSpeechRequestBody( audio: try Data(contentsOf: localAudioURL), modelID: "eleven_english_sts_v2", removeBackgroundNoise: true ) let mpegData = try await elevenLabsService.speechToSpeechRequest( voiceID: "EXAVITQu4vr4xnSDxMaL", body: body ) // Do not use a local `let` or `var` for AVAudioPlayer. // You need the lifecycle of the player to live beyond the scope of this function. // Instead, use file scope or set the player as a member of a reference type with long life. // For example, at the top of this file you may define: // // fileprivate var audioPlayer: AVAudioPlayer? = nil // // And then use the code below to play the TTS result: audioPlayer = try AVAudioPlayer(data: mpegData) audioPlayer?.prepareToPlay() audioPlayer?.play() } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received non-200 status code: \(statusCode) with response body: \(responseBody)") } catch { print("Could not create ElevenLabs STS audio: \(error)") } ``` -------------------------------- ### Get an OpenAI conversation with AIProxy Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Retrieves an existing conversation by its ID using getConversation. Requires a valid conversationID and an AIProxy service. Prints the conversation ID and metadata, or handles AIProxyError.unsuccessfulRequest with status code and response body. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let openAIService = AIProxy.openAIDirectService( // unprotectedAPIKey: "your-openai-key" // ) /* Uncomment for all other production use cases */ // let openAIService = AIProxy.openAIService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) do { let response = try await openAIService.getConversation( conversationID: "", secondsToWait: 120 ) print("Retreived conversation with ID \(response.id) and metadata: \(response.metadata)") } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not get OpenAI Conversation: \(error)") } ``` -------------------------------- ### Extracting nested struct into its own file with longer prefix Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md When a provider's nested structure could be reused and the objects are likely to change together, pull the nested struct into its own file and give it a longer prefix. The example shows ProviderResponseBody.swift and ProviderStatus.swift. ```swift // ProviderResponseBody.swift public struct ProviderResponseBody: Decodable, Sendable { // An examples status public let status: ProviderStatus? // ... other fields ... } // ProviderStatus.swift public enum ProviderStatus: String, Decodable, Sendable { case succeeded case failed case canceled } ``` -------------------------------- ### Create a vector store with default chunking on OpenAI Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Configure the AIProxy OpenAI service, then create a vector store using the automatic chunking strategy. Waits up to 60 seconds for the operation. Prints the new vector store's id or an error. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let openAIService = AIProxy.openAIDirectService( // unprotectedAPIKey: "your-openai-key" // ) /* Uncomment for all other production use cases */ // let openAIService = AIProxy.openAIService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) let requestBody = OpenAICreateVectorStoreRequestBody( chunkingStrategy: .auto, name: "my-vector-store" ) do { let vectorStore = try await openAIService.createVectorStore( requestBody: requestBody, secondsToWait: 60 ) print("Created vector store with id: \(vectorStore.id)") } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not create an OpenAI vector store: \(error)") } ``` -------------------------------- ### OpenAI text-to-speech with AVAudioPlayer Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Creates TTS audio using OpenAITextToSpeechRequestBody with input "Hello world" and voice .nova, then plays the resulting MPEG data with AVAudioPlayer. Requires a file-scope or long-lived audioPlayer variable because the player's lifecycle must outlive the function scope. Handles AIProxyError.unsuccessfulRequest and other errors. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let openAIService = AIProxy.openAIDirectService( // unprotectedAPIKey: "your-openai-key" // ) /* Uncomment for all other production use cases */ // let openAIService = AIProxy.openAIService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) do { let requestBody = OpenAITextToSpeechRequestBody( input: "Hello world", voice: .nova ) let mpegData = try await openAIService.createTextToSpeechRequest(body: requestBody) // Do not use a local `let` or `var` for AVAudioPlayer. // You need the lifecycle of the player to live beyond the scope of this function. // Instead, use file scope or set the player as a member of a reference type with long life. // For example, at the top of this file you may define: // // fileprivate var audioPlayer: AVAudioPlayer? = nil // // And then use the code below to play the TTS result: audioPlayer = try AVAudioPlayer(data: mpegData) audioPlayer?.prepareToPlay() audioPlayer?.play() } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received \(statusCode) status code with response body: \(responseBody)") } catch { print("Could not create OpenAI TTS audio: \(error)") } ``` -------------------------------- ### Create a chat completion with Perplexity Source: https://github.com/aiproxyteam/aiproxyswift/blob/main/README.md Use AIProxy.perplexityService or AIProxy.perplexityDirectService to send a chat completion request. The example uses the llama-3.1-sonar-small-128k-online model and prints the response content, citations, and token usage. Errors are caught with AIProxyError.unsuccessfulRequest for non-200 status codes. ```swift import AIProxy /* Uncomment for BYOK use cases */ // let perplexityService = AIProxy.perplexityDirectService( // unprotectedAPIKey: "your-perplexity-key" // ) /* Uncomment for all other production use cases */ // let perplexityService = AIProxy.perplexityService( // partialKey: "partial-key-from-your-developer-dashboard", // serviceURL: "service-url-from-your-developer-dashboard" // ) do { let response = try await perplexityService.chatCompletionRequest(body: .init( messages: [.user(content: "How many national parks in the US?")], model: "llama-3.1-sonar-small-128k-online" )) print( """ Received from Perplexity: \(response.choices.first?.message?.content ?? "no content") With citations: \(response.citations ?? ["none"]) Using: \(response.usage?.promptTokens ?? 0) prompt tokens \(response.usage?.completionTokens ?? 0) completion tokens \(response.usage?.totalTokens ?? 0) total tokens """ ) } catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) { print("Received non-200 status code: \(statusCode) with response body: \(responseBody)") } catch { print("Could not create perplexity chat completion: \(error)") } ```