Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Migrate common to KMP #154

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
.gradle/
build/

# KMP files
.kotlin/

# Local configuration file (sdk path, etc)
local.properties

Expand Down
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ plugins {
id("com.android.library") version "8.1.3" apply false
id("org.jetbrains.dokka") version "1.8.20" apply false
kotlin("android") version "1.8.22" apply false
kotlin("multiplatform") version "2.0.0" apply false
kotlin("plugin.serialization") version "1.8.22" apply false
id("com.ncorti.ktfmt.gradle") version "0.18.0" apply false
id("license-plugin")
Expand Down
118 changes: 50 additions & 68 deletions common/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -14,89 +14,74 @@
* limitations under the License.
*/

@file:Suppress("UnstableApiUsage")
@file:OptIn(ExperimentalKotlinGradlePluginApi::class)

import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
import org.jetbrains.kotlin.gradle.dsl.KotlinVersion

plugins {
id("com.android.library")
id("com.android.kotlin.multiplatform.library") // version "8.6.0-alpha02"
kotlin("multiplatform") version "2.0.0"
id("maven-publish")
id("com.ncorti.ktfmt.gradle")
id("com.ncorti.ktfmt.gradle") version "0.18.0"
id("changelog-plugin")
id("release-plugin")
kotlin("android")
kotlin("plugin.serialization")
}

ktfmt {
googleStyle()
}

android {
namespace = "com.google.ai.client.generativeai.common"
compileSdk = 34

buildFeatures.buildConfig = true

defaultConfig {
kotlin {
val ktorVersion = "2.3.2"
androidLibrary {
compileSdk = 34
minSdk = 21

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro")

buildConfigField("String", "VERSION_NAME", "\"${project.version.toString()}\"")
}

publishing {
singleVariant("release") {
withSourcesJar()
namespace = "com.google.ai.client.generativeai.common"
optimization {
minify = false
consumerKeepRules.file("consumer-rules.pro")
consumerKeepRules.publish = true
}
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
withAndroidTestOnJvm {
isReturnDefaultValues = true
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
jvmToolchain(17)
compilerOptions {
apiVersion.set(KotlinVersion.KOTLIN_1_8)
languageVersion.set(KotlinVersion.KOTLIN_1_8)
}

testOptions {
unitTests.isReturnDefaultValues = true
}
}

dependencies {
val ktorVersion = "2.3.2"

implementation("io.ktor:ktor-client-okhttp:$ktorVersion")
implementation("io.ktor:ktor-client-core:$ktorVersion")
implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
implementation("io.ktor:ktor-client-logging:$ktorVersion")

implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.1")
implementation("androidx.core:core-ktx:1.12.0")
implementation("org.slf4j:slf4j-nop:2.0.9")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactive:1.7.3")
implementation("org.reactivestreams:reactive-streams:1.0.3")
jvm()
sourceSets {
commonMain.dependencies {
implementation("io.ktor:ktor-client-core:$ktorVersion")
implementation("org.jetbrains.kotlin:kotlin-stdlib-common:1.8.22")
implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
implementation("io.ktor:ktor-client-logging:$ktorVersion")

implementation("com.google.guava:listenablefuture:1.0")
implementation("androidx.concurrent:concurrent-futures:1.2.0-alpha02")
implementation("androidx.concurrent:concurrent-futures-ktx:1.2.0-alpha02")
testImplementation("junit:junit:4.13.2")
testImplementation("io.kotest:kotest-assertions-core:4.0.7")
testImplementation("io.kotest:kotest-assertions-jvm:4.0.7")
testImplementation("io.kotest:kotest-assertions-json:4.0.7")
testImplementation("io.ktor:ktor-client-mock:$ktorVersion")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.1")
implementation("org.slf4j:slf4j-nop:2.0.9")
}
androidMain.dependencies {
implementation("io.ktor:ktor-client-okhttp:$ktorVersion")
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.8.22")
}
jvmMain.dependencies {
implementation("io.ktor:ktor-client-okhttp:$ktorVersion")
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.8.22")
}
jvmTest.dependencies {
implementation("junit:junit:4.13.2")
implementation("io.kotest:kotest-assertions-core-jvm:4.0.7")
implementation("io.kotest:kotest-assertions-json-jvm:4.0.7")
implementation("io.ktor:ktor-client-mock-jvm:$ktorVersion")
}
}
}

publishing {
Expand All @@ -113,9 +98,6 @@ publishing {
}
}
}
afterEvaluate {
from(components["release"])
}
}
}
repositories {
Expand Down
2 changes: 2 additions & 0 deletions common/gradle.properties
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
version=0.5.0
kotlin.mpp.androidSourceSetLayoutVersion=2
kotlin.compiler.runViaBuildToolsApi=true
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.ai.client.generativeai.common

import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.okhttp.OkHttp

internal actual fun createHttpClient(): HttpClientEngine = OkHttp.create()
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.ai.client.generativeai.common.util

import kotlin.reflect.KClass

internal actual inline fun <reified T : Any> KClass<T>.name(): String = java.name
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.ai.client.generativeai.common.util

import android.util.Log

internal actual fun Error(tag: String, message: String) {
Log.e(tag, message)
}

internal actual fun Warning(tag: String, message: String) {
Log.w(tag, message)
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2023 Google LLC
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,19 +16,10 @@

package com.google.ai.client.generativeai.common.util

import com.google.ai.client.generativeai.common.SerializationException
import kotlinx.serialization.SerialName
import java.lang.reflect.Field

/**
* Removes the last character from the [StringBuilder].
*
* If the StringBuilder is empty, calling this function will throw an [IndexOutOfBoundsException].
*
* @return The [StringBuilder] used to make the call, for optional chaining.
* @throws IndexOutOfBoundsException if the StringBuilder is empty.
*/
internal fun StringBuilder.removeLast(): StringBuilder =
if (isEmpty()) throw IndexOutOfBoundsException("StringBuilder is empty.")
else deleteCharAt(length - 1)
import kotlin.reflect.KClass

/**
* A variant of [getAnnotation][Field.getAnnotation] that provides implicit Kotlin support.
Expand All @@ -39,3 +30,20 @@ internal fun StringBuilder.removeLast(): StringBuilder =
* ```
*/
internal inline fun <reified T : Annotation> Field.getAnnotation() = getAnnotation(T::class.java)


/**
* Provides the name to be used in serialization for this enum value.
*
* By default an enum is serialized to its [name][Enum.name], and can be overwritten by providing a
* [SerialName] annotation.
*/
internal actual fun <T : Enum<T>> T.serialName(): String = declaringJavaClass.getField(name).getAnnotation<SerialName>()?.value ?: name

/**
* Variant of [kotlin.enumValues] that provides support for [KClass] instances of enums.
*
* @throws SerializationException if the class is not a valid enum. Beyond runtime emily magic, this
* shouldn't really be possible.
*/
internal actual fun <T : Enum<T>> KClass<T>.enumValues(): Array<T> = java.enumConstants ?: throw SerializationException("$simpleName is not a valid enum type.")
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@

package com.google.ai.client.generativeai.common

import android.util.Log
// import android.util.Log
import com.google.ai.client.generativeai.common.server.FinishReason
import com.google.ai.client.generativeai.common.util.Warning
import com.google.ai.client.generativeai.common.util.decodeToFlow
import com.google.ai.client.generativeai.common.util.name
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.HttpRequestBuilder
Expand Down Expand Up @@ -53,6 +54,8 @@ internal val JSON = Json {
prettyPrint = false
}

internal expect fun createHttpClient(): HttpClientEngine

/**
* Backend class for interfacing with the Gemini API.
*
Expand Down Expand Up @@ -81,7 +84,7 @@ internal constructor(
requestOptions: RequestOptions,
apiClient: String,
headerProvider: HeaderProvider? = null,
) : this(key, model, requestOptions, OkHttp.create(), apiClient, headerProvider)
) : this(key, model, requestOptions, createHttpClient(), apiClient, headerProvider)

private val model = fullModelName(model)

Expand Down Expand Up @@ -150,7 +153,7 @@ internal constructor(
}
}
} catch (e: TimeoutCancellationException) {
Log.w(TAG, "HeaderProvided timed out without generating headers, ignoring")
Warning(TAG, "HeaderProvided timed out without generating headers, ignoring")
}
}
}
Expand Down Expand Up @@ -203,7 +206,7 @@ internal constructor(
}

companion object {
private val TAG = APIController::class.java.simpleName
private val TAG = APIController::class.name()
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.ai.client.generativeai.common.util

import kotlin.reflect.KClass

internal expect inline fun <reified T : Any> KClass<T>.name(): String
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.ai.client.generativeai.common.util

internal expect fun Error(tag: String, message: String)

internal expect fun Warning(tag: String, message: String)
Loading
Loading