### Build and Install Android App with Gradle Source: https://github.com/codeandtheory/ychat/blob/main/CONTRIBUTING.md This command builds and installs the Android application using Gradle. It requires an Android emulator or a real Android device to be connected. This is part of the build process for the YChat SDK. ```shell # To build and run the android app (emulator or real android device is needed) $ ./gradlew :app-android:installDebug ``` -------------------------------- ### Initialize YChat SDK Source: https://context7.com/codeandtheory/ychat/llms.txt Demonstrates how to create an instance of the YChat SDK using an OpenAI API key. Includes examples for both Kotlin and Swift, along with basic error handling using try-catch blocks or async/await patterns. ```kotlin val yChat = YChat.create("your-openai-api-key") // For error handling, wrap API calls in try-catch try { val result = yChat.completion() .setInput("Hello, world!") .execute() println(result) } catch (e: YChatException) { println("Error: ${e.message}, Status Code: ${e.statusCode}") } ``` ```swift let yChat = YChatCompanion.shared.create(apiKey: "your-openai-api-key") // Async/await pattern do { let result = try await yChat.completion() .setInput(input: "Hello, world!") .execute() print(result) } catch { print("Error: (error.localizedDescription)") } ``` -------------------------------- ### Platform Configuration for YChat Source: https://context7.com/codeandtheory/ychat/llms.txt Provides dependency setup instructions for integrating YChat across different platforms. Includes Gradle configurations for Android and JVM projects, Swift Package Manager for iOS, and Gradle properties for API key management. Ensure you use the correct dependency versions. ```gradle // Android - build.gradle.kts dependencies { implementation("co.yml:ychat:1.4.1") // YChat uses these under the hood (auto-included) // implementation("io.ktor:ktor-client-okhttp:2.x.x") // implementation("io.insert-koin:koin-android:3.x.x") } ``` ```gradle // JVM - build.gradle.kts dependencies { implementation("co.yml:ychat:1.4.1") } ``` ```swift // iOS - Package.swift dependencies: [ .package(url: "https://github.com/yml-org/ychat.git", from: "1.4.1") ] // Or add via Xcode: // 1. File > Add Packages // 2. Enter: https://github.com/yml-org/ychat.git // 3. Select version 1.4.1 or later ``` ```bash # Gradle - settings.gradle.kts repositories { mavenCentral() } # For JVM backend server (Spring Boot example) # gradle.properties # ychat.api.key=your-api-key-here ``` -------------------------------- ### List Available AI Models Source: https://context7.com/codeandtheory/ychat/llms.txt Shows how to retrieve a list of all available AI models supported by the OpenAI API. The response includes model metadata such as ID, owner, and creation date. Examples are provided for both Kotlin (synchronous and callback styles) and Swift using async/await. ```kotlin val yChat = YChat.create("your-api-key") try { val models: List = yChat.listModels().execute() models.forEach { model -> println("Model ID: ${model.id}") println("Owner: ${model.ownedBy}") println("Created: ${model.created}") } } catch (e: YChatException) { println("Failed to list models: ${e.message}") } // Kotlin - Callback style yChat.listModels().execute(object : YChat.Callback> { override fun onSuccess(result: List) { result.forEach { model -> println("Available model: ${model.id}") } } override fun onError(throwable: Throwable) { println("Error: ${throwable.message}") } }) ``` ```swift let yChat = YChatCompanion.shared.create(apiKey: "your-api-key") do { let models = try await yChat.listModels().execute() for model in models { print("Model ID: (model.id)") print("Owner: (model.ownedBy)") } } catch { print("Failed to list models: (error)") } ``` -------------------------------- ### Kotlin: Setup YChat Dependency Injection with Koin Source: https://context7.com/codeandtheory/ychat/llms.txt Configures YChat with Koin for advanced dependency injection scenarios. This involves creating a custom Application class, defining Koin modules, and injecting YChat into ViewModels or Repositories. Requires Koin and YChat libraries. ```kotlin import co.yml.ychat.di.module.LibraryModule import org.koin.core.context.startKoin import org.koin.dsl.module import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import co.yml.ychat.YChat import co.yml.ychat.core.exceptions.YChatException class MyApplication : Application() { override fun onCreate() { super.onCreate() // Initialize Koin with YChat modules startKoin { modules( LibraryModule.getModule("your-api-key"), appModule ) } } } val appModule = module { // Your app-specific dependencies single { MyRepository(get()) } // YChat features available via DI } // Usage in ViewModel or Repository class ChatViewModel(private val yChat: YChat) : ViewModel() { fun sendMessage(message: String) { viewModelScope.launch { try { val response = yChat.chatCompletions() .setModel("gpt-3.5-turbo") .execute(message) // Handle response } catch (e: YChatException) { // Handle error } } } } ``` -------------------------------- ### Retrieve Specific AI Model Details Source: https://context7.com/codeandtheory/ychat/llms.txt Provides code examples for fetching detailed information about a specific AI model using its unique ID. This includes the model's ID, owner, and permissions. Supported in both Kotlin and Swift, utilizing their respective error handling mechanisms. ```kotlin val yChat = YChat.create("your-api-key") try { val model: AIModel = yChat.retrieveModel().execute("gpt-3.5-turbo") println("Model: ${model.id}") println("Owner: ${model.ownedBy}") println("Permissions: ${model.permission}") } catch (e: YChatException) { println("Model not found: ${e.message}") } ``` ```swift let yChat = YChatCompanion.shared.create(apiKey: "your-api-key") do { let model = try await yChat.retrieveModel().execute(id: "gpt-3.5-turbo") print("Model: (model.id)") print("Owner: (model.ownedBy)") } catch { print("Model not found: (error)") } ``` -------------------------------- ### Transcribe Audio with YChat API (Swift & Kotlin) Source: https://github.com/codeandtheory/ychat/blob/main/guides/Features.md Provides code examples for transcribing audio files using the YChat API. The snippets demonstrate how to load audio data, initialize the YChat client, and call the audio transcriptions endpoint with parameters like model, prompt, response format, temperature, and language. Includes error handling. ```swift var yChat: YChat { YChatCompanion.shared.create(apiKey: "your-api-key") } guard let audioFileUrl = Bundle.main.url(forResource: "audio", withExtension: "m4a") else { print("Unable to find the audio file.") return } let audioData = try! Data(contentsOf: audioFileUrl) do { let result = try await yChat.audioTranscriptions() .setModel(model: "whisper-1") .setPrompt(prompt: "") .setResponseFormat(format: "json") .setTemperature(temperature: 0.4) .setLanguage(language: "en") .execute(filename: "audio.m4a", audioFile: audioData) } catch { // catch any error that may occurs on api call. } ``` ```kotlin val yChat by lazy { YChat.create("your-api-key") } val inputStream = application.resources.openRawResource(R.raw.audio) val byteArray = inputStream.readBytes() try { val result = yChat.audioTranscriptions() .setModel("whisper-1") .setPrompt("") .setResponseFormat("json") .setTemperature(0.4) .setLanguage("en") .execute("audio.m4a", byteArray) } catch (e: exception) { // catch any error that may occurs on api call. } ``` -------------------------------- ### Initialize and Use YChat Completion API in Kotlin (Android/JVM) Source: https://github.com/codeandtheory/ychat/blob/main/README.md This Kotlin code snippet shows how to initialize the YChat library with an API key and perform a completion request. It covers setting the input text, saving history preference, and maximum tokens. The example also includes a try-catch block for handling potential exceptions during the API execution. ```kotlin val yChat by lazy { YChat.create("your-api-key") } try { val result = yChat.completion() .setInput("Say this is a test.") .saveHistory(false) .setMaxTokens(1024) .set... // you can set more parameters .execute() } catch (e: exception) { // catch any error that may occurs on api call. } ``` -------------------------------- ### Kotlin: YChat Error Handling Patterns Source: https://context7.com/codeandtheory/ychat/llms.txt Demonstrates comprehensive error handling for YChat operations using status codes and custom exceptions. Includes examples for handling specific HTTP errors (401, 429, 500, 503) and general exceptions, as well as using the ApiResult wrapper for cleaner success/error state management. Requires YChat core library. ```kotlin import co.yml.ychat.core.exceptions.YChatException import co.yml.ychat.core.network.infrastructure.ApiResult import co.yml.ychat.YChat import kotlin.coroutines.cancellation.CancellationException val yChat = YChat.create("your-api-key") try { val result = yChat.completion() .setInput("Generate a story") .setMaxTokens(2000) .execute() println(result) } catch (e: YChatException) { when (e.statusCode) { 401 -> println("Invalid API key: ${e.message}") 429 -> println("Rate limit exceeded: ${e.message}") 500 -> println("OpenAI server error: ${e.message}") 503 -> println("Service unavailable: ${e.message}") else -> println("Error ${e.statusCode}: ${e.message}") } } catch (e: CancellationException) { println("Request was cancelled") } catch (e: Exception) { println("Unexpected error: ${e.message}") } // Kotlin - ApiResult wrapper for custom handling fun handleApiResult(result: ApiResult) { when { result.exception != null -> { println("Error: ${result.exception?.message}") println("Status: ${result.statusCode}") } result.body != null -> { println("Success: ${result.body}") } else -> { println("Unknown result state") } } } ``` -------------------------------- ### GET /models Source: https://github.com/codeandtheory/ychat/blob/main/guides/Features.md Lists the currently available models with basic information such as owner and availability. ```APIDOC ## GET /models ### Description Lists the currently available models and provides basic information about each one. ### Method GET ### Endpoint /models ### Parameters None ### Request Example None ### Response #### Success Response (200) - **id** (string) - The model's ID. - **owner** (string) - The owner of the model. - **availability** (boolean) - Whether the model is available. #### Response Example { "id": "text-davinci-003", "owner": "OpenAI", "availability": true } ``` -------------------------------- ### Edit Prompts with YChat API (Swift & Kotlin) Source: https://github.com/codeandtheory/ychat/blob/main/guides/Features.md Shows how to use the YChat API's edits functionality to modify prompts based on given instructions. The examples initialize the YChat client and then call the edits endpoint, specifying the input prompt, desired model, temperature, top_p, and the editing instruction. Error handling is provided. ```swift var yChat: YChat { YChatCompanion.shared.create(apiKey: "your-api-key") } do { let result = try await yChat.edits() .setInput(input: "What day of the wek is it?") .setResults(result: 1) .setModel(model: "text-davinci-edit-001") .setTemperature(temperature: 1.0) .setTopP(topP: 1.0) .execute(instruction: "Fix the spelling mistakes") } catch { // catch any error that may occurs on api call. } ``` ```kotlin val yChat by lazy { YChat.create("your-api-key") } try { val result = yChat.edits() .setInput("What day of the wek is it?") .setResults(1) .setModel("text-davinci-edit-001") .setTemperature(1.0) .setTopP(1.0) .execute("Fix the spelling mistakes") } catch (e: exception) { // catch any error that may occurs on api call. } ``` -------------------------------- ### GET /models/{id} Source: https://github.com/codeandtheory/ychat/blob/main/guides/Features.md Retrieves a specific model based on the given ID and provides basic information. ```APIDOC ## GET /models/{id} ### Description Retrieves a specific model based on the given ID and provides basic information about it. ### Method GET ### Endpoint /models/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the model to retrieve. ### Request Example None ### Response #### Success Response (200) - **id** (string) - The model's ID. - **owner** (string) - The owner of the model. - **availability** (boolean) - Whether the model is available. #### Response Example { "id": "babbage", "owner": "OpenAI", "availability": true } ``` -------------------------------- ### List Available AI Models using YChat JVM SDK Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This API endpoint retrieves a list of all currently available artificial intelligence models. It helps in understanding the model landscape. No specific input parameters are required. ```Java GET http://localhost:[port_number]/api/ychat/models ``` -------------------------------- ### Completion API Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This endpoint generates text based on a provided prompt. ```APIDOC ## GET /api/ychat/completion ### Description Generates text based on the provided prompt. ### Method GET ### Endpoint http://localhost:[port_number]/api/ychat/completion ### Parameters #### Query Parameters - **input** (string) - Required - The prompt for generating text. ### Request Example `GET http://localhost:8080/api/ychat/completion?input="What is 1 + 1?"` ### Response #### Success Response (200) - **text** (string) - The generated text based on the prompt. #### Response Example { "text": "1 + 1 = 2" } ``` -------------------------------- ### List Models API Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This endpoint retrieves a list of currently available AI models. ```APIDOC ## GET /api/ychat/models ### Description Retrieves a list of currently available artificial intelligence models. ### Method GET ### Endpoint http://localhost:[port_number]/api/ychat/models ### Response #### Success Response (200) - **models** (array) - An array of available model objects. - **id** (string) - The ID of the model. - **name** (string) - The name of the model. #### Response Example { "models": [ {"id": "ada", "name": "ada"}, {"id": "babbage", "name": "babbage"} ] } ``` -------------------------------- ### Initialize and Use YChat Completion API in Swift (iOS) Source: https://github.com/codeandtheory/ychat/blob/main/README.md This Swift code snippet demonstrates how to initialize the YChat library with an API key and make a completion request. It includes setting input text, maximum tokens, and optionally saving history. Error handling for API calls is also shown. ```swift var yChat: YChat { YChatCompanion.shared.create(apiKey: "your-api-key") } do { let result = try await chatGpt.completion() .setInput(input: "Say this is a test.") .setMaxTokens(tokens: 1024) .saveHistory(isSaveHistory: false) .set... // you can set more parameters .execute() } catch { // catch any error that may occurs on api call. } ``` -------------------------------- ### Generate Images from Text Prompts (Kotlin) Source: https://context7.com/codeandtheory/ychat/llms.txt Generates images based on a text description using the YChat API. Supports specifying the number of images, size, and output format (URL or base64 JSON). Handles potential API exceptions. ```kotlin val yChat = YChat.create("your-api-key") try { val imageUrls: List = yChat.imageGenerations() .setResults(3) // Generate 3 images .setSize("1024x1024") // Options: "256x256", "512x512", "1024x1024" .setResponseFormat("url") // Options: "url" or "b64_json" .execute("A serene ocean sunset with sailboats") imageUrls.forEachIndexed { index, url -> println("Image ${index + 1}: $url") // Download or display the image from URL } } catch (e: YChatException) { println("Image generation failed: ${e.message}") } ``` ```kotlin val base64Images = yChat.imageGenerations() .setResults(1) .setSize("512x512") .setResponseFormat("b64_json") .execute("A cyberpunk city at night") base64Images.forEach { base64Data -> // Decode and save the base64 image data println("Base64 image data length: ${base64Data.length}") } ``` -------------------------------- ### Chat Completions API Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This endpoint generates text based on a prompt and a specified topic. ```APIDOC ## GET /api/ychat/chat-completions ### Description Generates text based on the provided prompt and a specified topic. The generated text will be related to the topic provided. ### Method GET ### Endpoint http://localhost:[port_number]/api/ychat/chat-completions ### Parameters #### Query Parameters - **input** (string) - Required - The prompt for generating text. - **topic** (string) - Required - The topic to limit the response to. ### Request Example `GET http://localhost:8080/api/ychat/chat-completions?input="Tell me an exercise plan"&topic=fitness` ### Response #### Success Response (200) - **message** (string) - The generated chat completion related to the topic. #### Response Example { "message": "A balanced fitness plan includes cardio, strength training, and flexibility exercises." } ``` -------------------------------- ### Perform Chat Completions with Topic using YChat JVM SDK Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This API endpoint generates text related to a specified topic, based on a given prompt. It allows for more focused conversational AI. Inputs include the prompt string and the topic string. ```Java GET http://localhost:[port_number]/api/ychat/chat-completions?input="Tell me an exercise plan"&topic=fitness ``` -------------------------------- ### List Models with YChat API Source: https://github.com/codeandtheory/ychat/blob/main/guides/Features.md Lists available models and their basic information. Supports Swift and Kotlin. Requires an API key for initialization. ```swift var yChat: YChat { YChatCompanion.shared.create(apiKey: "your-api-key") } do { let result = try await yChat.listModels().execute() } catch { // catch any error that may occurs on api call. } ``` ```kotlin val yChat by lazy { YChat.create("your-api-key") } try { val result = yChat.listModels().execute() } catch (e: exception) { // catch any error that may occurs on api call. } ``` -------------------------------- ### Transcribe Audio using YChat JVM SDK Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This API endpoint transcribes audio data into text in the input language. It requires a POST request with multipart/form-data containing the audio file. The output is the transcribed text. ```cURL curl -X POST \ -H "Content-Type: multipart/form-data" \ -F "file=@/path/to/audio/file" \ "http://localhost:8080/api/ychat/audio/transcriptions" ``` -------------------------------- ### Generate Images using YChat JVM SDK Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This API endpoint generates images based on a text prompt. It leverages generative AI for visual content creation. The input is a string representing the image description. ```Java GET http://localhost:[port_number]/api/ychat/generations?prompt="ocean" ``` -------------------------------- ### Image Generations API Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This endpoint generates images based on a provided prompt. ```APIDOC ## GET /api/ychat/generations ### Description Generates images based on the provided prompt. ### Method GET ### Endpoint http://localhost:[port_number]/api/ychat/generations ### Parameters #### Query Parameters - **prompt** (string) - Required - The prompt for generating images. ### Request Example `GET http://localhost:8080/api/ychat/generations?prompt="ocean"` ### Response #### Success Response (200) - **url** (string) - The URL of the generated image. #### Response Example { "url": "http://example.com/image.png" } ``` -------------------------------- ### Generate Images with YChat API (Swift & Kotlin) Source: https://github.com/codeandtheory/ychat/blob/main/guides/Features.md Demonstrates how to generate images using the YChat API. This involves initializing the YChat client with an API key and then calling the image generation endpoint with specified parameters such as result count, size, and response format. Error handling for API calls is included. ```swift var yChat: YChat { YChatCompanion.shared.create(apiKey: "your-api-key") } do { let result = try await yChat.imageGenerations() .setResults(results: 1) .setSize(size: "1024x1024") .setResponseFormat(responseFormat: "url") .execute(prompt: "ocean") } catch { // catch any error that may occurs on api call. } ``` ```kotlin val yChat by lazy { YChat.create("your-api-key") } try { val result = yChat.imageGenerations() .setResults(1) .setSize("1024x1024") .setResponseFormat("url") .execute("ocean") } catch (e: exception) { // catch any error that may occurs on api call. } ``` -------------------------------- ### Audio Transcriptions API Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This endpoint transcribes audio into the input language. ```APIDOC ## POST /api/ychat/audio/transcriptions ### Description Transcribes audio into the input language. ### Method POST ### Endpoint http://localhost:[port_number]/api/ychat/audio/transcriptions ### Parameters #### Request Body - **file** (file) - Required - The audio file to transcribe. ### Request Example ```curl curl -X POST \ -H "Content-Type: multipart/form-data" \ -F "file=@/path/to/audio/file" \ "http://localhost:8080/api/ychat/audio/transcriptions" ``` ### Response #### Success Response (200) - **text** (string) - The transcribed text from the audio. #### Response Example { "text": "This is a transcription of the audio file." } ``` -------------------------------- ### Perform Text Completion using YChat JVM SDK Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This API endpoint generates text based on a given prompt. It's a core functionality for natural language generation tasks. The input is a string representing the prompt. ```Java GET http://localhost:[port_number]/api/ychat/completion?input="What is 1 + 1?" ``` -------------------------------- ### Perform Chat Completions with YChat in Kotlin Source: https://context7.com/codeandtheory/ychat/llms.txt Enables interactive chat conversations using the YChat API in Kotlin. Supports system prompts, role-based messages, and multi-turn context. Allows configuration of model, token limits, temperature, and response quantity. Includes callback style for Android UI updates. ```kotlin // Kotlin - Basic chat completion val yChat = YChat.create("your-api-key") try { val messages: List = yChat.chatCompletions() .setModel("gpt-3.5-turbo") .setMaxTokens(1024) .setMaxResults(1) .setTemperature(0.8) .setTopP(1.0) .execute("Hello! How can you help me today?") messages.forEach { message -> println("${message.role}: ${message.content}") } } catch (e: YChatException) { println("Chat error: ${e.message}") } // Kotlin - With system context and assistant role val fitness = yChat.chatCompletions() .setModel("gpt-3.5-turbo") .setMaxTokens(2048) .setMaxResults(3) // Get 3 different response options .setTemperature(0.7) .addMessage( role = "system", content = "You are a certified fitness trainer with 10 years of experience" ) .addMessage( role = "assistant", content = "I only answer questions related to fitness and nutrition" ) .execute("What's the best exercise for building muscle?") fitness.forEach { message -> println("Response ${fitness.indexOf(message) + 1}:") println("${message.role}: ${message.content}\n") } // Kotlin - Callback style for Android UI updates yChat.chatCompletions() .setModel("gpt-3.5-turbo") .setMaxTokens(512) .addMessage(role = "system", content = "You are a helpful coding assistant") .execute("Explain Kotlin coroutines", object : YChat.Callback> { override fun onSuccess(result: List) { result.forEach { message -> // Update UI on main thread println(message.content) } } override fun onError(throwable: Throwable) { println("Error: ${throwable.message}") } }) ``` -------------------------------- ### Generate Text Completions with YChat in Kotlin Source: https://context7.com/codeandtheory/ychat/llms.txt Generates text completions using the YChat API in Kotlin. Supports configuring model, input, token limits, temperature, topP, and conversation history. Includes error handling for YChat exceptions. ```kotlin // Kotlin - Basic completion val yChat = YChat.create("your-api-key") try { val result: String = yChat.completion() .setModel("text-davinci-003") .setInput("As Descartes said, I think, therefore") .setMaxTokens(1024) .setTemperature(0.7) .setTopP(1.0) .saveHistory(false) .execute() println("Completion: $result") } catch (e: YChatException) { println("Error: ${e.message}, Status: ${e.statusCode}") } // Kotlin - With conversation history enabled val conversationalChat = yChat.completion() .setModel("text-davinci-003") .setInput("What is the capital of France?") .setMaxTokens(512) .setTemperature(0.5) .saveHistory(true) // Enables chat history storage .execute() println("First response: $conversationalChat") // Follow-up question uses previous context val followUp = yChat.completion() .setInput("What is its population?") .setMaxTokens(512) .saveHistory(true) .execute() println("Follow-up response: $followUp") ``` -------------------------------- ### Perform Chat Completions with YChat in Swift Source: https://context7.com/codeandtheory/ychat/llms.txt Enables interactive chat conversations using the YChat API in Swift. Supports system prompts and role-based messages. Allows configuration of model, token limits, and response quantity. Includes error handling for execution failures. ```swift // Swift - Chat with system context let yChat = YChatCompanion.shared.create(apiKey: "your-api-key") do { let messages = try await yChat.chatCompletions() .setModel(model: "gpt-3.5-turbo") .setMaxTokens(tokens: 1024) .setMaxResults(results: 1) .setTemperature(temperature: 0.7) .addMessage( role: "system", content: "You are a helpful assistant specialized in Swift programming" ) .addMessage( role: "assistant", content: "I provide concise, practical Swift code examples" ) .execute(content: "How do I handle optionals in Swift?") for message in messages { print("\(message.role): \(message.content)") } } catch { print("Chat failed: (error)") } ``` -------------------------------- ### Audio Translations API Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This endpoint translates audio into English. ```APIDOC ## POST /api/ychat/audio/translations ### Description Translates audio into English. ### Method POST ### Endpoint http://localhost:[port_number]/api/ychat/audio/translations ### Parameters #### Request Body - **file** (file) - Required - The audio file to translate. ### Request Example ```curl curl -X POST \ -H "Content-Type: multipart/form-data" \ -F "file=@/path/to/audio/file" \ "http://localhost:8080/api/ychat/audio/translations" ``` ### Response #### Success Response (200) - **translation** (string) - The translated text from the audio into English. #### Response Example { "translation": "This is the English translation of the audio file." } ``` -------------------------------- ### Translate Audio to English with YChat API (Swift & Kotlin) Source: https://github.com/codeandtheory/ychat/blob/main/guides/Features.md Illustrates how to translate audio files into English using the YChat API. The code initializes the YChat client and invokes the audio translations endpoint, configuring parameters such as the model, prompt, response format, and temperature. Error handling is included for API requests. ```swift var yChat: YChat { YChatCompanion.shared.create(apiKey: "your-api-key") } guard let audioFileUrl = Bundle.main.url(forResource: "audio", withExtension: "m4a") else { print("Unable to find the audio file.") return } let audioData = try! Data(contentsOf: audioFileUrl) do { let result = try await yChat.audioTranslations() .setModel(model: "whisper-1") .setPrompt(prompt: "") .setResponseFormat(format: "json") .setTemperature(temperature: 0.4) .execute(filename: "audio.m4a", audioFile: audioData) } catch { // catch any error that may occurs on api call. } ``` ```kotlin val yChat by lazy { YChat.create("your-api-key") } val inputStream = application.resources.openRawResource(R.raw.audio) val byteArray = inputStream.readBytes() try { val result = yChat.audioTranslations() .setModel("whisper-1") .setPrompt("") .setResponseFormat("json") .setTemperature(0.4) .execute("audio.m4a", byteArray) } catch (e: exception) { // catch any error that may occurs on api call. } ``` -------------------------------- ### Add YChat Dependency to Gradle (Android/JVM) Source: https://github.com/codeandtheory/ychat/blob/main/README.md Instructions for adding the YChat library dependency to an Android or JVM project using Gradle. It first ensures that Maven Central is configured in the repositories and then provides the specific implementation line for the build.gradle file. ```gradle repositories { mavenCentral() // ... } implementation("co.yml:ychat:1.4.1") ``` -------------------------------- ### Generate Text Completions with YChat in Swift Source: https://context7.com/codeandtheory/ychat/llms.txt Generates text completions using the YChat API in Swift. Allows configuration of model, input, token limits, temperature, topP, and conversation history. Includes error handling for execution failures. ```swift // Swift - Text completion let yChat = YChatCompanion.shared.create(apiKey: "your-api-key") do { let result = try await yChat.completion() .setModel(input: "text-davinci-003") .setInput(input: "Write a haiku about programming") .setMaxTokens(tokens: 100) .setTemperature(temperature: 0.9) .setTopP(topP: 1.0) .saveHistory(isSaveHistory: false) .execute() print("Generated text: (result)") } catch { print("Completion failed: (error)") } ``` -------------------------------- ### Translate Audio to English Source: https://context7.com/codeandtheory/ychat/llms.txt Translates audio content from any supported language into English text. Supports various response formats including text and verbose JSON, which includes metadata. Optional prompt and temperature parameters can be provided. Requires an API key for initialization. Handles audio data as bytes. ```kotlin // Kotlin - Translate audio to English val yChat = YChat.create("your-api-key") // Load foreign language audio file val inputStream = context.resources.openRawResource(R.raw.spanish_audio) val audioBytes = inputStream.readBytes() inputStream.close() try { val translation: String = yChat.audioTranslations() .setModel("whisper-1") .setPrompt("Spanish interview about technology") .setResponseFormat("text") .setTemperature(0.0) .execute("spanish_interview.m4a", audioBytes) println("English translation: $translation") } catch (e: YChatException) { println("Translation failed: ${e.message}") } // Kotlin - Get verbose JSON output with metadata val verboseTranslation = yChat.audioTranslations() .setModel("whisper-1") .setResponseFormat("verbose_json") .execute("french_lecture.mp3", frenchAudioBytes) println("Translation with metadata: $verboseTranslation") ``` -------------------------------- ### Translate Audio to English using YChat JVM SDK Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This API endpoint translates audio data into English. Similar to transcription, it uses a POST request with multipart/form-data for the audio file. The output is the translated text in English. ```cURL curl -X POST \ -H "Content-Type: multipart/form-data" \ -F "file=@/path/to/audio/file" \ "http://localhost:8080/api/ychat/audio/translations" ``` -------------------------------- ### Model API Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This endpoint retrieves a specific AI model based on its ID. ```APIDOC ## GET /api/ychat/models/{modelID} ### Description Retrieves the artificial intelligence model based on the given ID. ### Method GET ### Endpoint http://localhost:[port_number]/api/ychat/models/{modelID} ### Parameters #### Path Parameters - **modelID** (string) - Required - The ID of the model to retrieve. ### Request Example `GET http://localhost:8080/api/ychat/models/babbage` ### Response #### Success Response (200) - **id** (string) - The ID of the model. - **name** (string) - The name of the model. #### Response Example { "id": "babbage", "name": "babbage" } ``` -------------------------------- ### Transcribe Audio to Text Source: https://context7.com/codeandtheory/ychat/llms.txt Converts audio files into text transcriptions in the original language. Supports various response formats including JSON, text, SRT, and VTT. Optional parameters like prompt, temperature, and language code can be provided for better accuracy and context. Requires an API key for initialization. Handles audio data as bytes or FileBytes wrapper. ```kotlin // Kotlin - Transcribe audio file val yChat = YChat.create("your-api-key") // Load audio file from resources val inputStream = context.resources.openRawResource(R.raw.interview_audio) val audioBytes = inputStream.readBytes() inputStream.close() try { val transcription: String = yChat.audioTranscriptions() .setModel("whisper-1") .setPrompt("Interview about technology trends") // Optional context .setResponseFormat("json") // Options: "json", "text", "srt", "verbose_json", "vtt" .setTemperature(0.2) .setLanguage("en") // ISO-639-1 language code .execute("interview.m4a", audioBytes) println("Transcription: $transcription") } catch (e: YChatException) { println("Transcription failed: ${e.message}") } // Kotlin - Get transcription with timestamps (SRT format) val srtTranscription = yChat.audioTranscriptions() .setModel("whisper-1") .setResponseFormat("srt") .setLanguage("en") .execute("meeting.mp3", audioFileBytes) println("SRT Subtitles:\n$srtTranscription") // Kotlin - Using FileBytes wrapper for cross-platform compatibility import co.yml.ychat.core.model.FileBytes val fileBytes = FileBytes(audioByteArray) val result = yChat.audioTranscriptions() .setModel("whisper-1") .setResponseFormat("text") .execute("recording.m4a", fileBytes) ``` -------------------------------- ### Edits API Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This endpoint edits text based on a provided instruction. ```APIDOC ## GET /api/ychat/edits ### Description Edits the prompt based on the provided instruction. ### Method GET ### Endpoint http://localhost:[port_number]/api/ychat/edits ### Parameters #### Query Parameters - **input** (string) - Required - The input text to use as a starting point for the edit. - **instruction** (string) - Required - The instruction that tells the model how to edit the prompt. ### Request Example `GET http://localhost:8080/api/ychat/edits?input=What day of the wek is it?&instruction=Fix the spelling mistakes` ### Response #### Success Response (200) - **text** (string) - The edited text. #### Response Example { "text": "What day of the week is it?" } ``` -------------------------------- ### Generate Images from Text Prompts (Swift) Source: https://context7.com/codeandtheory/ychat/llms.txt Generates images from a given text prompt using the YChat API in Swift. Allows configuration of the number of results, image size, and response format. Uses async/await for asynchronous operations and do-catch for error handling. ```swift let yChat = YChatCompanion.shared.create(apiKey: "your-api-key") do { let imageUrls = try await yChat.imageGenerations() .setResults(results: 2) .setSize(size: "1024x1024") .setResponseFormat(responseFormat: "url") .execute(prompt: "A futuristic robot in a garden") for (index, url) in imageUrls.enumerated() { print("Image (index + 1): (url)") // Load image from URL into UIImage/NSImage } } catch { print("Image generation failed: (error)") } ``` -------------------------------- ### Generate Text Completion with YChat API Source: https://github.com/codeandtheory/ychat/blob/main/guides/Features.md Generates text completions based on a given prompt. Allows setting model, max tokens, temperature, and topP. Supports Swift and Kotlin. Requires an API key. ```swift var yChat: YChat { YChatCompanion.shared.create(apiKey: "your-api-key") } do { let result = try await yChat.completion() .setModel(input: "text-davinci-003") .setInput(input: "Say this is a test.") .setMaxTokens(tokens: 1024) .setTemperature(temperature: 1.0) .setTopP(topP: 1.0) .saveHistory(isSaveHistory: false) .execute() } catch { // catch any error that may occurs on api call. } ``` ```kotlin val yChat by lazy { YChat.create("your-api-key") } try { val result = yChat.completion() .setModel("text-davinci-003") .setInput("Say this is a test.") .setMaxTokens(1024) .setTemperature(1.0) .setTopP(1.0) .saveHistory(false) .execute() } catch (e: exception) { // catch any error that may occurs on api call. } ``` -------------------------------- ### Translate Audio to English Source: https://context7.com/codeandtheory/ychat/llms.txt Translates audio content from any supported language into English text. Supports text and JSON response formats. Optional prompt and temperature parameters can be provided. Requires an API key for initialization. Handles audio data as Data objects. ```swift // Swift - Translate audio to English let yChat = YChatCompanion.shared.create(apiKey: "your-api-key") guard let audioUrl = Bundle.main.url(forResource: "german_speech", withExtension: "m4a") else { print("Audio file not found") return } let audioData = try! Data(contentsOf: audioUrl) do { let translation = try await yChat.audioTranslations() .setModel(model: "whisper-1") .setPrompt(prompt: "German presentation about AI") .setResponseFormat(format: "text") .setTemperature(temperature: 0.0) .execute(filename: "german_speech.m4a", audioFile: audioData) print("English translation: \(translation)") } catch { print("Translation failed: \(error)") } ``` -------------------------------- ### Transcribe Audio to Text Source: https://context7.com/codeandtheory/ychat/llms.txt Converts audio files into text transcriptions in the original language. Supports various response formats including JSON, text, SRT, and VTT. Optional parameters like prompt, temperature, and language code can be provided for better accuracy and context. Requires an API key for initialization. Handles audio data as Data objects. ```swift // Swift - Transcribe audio let yChat = YChatCompanion.shared.create(apiKey: "your-api-key") guard let audioFileUrl = Bundle.main.url(forResource: "podcast", withExtension: "m4a") else { print("Audio file not found") return } let audioData = try! Data(contentsOf: audioFileUrl) do { let transcription = try await yChat.audioTranscriptions() .setModel(model: "whisper-1") .setPrompt(prompt: "Podcast about iOS development") .setResponseFormat(format: "json") .setTemperature(temperature: 0.0) .setLanguage(language: "en") .execute(filename: "podcast.m4a", audioFile: audioData) print("Transcription: \(transcription)") } catch { print("Transcription failed: \(error)") } // Swift - Get VTT subtitles for video do { let vttSubtitles = try await yChat.audioTranscriptions() .setModel(model: "whisper-1") .setResponseFormat(format: "vtt") .execute(filename: "video.mp4", audioFile: videoAudioData) print("VTT Subtitles:\n\(vttSubtitles)") } catch { print("Subtitle generation failed: \(error)") } ``` -------------------------------- ### POST /completions Source: https://github.com/codeandtheory/ychat/blob/main/guides/Features.md Generates a text completion based on a given prompt. The model attempts to match the context or pattern provided. ```APIDOC ## POST /completions ### Description Generates a text completion based on a given prompt. ### Method POST ### Endpoint /completions ### Parameters #### Request Body - **model** (string) - Required - The model to use for completion. - **input** (string) - Required - The prompt for the model. - **max_tokens** (integer) - Optional - The maximum number of tokens to generate. - **temperature** (number) - Optional - The sampling temperature. - **top_p** (number) - Optional - The nucleus sampling probability. - **save_history** (boolean) - Optional - Whether to save the history. ### Request Example { "model": "text-davinci-003", "input": "Say this is a test.", "max_tokens": 1024, "temperature": 1.0, "top_p": 1.0, "save_history": false } ### Response #### Success Response (200) - **completion** (string) - The generated text completion. #### Response Example { "completion": "This is a test completion." } ``` -------------------------------- ### Edit Text using YChat JVM SDK Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This API endpoint edits provided input text based on a given instruction. It's useful for text correction or transformation. Inputs are the text to edit and the editing instruction. ```Java GET http://localhost:[port_number]/api/ychat/edits?input=What day of the wek is it?&instruction=Fix the spelling mistakes ``` -------------------------------- ### Retrieve Specific AI Model using YChat JVM SDK Source: https://github.com/codeandtheory/ychat/blob/main/sample/jvm/README.md This API endpoint retrieves details about a specific artificial intelligence model based on its ID. It allows for querying information about individual models. The input is the modelID string. ```Java GET http://localhost:[port_number]/api/ychat/models/babbage ```