Y-Chat Kotlin Multiplatform Library

repository·main·Indexed 40 days ago

https://github.com/codeandtheory/ychat

A Kotlin Multiplatform (KMP) library providing a unified API to integrate OpenAI's ChatGPT capabilities into iOS, Android, and JVM applications. It supports features including text completions, chat completions, image generation, prompt edits, audio transcriptions, and audio translations. Version 1.4.1 is available via Gradle and Swift Package Manager.

Tokens
5.4K
Snippets
21
Records
22
Agent score
100%

What's inside Y-Chat

  1. Available Y—Chat Features

    main

    Y—Chat provides a consistent interface for several OpenAI-powered features across platforms:

    • ListModels: List available models.
    • RetrieveModel: Retrieve specific model details.
    • Completions: Standard text completion.
    • ChatCompletions: Chat-based interactions.
    • ImageGenerations: Generate images from text.
    • Edits: Edit existing text.
    • AudioTranscriptions: Convert audio to text.
    • AudioTranslations: Translate audio to different languages.
  2. Configure the API key for the YChat iOS Sample

    main

    To run the YChat iOS sample project successfully, you must provide a valid API key via the project's configuration file.

    1. Open the EnvConfig.xcconfig file located in the root directory of the sample project.
    2. Locate the API_KEY variable.
    3. Assign your API key to this variable.

    If you do not have an API key, you can obtain one from OpenAI.

    // EnvConfig.xcconfig
    API_KEY = YOUR_API_KEY_HERE
  3. Setup Y—Chat for Android/JVM

    main

    To use Y—Chat in an Android or JVM project, add the library via Gradle.

    First, ensure mavenCentral() is included in your repositories block. Then, add the dependency to your build.gradle file:

    implementation("co.yml:ychat:1.4.1")
    repositories {
        mavenCentral()
        // ...
    }
    
    dependencies {
        implementation("co.yml:ychat:1.4.1")
    }
  4. Configure the OpenAI API key for the Android Sample

    main

    To run the YChat GPT Android Sample successfully, you must provide an OpenAI API key. This is configured via the local.properties file in the root directory of the sample project.

    1. Open the local.properties file located in the root folder of the sample project.
    2. Locate the api.key variable.
    3. Assign your OpenAI API key to this variable.

    For details on how to obtain an API key, refer to the OpenAI authentication documentation.

    api.key=YOUR_OPENAI_API_KEY
  5. Setup the YChat GPT JVM Sample

    main

    To run the YChat GPT JVM sample server, follow these configuration steps:

    1. Rename Configuration File: Locate sample/jvm/main/src/resources/application.properties.txt and remove the .txt suffix so the file is named application.properties.
    2. Configure API Key: Open the renamed application.properties file and set your OpenAI API key in the apiKey variable.
    3. Run the Server: Use the Gradle wrapper to start the server on a specific port.

    Replace [port_number] with an available port (e.g., 8080).

    ./gradlew bootRun -Dserver.port=8080
  6. Setup Y—Chat for iOS

    main

    To integrate Y—Chat into an iOS project, add the repository as a Swift Package Manager (SPM) dependency:

    1. Open your project in Xcode and go to File > Add Packages...
    2. In the search field at the top right, enter the repository URL: https://github.com/yml-org/ychat.git
    3. Click Add Package to include the SDK in your project.

    You can then initialize the SDK using YChatCompanion.shared.create(apiKey:).

    var yChat: YChat {
        YChatCompanion.shared.create(apiKey: "your-api-key") 
    }
  7. Use Completions in Kotlin (Android/JVM)

    main

    In Kotlin, initialize the YChat instance (ideally using lazy) and use the completion builder pattern. Configure parameters like input, history saving, and max tokens, then call .execute().

    Wrap the call in a try-catch block to handle potential API errors.

    val yChat by lazy {
      YChat.create("your-api-key")
    }
    
    try {
      val result = yChat.completion()
         .setInput("Say this is a test.")
         .saveHistory(false)
         .setMaxTokens(1024)
         .execute()
      
    } catch (e: Exception) {
      // catch any error that may occurs on api call.  
    }
  8. Use Completions in Swift (iOS)

    main

    After initializing YChat via YChatCompanion, you can perform text completions using a builder pattern. Use .setInput(), .setMaxTokens(), and .saveHistory() to configure the request before calling .execute().

    Note: The .execute() method is asynchronous and should be called within an async context.

    var yChat: YChat {
        YChatCompanion.shared.create(apiKey: "your-api-key") 
    }
    
    do {
      let result = try await yChat.completion()
                        .setInput(input: "Say this is a test.")
                        .setMaxTokens(tokens: 1024)
                        .saveHistory(isSaveHistory: false)
                        .execute()
    } catch {
      // catch any error that may occurs on api call.  
    }
  9. Generate text completions with completion()

    main

    The completion() API takes a text prompt and generates a completion that matches the provided context or pattern.

    Available configuration options:

    • .setModel(input:) / .setModel(model:): Specify the model ID (e.g., "text-davinci-003").
    • .setInput(input:): The prompt text.
    • .setMaxTokens(tokens:) / .setMaxTokens(maxTokens:): Maximum number of tokens to generate.
    • .setTemperature(temperature:): Controls randomness.
    • .setTopP(topP:): Nucleus sampling parameter.
    • .saveHistory(isSaveHistory:) / .saveHistory(saveHistory:): Boolean to persist conversation history.
    • .execute(): Executes the request.
    // Swift
    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 {
      // handle error
    }
    // Kotlin
    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) {
        // handle error
    }
  10. Retrieve AI Models

    main

    The sample provides two endpoints for interacting with available AI models:

    List Models

    Retrieves a list of all currently available artificial intelligence models. Endpoint: GET http://localhost:[port_number]/api/ychat/models

    Get Specific Model

    Retrieves details for a specific artificial intelligence model using its ID. Endpoint: GET http://localhost:[port_number]/api/ychat/models/{modelID}

    Example (List): GET http://localhost:8080/api/ychat/models

    Example (Specific Model): GET http://localhost:8080/api/ychat/models/babbage

    GET http://localhost:8080/api/ychat/models/babbage
  11. Use the Chat Completions Endpoint

    main

    Generates text based on a prompt and a specified topic to constrain the response.

    Endpoint: GET http://localhost:[port_number]/api/ychat/chat-completions

    Parameters:

    • input: The prompt for generating text.
    • topic: The topic to limit the response to.

    Example: GET http://localhost:8080/api/ychat/chat-completions?input="Tell me an exercise plan"&topic=fitness

    GET http://localhost:8080/api/ychat/chat-completions?input="Tell me an exercise plan"&topic=fitness
  12. Use the Completion Endpoint

    main

    Generates text based on a provided prompt.

    Endpoint: GET http://localhost:[port_number]/api/ychat/completion

    Parameters:

    • input: The prompt for generating text.

    Example: GET http://localhost:8080/api/ychat/completion?input="What is 1 + 1?"

    GET http://localhost:8080/api/ychat/completion?input="What is 1 + 1?"