diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..00a51af --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# These are explicitly windows files and should use crlf +*.bat text eol=crlf + diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..1ca9fcd --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,13 @@ +# These are supported funding model platforms + +github: [paulotaylor] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/workflows/dokka-publish.yml b/.github/workflows/dokka-publish.yml new file mode 100644 index 0000000..964e194 --- /dev/null +++ b/.github/workflows/dokka-publish.yml @@ -0,0 +1,35 @@ +name: Publish Dokka Documentation + +on: + release: + types: [published] + workflow_dispatch: + +jobs: + build-and-publish: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - name: Set up JDK + uses: actions/setup-java@v2 + with: + distribution: 'temurin' + java-version: '11' + + - name: Grant execute permission for gradlew + run: chmod +x gradlew + + - name: Generate Dokka HTML documentation + run: ./gradlew dokkaHtml + + - name: Deploy to GitHub Pages + uses: JamesIves/github-pages-deploy-action@4.1.5 + with: + token: ${{ secrets.GITHUB_TOKEN }} + branch: gh-pages + folder: build/dokka/html diff --git a/.github/workflows/readme-version.yml b/.github/workflows/readme-version.yml new file mode 100644 index 0000000..ec14f15 --- /dev/null +++ b/.github/workflows/readme-version.yml @@ -0,0 +1,37 @@ +name: Update README Version + +on: + release: + types: + - published + workflow_dispatch: + +jobs: + update-version: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + + - name: Update version in README + run: | + # Extract the version from the build.gradle.kts file + VERSION=$(grep -oP 'version\s*=\s*"\K\d+\.\d+\.\d+' build.gradle.kts) + + # Update the README.md file + export VERSION + python -c "import re, os; version=os.environ['VERSION']; content=open('README.md').read(); content=re.sub(r'\d+\.\d+\.\d+', f'{version}', content); open('README.md', 'w').write(content)" + + - name: Commit and push changes + run: | + git config --global user.name "GitHub Actions Bot" + git config --global user.email "paulotaylor@gmail.com" + git remote set-url origin https://${{ secrets.PAT }}@github.com/paulotaylor/klaude.git + git add README.md + git diff --quiet && git diff --staged --quiet || (git commit -m "Update version in README.md" && git push) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..95b73c7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +# Eclipse +.classpath +.project +.settings/ + +# Intellij +.idea/ +*.iml +*.iws + +# Mac +.DS_Store + +# VSCode +.vscode/ + +# Netbrans +nbproject/ +nbactions.xml + +# Gradle +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar +gradle.properties + +# Maven +log/ +target/ + +# +.env \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3fbe028 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Paulo Taylor + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b9d1343 --- /dev/null +++ b/README.md @@ -0,0 +1,89 @@ +
+ +# Klaude - Kotlin Client for Claude from Anthropic + [![Maven Central](https://img.shields.io/maven-central/v/com.klaude/klaude?color=blue&label=Download)](https://central.sonatype.com/namespace/com.klaude) + [![License](https://img.shields.io/github/license/WeaponMechanics/ArmorMechanics)](https://github.com/WeaponMechanics/ArmorMechanics/blob/master/LICENSE) + +A community-maintained easy-to-use Java/Kotlin Claude API +
+ +## Documentation +* [Claude API](https://docs.anthropic.com/claude/docs) + +## Installation +For Kotlin DSL (`build.gradle.kts`), add this to your dependencies block: +```kotlin +dependencies { + implementation("com.klaude:klaude:0.0.1") +} +``` +For Maven projects, add this to your `pom.xml` file in the `` block: +```xml + + com.klaude + klaude + 0.0.1 + +``` +See the [maven repository](https://central.sonatype.com/artifact/com.klaude/klaude/0.0.1) for gradle/ant/etc. + + +## Working Example +This is a basic working example. +```kotlin +fun translateToEnglish() { + + val klaudeClient = KlaudeClient.Builder() + .key("YOUR_API_KEY") + .model("claude-2") + .maxTokensToSample(1000) + .build() + val text = "Olá, tudo bem?" + klaudeClient.complete("Translate to English: $text") { result -> + println(result ?: "[empty]") + } +} + +fun chat() { + val scan = Scanner(System.`in`) + + val klaude = KlaudeClient.Builder() + .model("claude-2") + .key("YOUR_API_KEY") + .maxTokensToSample(500) + .build() + + val messages = mutableListOf(KlaudeMessage("You are a helpful assistant", KlaudeMessageType.USER)) + + println("Start chatting, type 'exit' or 'quit' to finish:\n") + + while (true) { + + println("Human:") + + val input = scan.nextLine().trim() + + if (input.isBlank()) { + continue + } + + if (input == "exit" || input == "quit") { + break + } + messages.add(KlaudeMessage(input, KlaudeMessageType.USER)) + + klaude.chat(messages) { reply -> + if (!reply.isNullOrBlank()) { + messages.add(KlaudeMessage(reply.trim(), KlaudeMessageType.ASSISTANT)) + println("Assistant:\n${reply.trim()}") + } + } + } + println("DONE") +} + +``` + +## License +Klaude is an open-sourced software licensed under the [MIT License](https://github.com/paulotaylor/klaude/blob/master/LICENSE). +**This is an unofficial library, and is not affiliated with Anthropic**. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..074faef --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,182 @@ +import com.github.breadmoirai.githubreleaseplugin.GithubReleaseTask + +group = "com.klaude" +version = "0.0.1" + +plugins { + `java-library` + `maven-publish` + signing + id("io.codearte.nexus-staging") version "0.30.0" + kotlin("jvm") version "1.9.0" + kotlin("plugin.serialization") version "1.9.0" + id("org.jetbrains.dokka") version "1.8.10" // KDoc Documentation Builder + id("com.github.breadmoirai.github-release") version "2.4.1" +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("com.github.kittinunf.fuel:fuel:2.3.1") + implementation("com.github.kittinunf.fuel:fuel-coroutines:2.3.1") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:1.0-M1-1.4.0-rc") + implementation("com.google.code.gson:gson:2.10.1") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.1") + + testImplementation("io.github.cdimascio:dotenv-kotlin:6.4.1") + testImplementation("org.junit.jupiter:junit-jupiter:5.9.2") + testImplementation("org.jetbrains.kotlin:kotlin-serialization:1.7.20") + implementation(kotlin("stdlib-jdk8")) +} + +kotlin { + jvmToolchain { + languageVersion.set(JavaLanguageVersion.of(8)) + } + jvmToolchain(11) +} + +tasks.withType().all { + kotlinOptions { + jvmTarget = "1.8" + } +} + +tasks.test { + useJUnitPlatform() +} + +// Create javadocJar and sourcesJar tasks +val javadocJar by tasks.registering(Jar::class) { + archiveClassifier.set("javadoc") + from(tasks.named("javadoc")) +} + +val sourcesJar by tasks.registering(Jar::class) { + archiveClassifier.set("sources") + from(sourceSets.main.get().allSource) +} + +nexusStaging { + serverUrl = "https://s01.oss.sonatype.org/service/local/" + packageGroup = "com.kotlin" + stagingProfileId = findProperty("OSSRH_ID").toString() + username = findProperty("OSSRH_USERNAME").toString() + password = findProperty("OSSRH_PASSWORD").toString() + numberOfRetries = 30 + delayBetweenRetriesInMillis = 3000 +} + +// Signing artifacts +signing { + isRequired = true + //useGpgCmd() + + useInMemoryPgpKeys( + findProperty("SIGNING_KEY_ID").toString(), + findProperty("SIGNING_PRIVATE_KEY").toString(), + findProperty("SIGNING_PASSWORD").toString() + ) + //sign(configurations["archives"]) + sign(publishing.publications) +} + +publishing { + publications { + create("mavenJava") { + from(components["java"]) + + artifact(javadocJar) + artifact(sourcesJar) + + pom { + name.set("Klaude") + description.set("Kotlin Client for Claude") + url.set("https://github.com/paulotaylor/klaude") + + groupId = "com.klaude" + artifactId = "klaude" + + licenses { + license { + name.set("The MIT License") + url.set("https://opensource.org/licenses/MIT") + } + } + developers { + developer { + id.set("paulotaylor") + name.set("Paulo Taylor") + email.set("paulotaylor@gmail.com") + } + } + scm { + connection.set("scm:git:https://github.com/paulotaylor/klaude.git") + developerConnection.set("scm:git:ssh://github.com/paulotaylor/klaude.git") + url.set("https://github.com/paulotaylor/klaude") + } + } + } + } + + repositories { + maven { + url = uri("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2") + credentials { + username = findProperty("OSSRH_USERNAME").toString() + password = findProperty("OSSRH_PASSWORD").toString() + } + } + } +} + +// After publishing, the nexus plugin will automatically close and release +tasks.named("publish") { + finalizedBy("closeAndReleaseRepository", "createGithubRelease") +} + +tasks.register("createGithubRelease").configure { + // https://github.com/BreadMoirai/github-release-gradle-plugin + owner.set("Paulo Taylor") + repo.set("Kalude") + authorization.set("Token ${findProperty("GITHUB_TOKEN").toString()}") + tagName.set("$version") + targetCommitish.set("master") + releaseName.set("$version") + draft.set(false) + prerelease.set(false) + generateReleaseNotes.set(true) + body.set(""" +For Gradle projects, add this to your `build.gradle` file in the dependencies block: +```groovy +dependencies { + implementation 'com.klaude:klaude:$version' +} +``` +Or, if you are using Kotlin DSL (`build.gradle.kts`), add this to your dependencies block: +```kotlin +dependencies { + implementation("com.klaude:klaude:$version") +} +``` +For Maven projects, add this to your `pom.xml` file in the `` block: +```xml + + com.klaude + klaude + $version + +``` +See the [maven repository](https://central.sonatype.com/artifact/com.klaude/klaude/$version) for gradle/ant/etc. + """.trimIndent()) + overwrite.set(false) + allowUploadToExisting.set(false) + apiEndpoint.set("https://api.github.com") + + setReleaseAssets(/* empty */) + + // If set to true, you can debug that this would do + dryRun.set(false) +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..41d9927 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..aa991fc --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..2c77aee --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "Klaude" diff --git a/src/main/kotlin/com/klaude/KlaudeClient.kt b/src/main/kotlin/com/klaude/KlaudeClient.kt new file mode 100644 index 0000000..e7c902d --- /dev/null +++ b/src/main/kotlin/com/klaude/KlaudeClient.kt @@ -0,0 +1,125 @@ +package com.klaude + +import com.github.kittinunf.fuel.core.extensions.jsonBody +import com.github.kittinunf.fuel.httpPost +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import kotlinx.serialization.encodeToString + +class KlaudeClient private constructor(builder: Builder){ + + companion object { + const val TAG = "KlaudeClient" + } + + private var jsonBuilder = Json { + this.ignoreUnknownKeys = true + this.encodeDefaults = true + } + + private var apiKey: String? = null + private var model: String? = null + private var maxTokens: Int? = null + private var timeout = 0 + private var temperature = 0.5f + + init { + this.maxTokens = builder.maxTokens + this.model = builder.model + this.apiKey = builder.apiKey + this.timeout = builder.timeout + this.temperature = builder.temperature + } + + private fun check() { + if (apiKey.isNullOrBlank()) { + throw IllegalStateException("apiKey is null or blank") + } + if (model.isNullOrBlank()) { + throw IllegalStateException("model is null or blank") + } + if (maxTokens == null) { + throw IllegalStateException("maxTokens is null or blank") + } + } + + class Builder { + var apiKey: String? = null + private set + var model: String? = null + private set + var maxTokens : Int? = null + var timeout = 0 + var temperature = 0.5f + + fun key(key: String) = apply { this.apiKey = key } + fun model(model: String) = apply { this.model = model } + fun maxTokensToSample(maxTokensToSample: Int) = apply { this.maxTokens = maxTokensToSample } + fun timeout(timeout: Int) = apply { this.timeout = timeout } + fun build() = KlaudeClient(this) + } + + + fun chat(messages: List, listener: (String?) -> Unit) { + var prompt = "" + messages.forEach { message -> + if (message.text.isNotBlank()) { + if (message.type == KlaudeMessageType.USER) { + prompt += "\n\nHuman:${message.text}" + } + if (message.type == KlaudeMessageType.ASSISTANT) { + prompt += "\n\nAssistant:${message.text}" + } + } + } + if (prompt.isEmpty()) { + listener(null) + return + } + prompt += "\n\nAssistant:" + execute(prompt, listener) + } + fun complete(text: String, listener: (String?) -> Unit) { + execute("\n\nHuman:$text\n\nAssistant:", listener) + } + + fun execute(prompt: String, listener: (String?) -> Unit) { + try { + check() + val headers: MutableMap = HashMap() + headers["x-api-key"] = apiKey!! + val payload = KlaudePayload(prompt, model!!, maxTokens!!, listOf("\n\nHuman:"), temperature) + + val httpAsync = "https://api.anthropic.com/v1/complete".httpPost() + .jsonBody(Json.encodeToString(payload)) + httpAsync.header(headers) + httpAsync.timeoutRead(timeout) + httpAsync.timeout(timeout) + httpAsync.responseString { request, response, res -> + try { + val json = res.get() + val response = + jsonBuilder.decodeFromString(KlaudeResponse.serializer(), json) + listener(response.completion) + } catch (e: Exception) { + listener(null) + } + }.join() + } catch (e: Exception) { + listener(null) + } + } + +} + + +@Serializable +class KlaudeResponse(val completion: String) +@Serializable +class KlaudePayload(val prompt: String, val model: String, val max_tokens_to_sample: Int, val stop_sequences: List , val temperature :Float = 0.5f) + +class KlaudeMessage(val text: String, val type: KlaudeMessageType) + +enum class KlaudeMessageType { + USER, ASSISTANT +} diff --git a/src/test/kotlin/KotlinTest.kt b/src/test/kotlin/KotlinTest.kt new file mode 100644 index 0000000..ad32dcc --- /dev/null +++ b/src/test/kotlin/KotlinTest.kt @@ -0,0 +1,92 @@ +import com.klaude.KlaudeClient +import com.klaude.KlaudeMessage +import com.klaude.KlaudeMessageType +import io.github.cdimascio.dotenv.dotenv +import java.util.* + +// Colors for pretty formatting +const val RESET = "\u001b[0m" +const val BLACK = "\u001b[0;30m" +const val RED = "\u001b[0;31m" +const val GREEN = "\u001b[0;32m" +const val YELLOW = "\u001b[0;33m" +const val BLUE = "\u001b[0;34m" +const val PURPLE = "\u001b[0;35m" +const val CYAN = "\u001b[0;36m" +const val WHITE = "\u001b[0;37m" + +fun main() { + val scanner = Scanner(System.`in`) + + // Print out the menu of options + println(""" + ${GREEN}Please select one of the options below by typing a number. + 1. Completion + 2. Chat + """.trimIndent() + ) + + when (scanner.nextLine().trim()) { + "1" -> doCompletion() + "2" -> doChat() + else -> System.err.println("Invalid option") + } +} + +fun doCompletion() { + val scan = Scanner(System.`in`) + println(YELLOW + "Enter completion: ") + val input = scan.nextLine() + + val key = dotenv()["CLAUDE_KEY"] + + val klaude = KlaudeClient.Builder() + .model("claude-2") + .key(key) + .maxTokensToSample(500) + .build() + + klaude.complete(input) { + println(it) + } +} +fun doChat() { + val scan = Scanner(System.`in`) + + val key = dotenv()["CLAUDE_KEY"] + + val klaude = KlaudeClient.Builder() + .model("claude-2") + .key(key) + .maxTokensToSample(500) + .build() + + val messages = mutableListOf(KlaudeMessage("You are a helpful assistant", KlaudeMessageType.USER)) + + println(YELLOW + "Start chatting, type 'exit' or 'quit' to finish:\n") + + while (true) { + + println(GREEN + "Human:") + + val input = scan.nextLine().trim() + + if (input.isBlank()) { + continue + } + + if (input == "exit" || input == "quit") { + break + } + messages.add(KlaudeMessage(input, KlaudeMessageType.USER)) + + klaude.chat(messages) { reply -> + if (!reply.isNullOrBlank()) { + messages.add(KlaudeMessage(reply.trim(), KlaudeMessageType.ASSISTANT)) + println(BLUE + "Assistant:\n${reply.trim()}") + } + } + } + println(RED + "DONE") + +} \ No newline at end of file