Skip to content

Commit

Permalink
feat: Support adding custom api keys
Browse files Browse the repository at this point in the history
Tested-by: Pranav Purwar <[email protected]>
Signed-off-by: PranavPurwar <[email protected]>
  • Loading branch information
PranavPurwar committed Jan 9, 2024
1 parent b2900e3 commit 445de8a
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 60 deletions.
4 changes: 1 addition & 3 deletions app/src/main/kotlin/org/cosmicide/chat/ChatProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ object ChatProvider {

private var chat = generativeModel.startChat()

@JvmStatic
fun regenerateModel(
temp: Float = Prefs.temperature,
top_p: Float = Prefs.topP,
Expand All @@ -54,7 +53,7 @@ object ChatProvider {
)

GenerativeModel(
apiKey = BuildConfig.GEMINI_API_KEY,
apiKey = Prefs.geminiApiKey.ifEmpty { BuildConfig.GEMINI_API_KEY },
modelName = "gemini-pro",
safetySettings = safetySettings,
generationConfig = generationConfig {
Expand All @@ -69,7 +68,6 @@ object ChatProvider {
}
}

@JvmStatic
fun generate(conversation: List<Map<String, String>>): Flow<GenerateContentResponse> {
return chat.sendMessageStream(conversation.last()["text"]!!)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ package org.cosmicide.fragment.settings
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.FragmentActivity
import de.Maxr1998.modernpreferences.PreferenceScreen
import de.Maxr1998.modernpreferences.helpers.editText
import de.Maxr1998.modernpreferences.helpers.seekBar
import de.Maxr1998.modernpreferences.helpers.singleChoice
import de.Maxr1998.modernpreferences.preferences.choice.SelectionItem
Expand All @@ -33,6 +34,13 @@ class GeminiSettings(private val activity: FragmentActivity) : SettingsProvider
R.drawable.outline_forum_24,
activity.theme
)

editText(PreferenceKeys.GEMINI_API_KEY) {
title = "Gemini API Key"
summary =
"The API key to connect to the Gemini API. You can get one at https://makersuite.google.com/app/apikey"
}

singleChoice(PreferenceKeys.TEMPERATURE, keys) {
title = "temperature"
summary =
Expand Down
1 change: 1 addition & 0 deletions app/src/main/kotlin/org/cosmicide/util/PreferenceKeys.kt
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ object PreferenceKeys {
const val PLUGIN_SETTINGS = "plugin_settings"

// Gemini Pro
const val GEMINI_API_KEY = "gemini_api_key"
const val TEMPERATURE = "temperature"
const val TOP_P = "top_p"
const val TOP_K = "top_k"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ package org.cosmicide.build.java
import com.sun.tools.javac.api.JavacTool
import org.cosmicide.build.BuildReporter
import org.cosmicide.build.Task
import org.cosmicide.project.Project
import org.cosmicide.build.util.getSourceFiles
import org.cosmicide.build.util.getSystemClasspath
import org.cosmicide.common.Prefs
import org.cosmicide.rewrite.util.FileUtil
import org.cosmicide.project.Project
import java.io.File
import java.io.Writer
import java.nio.file.Files
Expand All @@ -24,7 +25,6 @@ import javax.tools.SimpleJavaFileObject
import javax.tools.StandardLocation

class JavaCompileTask(val project: Project) : Task {

val diagnostics = DiagnosticCollector<JavaFileObject>()
val tool = JavacTool.create()
val fileManager = tool.getStandardFileManager(diagnostics, null, null)
Expand All @@ -39,13 +39,15 @@ class JavaCompileTask(val project: Project) : Task {
reporter.reportWarning(e.stackTraceToString())
}

val javaFiles = getSourceFiles(project.srcDir)
val javaFiles = project.srcDir.getSourceFiles("java")

if (javaFiles.isEmpty()) {
reporter.reportInfo("No java files found. Skipping compilation.")
return
}

reporter.reportInfo("Compilingg")

val size = javaFiles.size
reporter.reportInfo("Compiling $size java ${if (size == 1) "file" else "files"}...")

Expand Down Expand Up @@ -115,22 +117,12 @@ class JavaCompileTask(val project: Project) : Task {
}
}

fun getSourceFiles(directory: File): List<File> {
return directory.listFiles()?.filter {
it.isFile && it.extension == "java"
} ?: emptyList()
}

fun getClasspath(project: Project): List<File> {
val classpath = mutableListOf(File(project.binDir, "classes"))
val libDir = project.libDir
if (libDir.exists() && libDir.isDirectory) {
classpath += libDir.listFiles()?.toList() ?: emptyList()
classpath += libDir.walk().filter { it.extension == "jar" }.toList()
}
return classpath
}

fun getSystemClasspath(): List<File> {
return FileUtil.classpathDir.listFiles()?.toList() ?: emptyList()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import org.cosmicide.build.BuildReporter
import org.cosmicide.build.Task
import org.cosmicide.build.util.getSourceFiles
import org.cosmicide.build.util.getSystemClasspath
import org.cosmicide.project.Project
import org.cosmicide.common.Prefs
import org.cosmicide.project.Project
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation
Expand All @@ -35,7 +35,7 @@ class KotlinCompiler(val project: Project) : Task {
}

override fun execute(reporter: BuildReporter) {
val sourceFiles = getSourceFiles(project.srcDir, "kt")
val sourceFiles = project.srcDir.getSourceFiles("kt")
if (sourceFiles.isEmpty()) {
reporter.reportInfo("No Kotlin files are present. Skipping Kotlin compilation.")
return
Expand Down
9 changes: 4 additions & 5 deletions build-tools/src/main/java/org/cosmicide/build/util/utils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@ import java.io.File
* @param extension The file extension to filter by.
* @return A list of files with the given extension within the specified directory and its subdirectories.
*/
fun getSourceFiles(directory: File, extension: String): List<File> {
return directory.listFiles()
?.flatMap { if (it.isDirectory) getSourceFiles(it, extension) else listOf(it) }
?.filter { it.extension == extension }
?: emptyList()
fun File.getSourceFiles(extension: String): List<File> {
return walkTopDown()
.filter { it.isFile && it.extension == extension }
.toList()
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import io.github.rosemoe.sora.lang.diagnostic.DiagnosticDetail
import io.github.rosemoe.sora.lang.diagnostic.DiagnosticRegion
import io.github.rosemoe.sora.lang.diagnostic.Quickfix
import io.github.rosemoe.sora.widget.CodeEditor
import org.cosmicide.common.Prefs
import org.cosmicide.completion.java.parser.CompletionProvider
import org.cosmicide.project.Project
import org.cosmicide.common.Prefs
import org.cosmicide.rewrite.util.FileUtil
import java.io.File
import java.nio.charset.Charset
Expand Down Expand Up @@ -110,43 +110,48 @@ class JavaAnalyzer(
fun getDiagnostics(): List<DiagnosticRegion> {
val diagnostic = diagnostics.diagnostics
val problems = mutableListOf<DiagnosticRegion>()
for (it in diagnostic) {
if (it.source == null) continue
val severity =
if (it.kind == Diagnostic.Kind.ERROR) DiagnosticRegion.SEVERITY_ERROR else DiagnosticRegion.SEVERITY_WARNING

val message = it.getMessage(Locale.getDefault())
val quickFixes = mutableListOf<Quickfix>()
if (it.code == "compiler.err.cant.resolve.location") {
val symbol = it.source.getCharContent(true)
.substring(it.startPosition.toInt(), it.endPosition.toInt())
Log.d("JavaAnalyzer", symbol)
CompletionProvider.symbolCacher.filterClassNames(symbol).forEach { name ->
quickFixes.add(Quickfix("Import ${name.value}", 0L) {
val lines = editor.text.lines()
var firstImportLine = lines.indexOfFirst { it.startsWith("import ") }
if (firstImportLine == -1) {
firstImportLine = lines.indexOfFirst { it.startsWith("package ") } + 1
}
Log.d("JavaAnalyzer", "index: $firstImportLine")
editor.text.insert(
firstImportLine,
0,
"import ${name.key}.${name.value};\n"
)
})
try {
for (it in diagnostic) {
if (it.source == null) continue
val severity =
if (it.kind == Diagnostic.Kind.ERROR) DiagnosticRegion.SEVERITY_ERROR else DiagnosticRegion.SEVERITY_WARNING

val message = it.getMessage(Locale.getDefault())
val quickFixes = mutableListOf<Quickfix>()
if (it.code == "compiler.err.cant.resolve.location") {
val symbol = it.source.getCharContent(true)
.substring(it.startPosition.toInt(), it.endPosition.toInt())
Log.d("JavaAnalyzer", symbol)
CompletionProvider.symbolCacher.filterClassNames(symbol).forEach { name ->
quickFixes.add(Quickfix("Import ${name.value}", 0L) {
val lines = editor.text.lines()
var firstImportLine = lines.indexOfFirst { it.startsWith("import ") }
if (firstImportLine == -1) {
firstImportLine =
lines.indexOfFirst { it.startsWith("package ") } + 1
}
Log.d("JavaAnalyzer", "index: $firstImportLine")
editor.text.insert(
firstImportLine,
0,
"import ${name.key}.${name.value};\n"
)
})
}
}
}

problems.add(
DiagnosticRegion(
it.startPosition.toInt(),
it.endPosition.toInt(),
severity,
0,
DiagnosticDetail(message, quickfixes = quickFixes),
problems.add(
DiagnosticRegion(
it.startPosition.toInt(),
it.endPosition.toInt(),
severity,
0,
DiagnosticDetail(message, quickfixes = quickFixes),
)
)
)
}
} catch (e: Exception) {
e.printStackTrace()
}
return problems
}
Expand Down
3 changes: 3 additions & 0 deletions common/src/main/java/org/cosmicide/common/Prefs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ object Prefs {
prefs.getString("font_size", "14")?.toFloatOrNull()?.coerceIn(1f, 32f) ?: 14f
}.getOrElse { 16f }

val geminiApiKey: String
get() = prefs.getString("gemini_api_key", "") ?: ""

val temperature: Float
get() = runCatching {
prefs.getString("temperature", "0.9")?.toFloatOrNull()?.coerceIn(0f, 1f) ?: 0.9f
Expand Down

0 comments on commit 445de8a

Please sign in to comment.