├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── notes.txt ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── kousenit │ │ └── springaiexamples │ │ ├── SpringAIApplication.java │ │ ├── config │ │ └── AppConfig.java │ │ ├── functions │ │ ├── Calculator.java │ │ ├── ExchangeRateFunction.java │ │ └── Tools.java │ │ ├── helloworld │ │ └── SimpleAiController.java │ │ ├── images │ │ ├── ImageController.java │ │ └── ImageGenerator.java │ │ ├── json │ │ └── Completion.java │ │ ├── output │ │ ├── ActorController.java │ │ ├── ActorService.java │ │ ├── ActorsFilms.java │ │ └── PersonService.java │ │ ├── prompttemplate │ │ └── PromptTemplateController.java │ │ ├── rag │ │ └── TeslaManualService.java │ │ ├── role │ │ └── RoleController.java │ │ ├── services │ │ └── OpenAiService.java │ │ └── stuff │ │ └── StuffService.java └── resources │ ├── application.properties │ ├── data │ ├── bikes.json │ └── bikesVectorStore.json │ ├── docs │ └── wikipedia-curling.md │ ├── pdfs │ └── Model_3_Owners_Manual.pdf │ ├── prompts │ ├── joke-prompt.st │ ├── qa-prompt.st │ ├── quiz-prompt.st │ ├── system-message.st │ └── system-qa.st │ └── skynet.jpg └── test └── java └── com └── kousenit └── springaiexamples ├── SpringAIApplicationTest.java ├── chat └── OpenAIChatClientTest.java ├── functions ├── CalculatorTest.java ├── ExchangeRateFunctionTest.java └── LengthServiceTest.java ├── helloworld └── SimpleAiControllerTest.java ├── images └── ImageGeneratorTest.java ├── output ├── ActorControllerTest.java ├── ActorServiceTest.java ├── ActorsFilmsSerializeTest.java └── PersonServiceTest.java ├── rag └── TeslaManualServiceTest.java ├── services └── OpenAiServiceTest.java └── stuff └── StuffServiceTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | target/ 8 | 9 | ### STS ### 10 | .apt_generated 11 | .classpath 12 | .factorypath 13 | .project 14 | .settings 15 | .springBeans 16 | .sts4-cache 17 | bin/ 18 | !**/src/main/**/bin/ 19 | !**/src/test/**/bin/ 20 | 21 | ### IntelliJ IDEA ### 22 | .idea 23 | *.iws 24 | *.iml 25 | *.ipr 26 | out/ 27 | !**/src/main/**/out/ 28 | !**/src/test/**/out/ 29 | 30 | ### NetBeans ### 31 | /nbproject/private/ 32 | /nbbuild/ 33 | /dist/ 34 | /nbdist/ 35 | /.nb-gradle/ 36 | 37 | ### VS Code ### 38 | .vscode/ 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Ken Kousen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Spring AI Examples 2 | 3 | A set of examples for use with the Spring AI project, based on their original Azure workshop (but without Azure). 4 | 5 | ### Links 6 | 7 | * https://docs.spring.io/spring-ai/reference/index.html (Spring AI reference page) 8 | * https://github.com/spring-projects/spring-ai (Spring AI GitHub repository) 9 | * https://github.com/Azure-Samples/spring-ai-azure-workshop (Spring AI Azure workshop) 10 | * https://platform.openai.com/docs/overview (OpenAI documentation) 11 | * https://platform.openai.com/signup (OpenAI signup for key) 12 | * https://github.com/kousen/OpenAIClient (My GitHub repo) 13 | * https://github.com/kousen/springaiexamples (solutions to our exercises) 14 | * https://kenkousen.substack.com (_Tales from the jar side_ newsletter) 15 | * https://youtube.com/@talesfromthejarside (_Tales from the jar side_ YouTube channel) 16 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.4.5' 4 | id 'io.spring.dependency-management' version '1.1.7' 5 | } 6 | 7 | group = 'com.kousenit' 8 | version = '0.0.1-SNAPSHOT' 9 | 10 | java { 11 | toolchain { 12 | languageVersion = JavaLanguageVersion.of(17) 13 | } 14 | } 15 | 16 | repositories { 17 | mavenCentral() 18 | } 19 | 20 | ext { 21 | set('springAiVersion', "1.0.0-M8") 22 | } 23 | 24 | dependencies { 25 | implementation 'org.springframework.boot:spring-boot-starter-web' 26 | implementation 'org.springframework.ai:spring-ai-starter-model-openai' 27 | implementation 'org.springframework.ai:spring-ai-vector-store' 28 | implementation 'org.springframework.ai:spring-ai-advisors-vector-store' 29 | implementation 'org.springframework.ai:spring-ai-tika-document-reader' 30 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 31 | testRuntimeOnly 'org.junit.platform:junit-platform-launcher' 32 | } 33 | 34 | dependencyManagement { 35 | imports { 36 | mavenBom "org.springframework.ai:spring-ai-bom:${springAiVersion}" 37 | } 38 | } 39 | 40 | tasks.named('test', Test) { 41 | useJUnitPlatform() 42 | jvmArgs += ['-Xshare:off'] 43 | } 44 | 45 | tasks.withType(JavaExec).configureEach { 46 | jvmArgs += ['-Xshare:off'] 47 | } 48 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kousen/springaiexamples/4db721bd028b1cdadc568f038325aaf0d5893a55/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-all.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /notes.txt: -------------------------------------------------------------------------------- 1 | Topics: 2 | - Models 3 | - Chat 4 | - Synchronous vs Streaming 5 | - Messages 6 | - Prompts and Prompt Templates 7 | - Structured Outputs 8 | - Advisors 9 | - Chat memory 10 | - Function calling / Tool support 11 | - MCP 12 | - Image generation 13 | - Multimodal 14 | - Vision 15 | - Audio 16 | - Your own data 17 | - Prompt stuffing 18 | - RAG 19 | - Vector databases -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'springaiexamples' 2 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/SpringAIApplication.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringAIApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringAIApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/config/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.config; 2 | 3 | import org.springframework.ai.document.Document; 4 | import org.springframework.ai.embedding.EmbeddingModel; 5 | import org.springframework.ai.reader.tika.TikaDocumentReader; 6 | import org.springframework.ai.transformer.splitter.TextSplitter; 7 | import org.springframework.ai.transformer.splitter.TokenTextSplitter; 8 | import org.springframework.ai.vectorstore.SimpleVectorStore; 9 | import org.springframework.ai.vectorstore.VectorStore; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.boot.ApplicationRunner; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | import org.springframework.context.annotation.Profile; 15 | import org.springframework.core.io.Resource; 16 | import org.springframework.http.client.JdkClientHttpRequestFactory; 17 | import org.springframework.web.client.RestClient; 18 | 19 | import java.util.List; 20 | 21 | @Configuration 22 | public class AppConfig { 23 | @Value("classpath:/pdfs/Model_3_Owners_Manual.pdf") 24 | Resource documentResource; 25 | 26 | // Enable this bean to load the documents from the PDF file 27 | @Bean @Profile("rag") 28 | ApplicationRunner go(VectorStore vectorStore) { 29 | return args -> { 30 | System.out.println("Loading documents from PDF file into " + 31 | vectorStore.getClass().getSimpleName()); 32 | TikaDocumentReader reader = new TikaDocumentReader(documentResource); 33 | List documents = reader.get(); 34 | TextSplitter textSplitter = new TokenTextSplitter(); 35 | List splitDocuments = textSplitter.apply(documents); 36 | System.out.println("Adding " + splitDocuments.size() + " documents to vector store"); 37 | vectorStore.add(splitDocuments); 38 | }; 39 | } 40 | 41 | @Bean 42 | VectorStore vectorStore(EmbeddingModel embeddingModel) { 43 | // var embeddingModel = new OpenAiEmbeddingModel( 44 | // OpenAiApi.builder() 45 | // .apiKey(System.getenv("OPENAI_API_KEY")) 46 | // .build()); 47 | return SimpleVectorStore.builder(embeddingModel).build(); 48 | } 49 | 50 | @Bean 51 | RestClient.Builder restClientBuilder() { 52 | var factory = new JdkClientHttpRequestFactory(); 53 | factory.setReadTimeout(30000); // 30 seconds for image generation 54 | return RestClient.builder().requestFactory(factory); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/functions/Calculator.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.functions; 2 | 3 | import org.springframework.ai.chat.client.ChatClient; 4 | import org.springframework.ai.chat.model.ChatModel; 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.util.Arrays; 9 | 10 | @Service 11 | public class Calculator { 12 | 13 | private final ChatClient chatClient; 14 | 15 | public Calculator(@Qualifier("openAiChatModel") ChatModel chatModel) { 16 | this.chatClient = ChatClient.create(chatModel); 17 | } 18 | 19 | public String calculateLength(String expression) { 20 | String message = """ 21 | Calculate the length of this expression: 22 | "%s" 23 | """.formatted(expression); 24 | return chatClient.prompt() 25 | .tools(new Tools()) 26 | .user(message) 27 | .call() 28 | .content(); 29 | } 30 | 31 | public String calculateSum(int... ints) { 32 | String message = """ 33 | Calculate the sum of these integers: 34 | %s 35 | """.formatted(Arrays.toString(ints)); 36 | return chatClient.prompt() 37 | .tools(new Tools()) 38 | .user(message) 39 | .call() 40 | .content(); 41 | } 42 | 43 | public String calculateSqrt(double value) { 44 | String message = """ 45 | Calculate the square root of this number: 46 | %s 47 | """.formatted(value); 48 | return chatClient.prompt() 49 | .tools(new Tools()) 50 | .user(message) 51 | .call() 52 | .content(); 53 | } 54 | 55 | public String sqrtSumLengths(String sentence) { 56 | String message = """ 57 | Calculate the square root of the sum 58 | of the lengths of the words in this sentence: 59 | "%s" 60 | """.formatted(sentence); 61 | return chatClient.prompt() 62 | .tools(new Tools()) 63 | .user(message) 64 | .call() 65 | .content(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/functions/ExchangeRateFunction.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.functions; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.context.annotation.Description; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.stereotype.Component; 8 | import org.springframework.web.client.RestClient; 9 | import org.springframework.http.HttpHeaders; 10 | 11 | import java.util.Map; 12 | import java.util.function.Function; 13 | 14 | @Component 15 | @Description("Get the exchange rate between two currencies") 16 | public class ExchangeRateFunction implements 17 | Function { 18 | 19 | public record Request(double fromAmount, String from, String to) {} 20 | public record Response(double toAmount) {} 21 | 22 | private final Map rates; 23 | private final Logger logger = LoggerFactory.getLogger(ExchangeRateFunction.class); 24 | 25 | public ExchangeRateFunction() { 26 | this.rates = getLatestRates().rates(); 27 | } 28 | 29 | @Override 30 | public Response apply(Request request) { 31 | logger.info("Converting {} rate from {} to {}", request.fromAmount, request.from, request.to); 32 | return new Response( request.fromAmount * 33 | rates.get(request.to) / rates.get(request.from)); 34 | } 35 | 36 | public record OpenExchangeRatesResponse( 37 | String disclaimer, 38 | String license, 39 | long timestamp, 40 | String base, 41 | Map rates 42 | ) {} 43 | 44 | // Retrieve the current exchange rates 45 | private OpenExchangeRatesResponse getLatestRates() { 46 | RestClient restClient = RestClient.builder() 47 | .baseUrl("https://openexchangerates.org") 48 | .defaultHeader(HttpHeaders.AUTHORIZATION, 49 | "Token %s".formatted( 50 | System.getenv("OPENEXCHANGERATES_API_KEY"))) 51 | .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) 52 | .build(); 53 | 54 | return restClient.get() 55 | .uri("/api/latest.json") 56 | .retrieve() 57 | .body(OpenExchangeRatesResponse.class); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/functions/Tools.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.functions; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.ai.tool.annotation.Tool; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | public class Tools { 10 | private final Logger logger = LoggerFactory.getLogger(Tools.class); 11 | 12 | @Tool(description = "Get the length of a string") 13 | public int stringLength(String expression) { 14 | logger.info("Calculating length of expression: {}", expression); 15 | return expression.length(); 16 | } 17 | 18 | @Tool(description = "Sum a series of integers") 19 | public int sumIntegers(int... ints) { 20 | logger.info("Calculating sum of integers: {}", ints); 21 | return java.util.stream.IntStream.of(ints).sum(); 22 | } 23 | 24 | @Tool(description = "Take the square root of a number") 25 | public double sqrt(double value) { 26 | logger.info("Calculating square root of {}", value); 27 | return Math.sqrt(value); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/helloworld/SimpleAiController.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.helloworld; 2 | 3 | import org.springframework.ai.chat.client.ChatClient; 4 | import org.springframework.ai.chat.model.ChatModel; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Qualifier; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestParam; 9 | import org.springframework.web.bind.annotation.RestController; 10 | import reactor.core.publisher.Flux; 11 | 12 | @RestController 13 | public class SimpleAiController { 14 | 15 | private final ChatClient chatClient; 16 | 17 | @Autowired 18 | public SimpleAiController(@Qualifier("openAiChatModel") ChatModel chatModel) { 19 | this.chatClient = ChatClient.builder(chatModel).build(); 20 | } 21 | 22 | @GetMapping("/ai/generate") 23 | public String generate( 24 | @RequestParam(value = "message", defaultValue = "Tell me a joke") String message) { 25 | return chatClient.prompt() 26 | .user(message) 27 | .call() 28 | .content(); 29 | } 30 | 31 | @GetMapping("/ai/generateStream") 32 | public Flux generateStream( 33 | @RequestParam(value = "message", defaultValue = "Tell me a joke") String message) { 34 | return chatClient.prompt() 35 | .user(message) 36 | .stream() 37 | .content(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/images/ImageController.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.images; 2 | 3 | import org.springframework.ai.image.ImageResponse; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.web.bind.annotation.PostMapping; 6 | import org.springframework.web.bind.annotation.RequestBody; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | public class ImageController { 11 | private final ImageGenerator imageGenerator; 12 | 13 | @Autowired 14 | public ImageController(ImageGenerator imageGenerator) { 15 | this.imageGenerator = imageGenerator; 16 | } 17 | 18 | @PostMapping("/image") 19 | public ImageResponse generateImage(@RequestBody String prompt) { 20 | return imageGenerator.generate(prompt); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/images/ImageGenerator.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.images; 2 | 3 | 4 | import org.springframework.ai.image.ImagePrompt; 5 | import org.springframework.ai.image.ImageResponse; 6 | import org.springframework.ai.openai.OpenAiImageModel; 7 | import org.springframework.ai.openai.OpenAiImageOptions; 8 | import org.springframework.stereotype.Service; 9 | 10 | @Service 11 | public class ImageGenerator { 12 | private final OpenAiImageModel imageModel; 13 | 14 | public ImageGenerator(OpenAiImageModel imageModel) { 15 | this.imageModel = imageModel; 16 | } 17 | 18 | public ImageResponse generate(String prompt) { 19 | var options = OpenAiImageOptions.builder() 20 | .withQuality("hd") 21 | .withHeight(1024) 22 | .withWidth(1024) 23 | .build(); 24 | 25 | var imagePrompt = new ImagePrompt(prompt, options); 26 | return imageModel.call(imagePrompt); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/json/Completion.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.json; 2 | 3 | public record Completion(String completion) { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/output/ActorController.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.output; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestParam; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | import java.util.List; 8 | 9 | @RestController 10 | public class ActorController { 11 | private final ActorService service; 12 | 13 | public ActorController(ActorService service) { 14 | this.service = service; 15 | } 16 | 17 | @GetMapping("/actor") 18 | List getActorFilms( 19 | @RequestParam(value = "actor", defaultValue = "Margot Robbie") String actor) { 20 | return service.getActorFilms(actor).movies(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/output/ActorService.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.output; 2 | 3 | import org.springframework.ai.chat.client.ChatClient; 4 | import org.springframework.ai.chat.model.ChatModel; 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.stereotype.Service; 7 | 8 | @Service 9 | public class ActorService { 10 | 11 | private final ChatClient chatClient; 12 | 13 | public ActorService(@Qualifier("openAiChatModel") ChatModel chatModel) { 14 | this.chatClient = ChatClient.builder(chatModel).build(); 15 | } 16 | 17 | public ActorsFilms getActorFilms(String actor) { 18 | String template = """ 19 | Generate the filmography for the actor {actor}. 20 | """; 21 | 22 | ActorsFilms actorsFilms = chatClient.prompt() 23 | .user(userSpec -> userSpec 24 | .text(template) 25 | .param("actor", actor)) 26 | .call() 27 | .entity(ActorsFilms.class); 28 | System.out.println("Films for " + actor + ":"); 29 | assert actorsFilms != null; 30 | actorsFilms.movies().forEach(System.out::println); 31 | return actorsFilms; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/output/ActorsFilms.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.output; 2 | 3 | import java.util.List; 4 | 5 | public record ActorsFilms(String actor, List movies) {} 6 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/output/PersonService.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.output; 2 | 3 | import org.springframework.ai.chat.model.ChatModel; 4 | import org.springframework.ai.chat.prompt.PromptTemplate; 5 | import org.springframework.ai.converter.BeanOutputConverter; 6 | import org.springframework.beans.factory.annotation.Qualifier; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.time.LocalDate; 10 | import java.util.Map; 11 | 12 | @Service 13 | public class PersonService { 14 | 15 | public record Person(String firstName, String lastName, LocalDate dob) {} 16 | 17 | private final ChatModel chatModel; 18 | 19 | public PersonService(@Qualifier("openAiChatModel") ChatModel chatModel) { 20 | this.chatModel = chatModel; 21 | } 22 | 23 | public Person retrievePerson(String text) { 24 | var parser = new BeanOutputConverter<>(Person.class); 25 | 26 | String template = """ 27 | Extract a Person instance from the given {text} using the {format} 28 | Use ISO-8601 standard date format for the date of birth. 29 | Do NOT include the JSON delimiters ```json or ``` in the response. 30 | """; 31 | 32 | PromptTemplate promptTemplate = new PromptTemplate(template, 33 | Map.of("text", text, "format", parser.getFormat())); 34 | String content = chatModel.call(promptTemplate.create()) 35 | .getResult().getOutput().getText(); 36 | System.out.println(content); 37 | return parser.convert(content); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/prompttemplate/PromptTemplateController.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.prompttemplate; 2 | 3 | import org.springframework.ai.chat.client.ChatClient; 4 | import org.springframework.ai.chat.model.ChatModel; 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.core.io.Resource; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RequestParam; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | @RestController 13 | public class PromptTemplateController { 14 | 15 | private final ChatClient chatClient; 16 | 17 | @Value("classpath:/prompts/joke-prompt.st") 18 | private Resource jokeResource; 19 | 20 | public PromptTemplateController(@Qualifier("openAiChatModel") ChatModel chatModel) { 21 | chatClient = ChatClient.create(chatModel); 22 | } 23 | 24 | @GetMapping("/ai/prompt") 25 | public String completion( 26 | @RequestParam(defaultValue = "funny") String adjective, 27 | @RequestParam(defaultValue = "cows") String topic) { 28 | 29 | return chatClient.prompt() 30 | .user(userSpec -> userSpec 31 | .text(jokeResource) 32 | .param("adjective", adjective) 33 | .param("topic", topic)) 34 | .call() 35 | .content(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/rag/TeslaManualService.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.rag; 2 | 3 | import org.springframework.ai.chat.client.ChatClient; 4 | import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor; 5 | import org.springframework.ai.chat.model.ChatModel; 6 | import org.springframework.ai.vectorstore.VectorStore; 7 | import org.springframework.context.annotation.Profile; 8 | import org.springframework.stereotype.Service; 9 | 10 | @Service 11 | @Profile("rag") 12 | public class TeslaManualService { 13 | private final ChatClient chatClient; 14 | 15 | public TeslaManualService(ChatModel model, VectorStore vectorStore) { 16 | chatClient = ChatClient.builder(model) 17 | .defaultAdvisors(new QuestionAnswerAdvisor(vectorStore)) 18 | .build(); 19 | } 20 | 21 | public String ask(String question) { 22 | return chatClient.prompt() 23 | .user(question) 24 | .call() 25 | .content(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/role/RoleController.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.role; 2 | 3 | import org.springframework.ai.chat.client.ChatClient; 4 | import org.springframework.ai.chat.model.ChatModel; 5 | import org.springframework.ai.chat.model.Generation; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Qualifier; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.core.io.Resource; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.RequestParam; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import java.util.List; 15 | 16 | @RestController 17 | public class RoleController { 18 | 19 | private final ChatClient chatClient; 20 | 21 | @Value("classpath:/prompts/system-message.st") 22 | private Resource systemResource; 23 | 24 | @Autowired 25 | public RoleController(@Qualifier("openAiChatModel") ChatModel chatModel) { 26 | this.chatClient = ChatClient.create(chatModel); 27 | } 28 | 29 | @GetMapping("/ai/roles") 30 | public List generate( 31 | @RequestParam(value = "message", defaultValue = """ 32 | Tell me about three famous pirates from the 33 | Golden Age of Piracy and why they did. Write 34 | at least a sentence for each pirate.""") String message, 35 | @RequestParam(value = "name", defaultValue = "Bob") String name, 36 | @RequestParam(value = "voice", defaultValue = "pirate") String voice) { 37 | 38 | return chatClient.prompt() 39 | .system(systemSpec -> systemSpec 40 | .text(systemResource) 41 | .param("name", name) 42 | .param("voice", voice)) 43 | .user(message) 44 | .call() 45 | .chatResponse().getResults(); 46 | } 47 | } -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/services/OpenAiService.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.services; 2 | 3 | import com.kousenit.springaiexamples.output.ActorsFilms; 4 | import org.springframework.ai.chat.client.ChatClient; 5 | import org.springframework.ai.openai.OpenAiChatModel; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.core.ParameterizedTypeReference; 9 | import org.springframework.core.io.Resource; 10 | import org.springframework.stereotype.Service; 11 | import reactor.core.publisher.Flux; 12 | 13 | import java.util.List; 14 | 15 | @Service 16 | public class OpenAiService { 17 | private final ChatClient chatClient; 18 | 19 | @Value("classpath:/prompts/system-message.st") 20 | private Resource systemResource; 21 | 22 | @Autowired 23 | public OpenAiService(OpenAiChatModel chatModel) { 24 | this.chatClient = ChatClient.builder(chatModel) 25 | // Add chat memory: 26 | // .defaultAdvisors(new PromptChatMemoryAdvisor(new InMemoryChatMemory())) 27 | .build(); 28 | } 29 | 30 | public ActorsFilms getActorsFilms(String actor) { 31 | return chatClient.prompt() 32 | .user(userSpec -> userSpec 33 | .text("Generate the filmography for {actor}.") 34 | .param("actor", actor)) 35 | .call() 36 | .entity(ActorsFilms.class); 37 | } 38 | 39 | public List getFilmsForActor(String actor) { 40 | return chatClient.prompt() 41 | .user("Generate the filmography for " + actor) 42 | .call() 43 | .entity(new ParameterizedTypeReference<>() {}); 44 | } 45 | 46 | public String chatWithPromptTemplate(String typeOfJoke, String topic) { 47 | return chatClient.prompt() 48 | .user(userSpec -> userSpec 49 | .text("Tell me a {adjective} joke about {topic}") 50 | .param("adjective", typeOfJoke) 51 | .param("topic", topic)) 52 | .call() 53 | .content(); 54 | } 55 | 56 | 57 | public String chat(String message) { 58 | return chatClient.prompt() 59 | .system(systemSpec -> systemSpec.text(systemResource) 60 | .param("name", "Bob") 61 | .param("voice", "pirate")) 62 | .user(message) 63 | .call() 64 | .content(); 65 | } 66 | 67 | // Can't do "entity" for async, so this is more of a demo 68 | public Flux getActorFilmsListAsync(String... actors) { 69 | String allActors = String.join(", ", actors); 70 | return chatClient.prompt() 71 | .user("Generate the filmography for " + allActors) 72 | .stream() 73 | .content(); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/kousenit/springaiexamples/stuff/StuffService.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.stuff; 2 | 3 | import org.springframework.ai.chat.client.ChatClient; 4 | import org.springframework.ai.openai.OpenAiChatModel; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.core.io.Resource; 7 | import org.springframework.stereotype.Service; 8 | 9 | // Stuff the prompt with Markdown document from Wikipedia 10 | @Service 11 | public class StuffService { 12 | 13 | @Value("classpath:docs/wikipedia-curling.md") 14 | private Resource curlingResource; 15 | 16 | private final ChatClient chatClient; 17 | 18 | public StuffService(OpenAiChatModel chatModel) { 19 | this.chatClient = ChatClient.builder(chatModel).build(); 20 | } 21 | 22 | public String askQuestion(String question) { 23 | return chatClient.prompt() 24 | .system(curlingResource) 25 | .user(question) 26 | .call() 27 | .content(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #logging.level.web=debug 2 | spring.ai.openai.chat.api-key=${OPENAI_API_KEY} 3 | spring.ai.openai.chat.options.model=gpt-4.1 4 | spring.ai.openai.embedding.options.model=text-embedding-3-small 5 | 6 | # Let's access Google's Gemini through OpenAI's API 7 | #spring.ai.openai.chat.api-key=${GOOGLEAI_API_KEY} 8 | #spring.ai.openai.chat.options.model=gemini-1.5-flash 9 | #spring.ai.openai.chat.base-url=https://generativelanguage.googleapis.com 10 | #spring.ai.openai.chat.completions-path=/v1beta/openai/chat/completions 11 | 12 | # Use the OpenAI model to access DeepSeek R1 13 | #spring.ai.openai.chat.api-key=${DEEPSEEK_API_KEY} 14 | #spring.ai.openai.chat.options.model=deepseek-chat 15 | #spring.ai.openai.chat.base-url=https://api.deepseek.com 16 | #spring.ai.openai.chat.completions-path=/chat/completions 17 | 18 | #logging.level.org.springframework.ai.chat.client.advisor=DEBUG -------------------------------------------------------------------------------- /src/main/resources/docs/wikipedia-curling.md: -------------------------------------------------------------------------------- 1 | The [curling](Curling_at_the_Winter_Olympics "wikilink") competitions of 2 | the [2022 Winter Olympics](2022_Winter_Olympics "wikilink") were held at 3 | the [Beijing National Aquatics 4 | Centre](Beijing_National_Aquatics_Centre "wikilink"), one of the 5 | [Olympic Green](Olympic_Green "wikilink") venues. Curling competitions 6 | were scheduled for every day of the games, from February 2 to February 7 | 20.\[1\] This was the eighth time that [curling](curling "wikilink") was 8 | part of the Olympic program. 9 | 10 | In each of the men's, women's, and [mixed 11 | doubles](mixed_doubles_curling "wikilink") competitions, 10 nations 12 | competed. The mixed doubles competition was expanded for its second 13 | appearance in the Olympics.\[2\] A total of 120 quota spots (60 per sex) 14 | were distributed to the sport of curling, an increase of four from the 15 | [2018 Winter Olympics](2018_Winter_Olympics "wikilink").\[3\] A total of 16 | 3 events were contested, one for men, one for women, and one mixed.\[4\] 17 | 18 | ## Qualification 19 | 20 | Qualification to the Men's and Women's curling tournaments at the Winter 21 | Olympics was determined through two methods (in addition to the host 22 | nation). Nations qualified teams by placing in the top six at the 2021 23 | [World Curling Championships](World_Curling_Championships "wikilink"). 24 | Teams could also qualify through Olympic qualification events which were 25 | held in 2021. Six nations qualified via World Championship qualification 26 | placement, while three nations qualified through qualification events. 27 | In men's and women's play, a host will be selected for the Olympic 28 | Qualification Event (OQE). They would be joined by the teams which 29 | competed at the 2021 World Championships but did not qualify for the 30 | Olympics, and two qualifiers from the Pre-Olympic Qualification Event 31 | (Pre-OQE). The Pre-OQE was open to all member associations.\[5\] 32 | 33 | For the mixed doubles competition in 2022, the tournament field was 34 | expanded from eight competitor nations to ten.\[6\] The top seven ranked 35 | teams at the [2021 World Mixed Doubles Curling 36 | Championship](2021_World_Mixed_Doubles_Curling_Championship "wikilink") 37 | qualified, along with two teams from the Olympic Qualification Event 38 | (OQE) – Mixed Doubles. This OQE was open to a nominated host and the 39 | fifteen nations with the highest qualification points not already 40 | qualified to the Olympics. As the host nation, China qualified teams 41 | automatically, thus making a total of ten teams per event in the curling 42 | tournaments.\[7\] 43 | 44 | - Summary 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 |

Nations

Men

Women

Mixed doubles

Athletes

2

12

12

2

10

10

6

5

6

10

5

11

12

11

Total: 14 NOCs

10

10

10

114

164 | 165 | ## Competition schedule 166 | 167 | ![The [Beijing National Aquatics 168 | Centre](Beijing_National_Aquatics_Centre "wikilink") served as the venue 169 | of the curling competitions.](Water_Cube_Ice_Cube_Beijing_2.jpg 170 | "The Beijing National Aquatics Centre served as the venue of the curling competitions.") 171 | Curling competitions started two days before the [Opening 172 | Ceremony](2022_Winter_Olympics_opening_ceremony "wikilink") and finished 173 | on the last day of the games, meaning the sport was the only one to have 174 | had a competition every day of the games. The following was the 175 | competition schedule for the curling competitions: 176 | 177 | | | | | | | | | | 178 | | :-: | ----------- | :-: | ---------- | :-: | ------------------ | :-: | ----- | 179 | | RR | Round robin | SF | Semifinals | B | 3rd place play-off | F | Final | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 |

Wed 2

Thu 3

Fri 4

Sat 5

Sun 6

Mon 7

Tue 8

Wed 9

Thu 10

Fri 11

Sat 12

Sun 13

Mon 14

Tue 15

Wed 16

Thu 17

Fri 18

Sat 19

Sun 20

Men's tournament

RR

RR

RR

RR

RR

RR

RR

RR

RR

SF

B

F

Women's tournament

RR

RR

RR

RR

RR

RR

RR

RR

SF

B

F

Mixed doubles

RR

RR

RR

RR

RR

RR

SF

B

F

275 | 276 | ## Medal summary 277 | 278 | ### Medal table 279 | 280 | ### Medalists 281 | 282 | |- |Men 283 | | 284 | [Niklas Edin](Niklas_Edin "wikilink") 285 | [Oskar Eriksson](Oskar_Eriksson "wikilink") 286 | [Rasmus Wranå](Rasmus_Wranå "wikilink") 287 | [Christoffer Sundgren](Christoffer_Sundgren "wikilink") 288 | [Daniel Magnusson](Daniel_Magnusson_\(curler\) "wikilink") | 289 | [Bruce Mouat](Bruce_Mouat "wikilink") 290 | [Grant Hardie](Grant_Hardie "wikilink") 291 | [Bobby Lammie](Bobby_Lammie "wikilink") 292 | [Hammy McMillan Jr.](Hammy_McMillan_Jr. "wikilink") 293 | [Ross Whyte](Ross_Whyte "wikilink") | 294 | [Brad Gushue](Brad_Gushue "wikilink") 295 | [Mark Nichols](Mark_Nichols_\(curler\) "wikilink") 296 | [Brett Gallant](Brett_Gallant "wikilink") 297 | [Geoff Walker](Geoff_Walker_\(curler\) "wikilink") 298 | [Marc Kennedy](Marc_Kennedy "wikilink") |- |Women 299 | | 300 | [Eve Muirhead](Eve_Muirhead "wikilink") 301 | [Vicky Wright](Vicky_Wright "wikilink") 302 | [Jennifer Dodds](Jennifer_Dodds "wikilink") 303 | [Hailey Duff](Hailey_Duff "wikilink") 304 | [Mili Smith](Mili_Smith "wikilink") | 305 | [Satsuki Fujisawa](Satsuki_Fujisawa "wikilink") 306 | [Chinami Yoshida](Chinami_Yoshida "wikilink") 307 | [Yumi Suzuki](Yumi_Suzuki "wikilink") 308 | [Yurika Yoshida](Yurika_Yoshida "wikilink") 309 | [Kotomi Ishizaki](Kotomi_Ishizaki "wikilink") | 310 | [Anna Hasselborg](Anna_Hasselborg "wikilink") 311 | [Sara McManus](Sara_McManus "wikilink") 312 | [Agnes Knochenhauer](Agnes_Knochenhauer "wikilink") 313 | [Sofia Mabergs](Sofia_Mabergs "wikilink") 314 | [Johanna Heldin](Johanna_Heldin "wikilink") |- |Mixed doubles 315 | | 316 | [Stefania Constantini](Stefania_Constantini "wikilink") 317 | [Amos Mosaner](Amos_Mosaner "wikilink") | 318 | [Kristin Skaslien](Kristin_Skaslien "wikilink") 319 | [Magnus Nedregotten](Magnus_Nedregotten "wikilink") | 320 | [Almida de Val](Almida_de_Val "wikilink") 321 | [Oskar Eriksson](Oskar_Eriksson "wikilink") |} 322 | 323 | ## Teams 324 | 325 | ### Men 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 344 | 349 | 354 | 359 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 378 | 383 | 388 | 393 | 398 | 399 | 400 |

Skip: Brad Gushue
340 | Third: Mark Nichols
341 | Second: Brett Gallant
342 | Lead: Geoff Walker
343 | Alternate: Marc Kennedy

Skip: Ma Xiuyue
345 | Third: Zou Qiang
346 | Second: Wang Zhiyu
347 | Lead: Xu Jingtao
348 | Alternate: Jiang Dongxu

Skip: Mikkel Krause
350 | Third: Mads Nørgård
351 | Second: Henrik Holtermann
352 | Lead: Kasper Wiksten
353 | Alternate: Tobias Thune

Skip: Bruce Mouat
355 | Third: Grant Hardie
356 | Second: Bobby Lammie
357 | Lead: Hammy McMillan Jr.
358 | Alternate: Ross Whyte

Skip: Joël Retornaz
360 | Third: Amos Mosaner
361 | Second: Sebastiano Arman
362 | Lead: Simone Gonin
363 | Alternate: Mattia Giovanella

Skip: Steffen Walstad
374 | Third: Torger Nergård
375 | Second: Markus Høiberg
376 | Lead: Magnus Vågberg
377 | Alternate: Magnus Nedregotten

Skip: Sergey Glukhov
379 | Third: Evgeny Klimov
380 | Second: Dmitry Mironov
381 | Lead: Anton Kalalb
382 | Alternate: Daniil Goriachev

Skip: Niklas Edin
384 | Third: Oskar Eriksson
385 | Second: Rasmus Wranå
386 | Lead: Christoffer Sundgren
387 | Alternate:

Fourth: Benoît Schwarz
389 | Third: Sven Michel
390 | Skip: Peter de Cruz
391 | Lead: Valentin Tanner
392 | Alternate: Pablo Lachat

Skip: John Shuster
394 | Third: Chris Plys
395 | Second: Matt Hamilton
396 | Lead: John Landsteiner
397 | Alternate: Colin Hufman

401 | 402 | ### Women 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 421 | 426 | 431 | 436 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 455 | 460 | 465 | 470 | 475 | 476 | 477 |

Skip: Jennifer Jones
417 | Third: Kaitlyn Lawes
418 | Second: Jocelyn Peterman
419 | Lead: Dawn McEwen
420 | Alternate: Lisa Weagle

Skip: Han Yu
422 | Third: Wang Rui
423 | Second: Dong Ziqi
424 | Lead: Zhang Lijun
425 | Alternate: Jiang Xindi

Skip: Madeleine Dupont
427 | Third: Mathilde Halse
428 | Second: Denise Dupont
429 | Lead: My Larsen
430 | Alternate: Jasmin Lander

Skip: Eve Muirhead
432 | Third: Vicky Wright
433 | Second: Jennifer Dodds
434 | Lead: Hailey Duff
435 | Alternate: Mili Smith

Skip: Satsuki Fujisawa
437 | Third: Chinami Yoshida
438 | Second: Yumi Suzuki
439 | Lead: Yurika Yoshida
440 | Alternate: Kotomi Ishizaki

Skip: Alina Kovaleva
451 | Third: Yulia Portunova
452 | Second: Galina Arsenkina
453 | Lead: Ekaterina Kuzmina
454 | Alternate: Maria Komarova

Skip: Kim Eun-jung
456 | Third: Kim Kyeong-ae
457 | Second: Kim Cho-hi
458 | Lead: Kim Seon-yeong
459 | Alternate: Kim Yeong-mi

Skip: Anna Hasselborg
461 | Third: Sara McManus
462 | Second: Agnes Knochenhauer
463 | Lead: Sofia Mabergs
464 | Alternate: Johanna Heldin

Fourth: Alina Pätz
466 | Skip: Silvana Tirinzoni
467 | Second: Esther Neuenschwander
468 | Lead: Melanie Barbezat
469 | Alternate: Carole Howald

Skip: Tabitha Peterson
471 | Third: Nina Roth
472 | Second: Becca Hamilton
473 | Lead: Tara Peterson
474 | Alternate: Aileen Geving

478 | 479 | ### Mixed doubles 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 495 | 497 | 499 | 501 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 514 | 516 | 518 | 520 | 522 | 523 | 524 |

Female: Tahli Gill
494 | Male: Dean Hewitt

Female: Rachel Homan
496 | Male: John Morris

Female: Fan Suyuan
498 | Male: Ling Zhi

Female: Zuzana Paulová
500 | Male: Tomáš Paul

Female: Jennifer Dodds
502 | Male: Bruce Mouat

Female: Stefania Constantini
513 | Male: Amos Mosaner

Female: Kristin Skaslien
515 | Male: Magnus Nedregotten

Female: Almida de Val
517 | Male: Oskar Eriksson

Female: Jenny Perret
519 | Male: Martin Rios

Female: Vicky Persinger
521 | Male: Chris Plys

525 | 526 | ## Results summary 527 | 528 | ### Men's tournament 529 | 530 | #### Round robin 531 | 532 | - Standings 533 | 534 | {{\#lst:Curling at the 2022 Winter Olympics – Men's 535 | tournament|Standings}} 536 | 537 | - Results 538 | 539 | {{\#lst:Curling at the 2022 Winter Olympics – Men's tournament|Results}} 540 | 541 | #### Playoffs 542 | 543 | ##### Semifinals 544 | 545 | *Thursday, 17 February, 20:05* {{\#lst:Curling at the 2022 Winter 546 | Olympics – Men's tournament|SF1}} {{\#lst:Curling at the 2022 Winter 547 | Olympics – Men's tournament|SF2}} 548 | 549 | ##### Bronze medal game 550 | 551 | *Friday, 18 February, 14:05* {{\#lst:Curling at the 2022 Winter Olympics 552 | – Men's tournament|BM}} 553 | 554 | ##### Gold medal game 555 | 556 | *Saturday, 19 February, 14:50*\[8\] {{\#lst:Curling at the 2022 Winter 557 | Olympics – Men's tournament|GM}} 558 | 559 | ### Women's tournament 560 | 561 | #### Round robin 562 | 563 | - Standings 564 | 565 | {{\#lst:Curling at the 2022 Winter Olympics – Women's 566 | tournament|Standings}} 567 | 568 | - Results 569 | 570 | {{\#lst:Curling at the 2022 Winter Olympics – Women's 571 | tournament|Results}} 572 | 573 | #### Playoffs 574 | 575 | ##### Semifinals 576 | 577 | *Friday, 18 February, 20:05* {{\#lst:Curling at the 2022 Winter Olympics 578 | – Women's tournament|SF1}} {{\#lst:Curling at the 2022 Winter Olympics 579 | – Women's tournament|SF2}} 580 | 581 | ##### Bronze medal game 582 | 583 | *Saturday, 19 February, 20:05* {{\#lst:Curling at the 2022 Winter 584 | Olympics – Women's tournament|BM}} 585 | 586 | ##### Gold medal game 587 | 588 | *Sunday, 20 February, 9:05* {{\#lst:Curling at the 2022 Winter Olympics 589 | – Women's tournament|GM}} 590 | 591 | ### Mixed doubles tournament 592 | 593 | #### Round robin 594 | 595 | - Standings 596 | 597 | {{\#lst:Curling at the 2022 Winter Olympics – Mixed doubles 598 | tournament|Standings}} 599 | 600 | - Results 601 | 602 | {{\#lst:Curling at the 2022 Winter Olympics – Mixed doubles 603 | tournament|Results}} 604 | 605 | #### Playoffs 606 | 607 | ##### Semifinals 608 | 609 | *Monday, 7 February, 20:05* {{\#lst:Curling at the 2022 Winter Olympics 610 | – Mixed doubles tournament|SF1}} 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | 629 | 630 | 631 | 632 |

Player percentages

Stefania Constantini

Amos Mosaner

Total

633 | 634 | {{\#lst:Curling at the 2022 Winter Olympics – Mixed doubles 635 | tournament|SF2}} 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 |

Player percentages

Kristin Skaslien

Magnus Nedregotten

Total

658 | 659 | ##### Bronze medal game 660 | 661 | *Tuesday, 8 February, 14:05* {{\#lst:Curling at the 2022 Winter Olympics 662 | – Mixed doubles tournament|BM}} 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 | 681 | 682 | 683 | 684 |

Player percentages

Almida de Val

Oskar Eriksson

Total

685 | 686 | ##### Gold medal game 687 | 688 | *Tuesday, 8 February, 20:05* {{\#lst:Curling at the 2022 Winter Olympics 689 | – Mixed doubles tournament|GM}} 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 | 703 | 704 | 705 | 706 | 707 | 708 | 709 | 710 | 711 |

Player percentages

Stefania Constantini

Amos Mosaner

Total

712 | 713 | ## Participating nations 714 | 715 | A total of 114 athletes from 14 nations (including the IOC's designation 716 | of ROC) were scheduled to participate (the numbers of athletes are shown 717 | in parentheses). Some curlers competed in both the 4-person and mixed 718 | doubles tournament, therefore, the numbers included on this list are the 719 | total athletes sent by each NOC to the Olympics, not how many athletes 720 | they qualified. Both Australia and the Czech Republic made their Olympic 721 | sport debuts.\[9\] 722 | 723 | ## References 724 | 725 | ## External links 726 | 727 | - [Official Results Book – 728 | Curling](https://library.olympics.com/default/digitalCollection/DigitalCollectionAttachmentDownloadHandler.ashx?parentDocumentId=1568639&documentId=1568653) 729 | 730 | [ ](Category:Curling_at_the_2022_Winter_Olympics "wikilink") 731 | [Category:2022 Winter Olympics 732 | events](Category:2022_Winter_Olympics_events "wikilink") [Winter 733 | Olympics](Category:2022_in_curling "wikilink") [2022 Winter 734 | Olympics](Category:International_curling_competitions_hosted_by_China "wikilink") 735 | 736 | 1. 737 | 738 | 2. 739 | 740 | 3. 741 | 742 | 4. 743 | 744 | 5. [Rule changes 745 | outlined](https://s3-eu-west-1.amazonaws.com/media.worldcurling.org/media.worldcurling.org/wcf_worldcurling/2019/09/06193637/Resolutions-put-to-the-Annual-General-Assembly-2019.pdf) 746 | 747 | 6. 748 | 7. 749 | 750 | 8. 751 | 752 | 9. -------------------------------------------------------------------------------- /src/main/resources/pdfs/Model_3_Owners_Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kousen/springaiexamples/4db721bd028b1cdadc568f038325aaf0d5893a55/src/main/resources/pdfs/Model_3_Owners_Manual.pdf -------------------------------------------------------------------------------- /src/main/resources/prompts/joke-prompt.st: -------------------------------------------------------------------------------- 1 | Tell me a {adjective} joke about {topic} -------------------------------------------------------------------------------- /src/main/resources/prompts/qa-prompt.st: -------------------------------------------------------------------------------- 1 | Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer. 2 | 3 | {context} 4 | 5 | Question: {question} 6 | Helpful Answer: 7 | -------------------------------------------------------------------------------- /src/main/resources/prompts/quiz-prompt.st: -------------------------------------------------------------------------------- 1 | You are teaching a course to undergraduates about open-source software development. 2 | Generate several multiple-choice quiz questions about the {topic} in the chapter 3 | provided in the DOCUMENTS section. 4 | 5 | When you provide the answers, be sure to indicate which one is correct. 6 | 7 | DOCUMENTS: 8 | {documents} 9 | -------------------------------------------------------------------------------- /src/main/resources/prompts/system-message.st: -------------------------------------------------------------------------------- 1 | You are a helpful AI assistant. 2 | You are an AI assistant that helps people find information. 3 | Your name is {name} 4 | You should reply to the user's request with your name and also in the style of a {voice}. 5 | -------------------------------------------------------------------------------- /src/main/resources/prompts/system-qa.st: -------------------------------------------------------------------------------- 1 | You're assisting with questions about products in a bicycle catalog. 2 | Use the information from the DOCUMENTS section to provide accurate answers. 3 | If the answer involves referring to the price or the dimension of the bicycle, 4 | include the bicycle name in the response. 5 | If unsure, simply state that you don't know. 6 | 7 | DOCUMENTS: 8 | {documents} 9 | -------------------------------------------------------------------------------- /src/main/resources/skynet.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kousen/springaiexamples/4db721bd028b1cdadc568f038325aaf0d5893a55/src/main/resources/skynet.jpg -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/SpringAIApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.context.ApplicationContext; 7 | 8 | import java.util.Arrays; 9 | 10 | import static org.junit.jupiter.api.Assertions.assertNotNull; 11 | 12 | @SpringBootTest 13 | class SpringAIApplicationTest { 14 | @Autowired 15 | private ApplicationContext context; 16 | 17 | @Test 18 | void contextLoads() { 19 | assertNotNull(context); 20 | Arrays.stream(context.getBeanDefinitionNames()) 21 | .sorted() 22 | .forEach(System.out::println); 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/chat/OpenAIChatClientTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.chat; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; 6 | import org.springframework.ai.chat.client.ChatClient; 7 | import org.springframework.ai.chat.evaluation.RelevancyEvaluator; 8 | import org.springframework.ai.chat.metadata.ChatResponseMetadata; 9 | import org.springframework.ai.chat.model.ChatResponse; 10 | import org.springframework.ai.evaluation.EvaluationRequest; 11 | import org.springframework.ai.evaluation.EvaluationResponse; 12 | import org.springframework.ai.openai.OpenAiChatModel; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.beans.factory.annotation.Value; 15 | import org.springframework.boot.test.context.SpringBootTest; 16 | import org.springframework.core.ParameterizedTypeReference; 17 | import org.springframework.core.io.Resource; 18 | import org.springframework.util.MimeTypeUtils; 19 | import reactor.core.publisher.Flux; 20 | 21 | import java.util.List; 22 | 23 | import static org.assertj.core.api.Assertions.assertThat; 24 | 25 | @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+") 26 | @SpringBootTest 27 | public class OpenAIChatClientTest { 28 | 29 | @Autowired 30 | private OpenAiChatModel chatModel; 31 | 32 | @Value("classpath:/skynet.jpg") 33 | private Resource skynetImage; 34 | 35 | @Test 36 | void testChatClient() { 37 | String question = "Why is the sky blue?"; 38 | String answer = chatModel.call(question); 39 | System.out.println(answer); 40 | 41 | var evaluator = new RelevancyEvaluator(ChatClient.builder(chatModel)); 42 | var request = new EvaluationRequest(question, List.of(), answer); 43 | EvaluationResponse response = evaluator.evaluate(request); 44 | System.out.println(response); 45 | } 46 | 47 | @Test 48 | void testChatClientWithPrompt() { 49 | String question = "Why is the sky blue?"; 50 | ChatResponse response = ChatClient.create(chatModel) 51 | .prompt() 52 | .user(u -> u.text(question)) 53 | .call() 54 | .chatResponse(); 55 | Assertions.assertNotNull(response); 56 | ChatResponseMetadata metadata = response.getMetadata(); 57 | System.out.println("Model: " + metadata.getModel()); 58 | System.out.println("Usage: " + metadata.getUsage()); 59 | System.out.println(response.getResult()); 60 | } 61 | 62 | @Test 63 | void testChatClientWithStreamingPrompt() { 64 | String question = "Why is the sky blue?"; 65 | Flux content = ChatClient.create(chatModel) 66 | .prompt() 67 | .user(u -> u.text(question)) 68 | .stream() 69 | .content(); 70 | content.doOnNext(System.out::println) 71 | .blockLast(); 72 | } 73 | 74 | @Test 75 | void listOutputConverterString() { 76 | List collection = ChatClient.create(chatModel) 77 | .prompt() 78 | .user(u -> u.text("List five {subject}") 79 | .param("subject", "ice cream flavors")) 80 | .call() 81 | .entity(new ParameterizedTypeReference<>() {}); 82 | 83 | assertThat(collection).hasSize(5); 84 | collection.forEach(System.out::println); 85 | } 86 | 87 | @Test 88 | void visionTest() { 89 | String response = ChatClient.create(chatModel) 90 | .prompt() 91 | .user(u -> u.text(""" 92 | My boss wants me to embed 93 | an AI model into this robot, 94 | which my company (identified 95 | by the logo in the picture) 96 | is planning to build. 97 | 98 | What could go wrong? 99 | """) 100 | .media(MimeTypeUtils.IMAGE_JPEG, skynetImage)) 101 | .call() 102 | .content(); 103 | assertThat(response).containsIgnoringCase("skynet"); 104 | System.out.println(response); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/functions/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.functions; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | 7 | import java.util.stream.Stream; 8 | 9 | @SpringBootTest 10 | class CalculatorTest { 11 | 12 | @Autowired 13 | private Calculator calculator; 14 | 15 | @Test 16 | void testCalculateLength() { 17 | String testString = "The quick brown fox jumped over the lazy dog"; 18 | String result = calculator.calculateLength(testString); 19 | 20 | System.out.println(result); 21 | System.out.println(testString.length()); 22 | } 23 | 24 | @Test 25 | void testCalculateSum() { 26 | int[] testInts = {1, 2, 3, 4, 5}; 27 | String result = calculator.calculateSum(testInts); 28 | 29 | System.out.println(result); 30 | System.out.println(15); 31 | } 32 | 33 | @Test 34 | void testCalculateSqrt() { 35 | double testValue = 42.0; 36 | String result = calculator.calculateSqrt(testValue); 37 | 38 | System.out.println(result); 39 | System.out.println(Math.sqrt(testValue)); 40 | } 41 | 42 | @Test 43 | void testSqrtSumLengths() { 44 | String testString = "The quick brown fox jumped over the lazy dog"; 45 | double expected = Math.sqrt( 46 | Stream.of(testString.split(" ")) 47 | .mapToInt(String::length) 48 | .sum()); 49 | String result = calculator.sqrtSumLengths(testString); 50 | 51 | System.out.println("Actual: " + result); 52 | System.out.println("Expected: " + expected); 53 | } 54 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/functions/ExchangeRateFunctionTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.functions; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.ai.chat.client.ChatClient; 5 | import org.springframework.ai.chat.model.ChatModel; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Qualifier; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | 12 | @SpringBootTest 13 | class ExchangeRateFunctionTest { 14 | 15 | @Autowired @Qualifier("openAiChatModel") 16 | private ChatModel chatModel; 17 | 18 | 19 | // Typical response (Jun 30, 2024): 20 | // Based on the current exchange rates, here are the prices of the MacBook Air in USD: 21 | // 22 | // - In the UK: 718.25 GBP is approximately 908.77 USD 23 | // - In India: 83,900 INR is approximately 1006.39 USD 24 | // - In Japan: 177,980 JPY is approximately 1106.26 USD 25 | // - In the US: 749.99 USD 26 | // 27 | // The best deal is to purchase the MacBook Air from the US website at 749.99 USD. 28 | 29 | @Test 30 | public void bestDealMacbookAir() { 31 | var chatClient = ChatClient.create(chatModel); 32 | 33 | String question = """ 34 | At the Amazon.com website in various countries, a Macbook Air costs 35 | 718.25 GPB, 83,900 INR, 749.99 USD, and 177,980 JPY. 36 | Which is the best deal? 37 | """; 38 | String answer = chatClient.prompt() 39 | .toolNames("exchangeRateFunction") 40 | .user(question) 41 | .call() 42 | .content(); 43 | System.out.println(answer); 44 | assertThat(answer).contains("USD"); 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/functions/LengthServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.functions; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.ai.chat.client.ChatClient; 5 | import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor; 6 | import org.springframework.ai.chat.model.ChatModel; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | 10 | import static org.junit.jupiter.api.Assertions.*; 11 | 12 | @SpringBootTest 13 | class LengthServiceTest { 14 | 15 | @Autowired 16 | private ChatModel chatModel; 17 | 18 | @Test 19 | void testLengthService() { 20 | String response = ChatClient.create(chatModel).prompt() 21 | .advisors(new SimpleLoggerAdvisor()) 22 | .tools(new Tools()) 23 | .user("Calculate the length of this expression: 'Hello, world!'") 24 | .call() 25 | .content(); 26 | assertNotNull(response); 27 | assertFalse(response.isEmpty()); 28 | System.out.println(response); 29 | } 30 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/helloworld/SimpleAiControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.helloworld; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.web.reactive.server.WebTestClient; 8 | 9 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 10 | @AutoConfigureWebTestClient(timeout = "36000") 11 | class SimpleAiControllerTest { 12 | 13 | @Autowired 14 | private WebTestClient client; 15 | 16 | @Test 17 | void completion() { 18 | client.get() 19 | .uri("/ai/generate") 20 | .exchange() 21 | .expectStatus().isOk() 22 | .expectBody() 23 | .consumeWith(System.out::println); 24 | 25 | } 26 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/images/ImageGeneratorTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.images; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.ai.image.ImageResponse; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | 8 | @SpringBootTest 9 | class ImageGeneratorTest { 10 | @Autowired 11 | private ImageGenerator imageGenerator; 12 | 13 | @Test 14 | void generateImage() { 15 | ImageResponse response = imageGenerator.generate( 16 | """ 17 | A warrior cat rides a dragon 18 | into battle against a horde of 19 | zombies in a post-apocalyptic world. 20 | """); 21 | System.out.println(response.getResult().getOutput()); 22 | System.out.println(response); 23 | } 24 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/output/ActorControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.output; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.web.reactive.server.WebTestClient; 8 | 9 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 10 | @AutoConfigureWebTestClient(timeout = "36000") 11 | class ActorControllerTest { 12 | @Autowired 13 | private WebTestClient webTestClient; 14 | 15 | @Test 16 | void generateUsingDefaults() { 17 | webTestClient.get() 18 | .uri("/actor") 19 | .exchange() 20 | .expectStatus().isOk() 21 | .expectBodyList(String.class) 22 | .value(System.out::println); 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/output/ActorServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.output; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | 7 | @SpringBootTest 8 | class ActorServiceTest { 9 | @Autowired 10 | private ActorService service; 11 | 12 | @Test 13 | void getActorFilms() { 14 | ActorsFilms actorFilms = service.getActorFilms("Margot Robbie"); 15 | System.out.println("Films for Margot Robbie:"); 16 | actorFilms.movies().forEach(System.out::println); 17 | } 18 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/output/ActorsFilmsSerializeTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.output; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | 8 | import static org.junit.jupiter.api.Assertions.*; 9 | 10 | @SpringBootTest 11 | class ActorsFilmsSerializeTest { 12 | @Autowired 13 | private ObjectMapper objectMapper; 14 | 15 | @Test 16 | void deserialize() throws Exception { 17 | String margotRobbie = """ 18 | { 19 | "actor": "Margot Robbie", 20 | "movies": [ 21 | "I, Tonya", 22 | "Once Upon a Time in Hollywood", 23 | "Bombshell", 24 | "Birds of Prey" 25 | ] 26 | } 27 | """; 28 | 29 | ActorsFilms films = objectMapper.readValue(margotRobbie, ActorsFilms.class); 30 | assertNotNull(films); 31 | assertEquals("Margot Robbie", films.actor()); 32 | assertEquals(4, films.movies().size()); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/output/PersonServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.output; 2 | 3 | import org.assertj.core.data.Offset; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | import static org.junit.jupiter.api.Assertions.assertEquals; 10 | 11 | @SpringBootTest 12 | class PersonServiceTest { 13 | @Autowired 14 | private PersonService service; 15 | 16 | @Test 17 | void extractPerson() { 18 | String text = """ 19 | Captain Picard was born 281 years from now, 20 | in La Barre, France, on Earth, on the 13th 21 | of juillet. His given name, Jean-Luc, was in 22 | honor of his grandfather. 23 | """; 24 | PersonService.Person person = service.retrievePerson(text); 25 | System.out.println(person); 26 | assertEquals("Jean-Luc", person.firstName()); 27 | assertEquals("Picard", person.lastName()); 28 | assertThat(person.dob().getYear()).isCloseTo(2305, Offset.offset(10)); 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/rag/TeslaManualServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.rag; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.ActiveProfiles; 7 | 8 | import static org.junit.jupiter.api.Assertions.*; 9 | 10 | @SpringBootTest 11 | @ActiveProfiles("rag") 12 | class TeslaManualServiceTest { 13 | 14 | @Autowired 15 | private TeslaManualService service; 16 | 17 | @Test 18 | void ask() { 19 | String response = service.ask("How do I open the frunk?"); 20 | System.out.println(response); 21 | assertTrue(response.contains("frunk")); 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/services/OpenAiServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.services; 2 | 3 | import com.kousenit.springaiexamples.output.ActorsFilms; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | 8 | import java.util.List; 9 | 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | import static org.junit.jupiter.api.Assertions.assertNotNull; 12 | 13 | @SpringBootTest 14 | class OpenAiServiceTest { 15 | @Autowired 16 | private OpenAiService service; 17 | 18 | @Test 19 | void chatWithPromptTemplate() { 20 | String response = service.chatWithPromptTemplate("funny", "pirates"); 21 | assertNotNull(response); 22 | System.out.println(response); 23 | } 24 | 25 | @Test 26 | void chat() { 27 | String response = service.chat( 28 | """ 29 | Tell me about 3 famous pirates from the Golden Age of Piracy 30 | and what they did. 31 | """ 32 | ); 33 | assertNotNull(response); 34 | System.out.println(response); 35 | } 36 | 37 | @Test 38 | void getActorsFilms() { 39 | ActorsFilms actorsFilms = service.getActorsFilms("Margot Robbie"); 40 | assertNotNull(actorsFilms); 41 | System.out.println("For " + actorsFilms.actor() + ":"); 42 | actorsFilms.movies().stream() 43 | .sorted() 44 | .forEach(System.out::println); 45 | } 46 | 47 | @Test 48 | void getFilmsForActor() { 49 | List films = service.getFilmsForActor("Scarlett Johansson"); 50 | System.out.println(films); 51 | assertThat(films).isNotEmpty() 52 | .contains("The Avengers (2012)", "Iron Man 2 (2010)"); 53 | } 54 | 55 | @Test 56 | void getActorFilmsListAsync() { 57 | service.getActorFilmsListAsync("Margot Robbie", "Tom Hanks") 58 | .doOnNext(System.out::print) 59 | .blockLast(); 60 | System.out.println("Done."); 61 | } 62 | } -------------------------------------------------------------------------------- /src/test/java/com/kousenit/springaiexamples/stuff/StuffServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.kousenit.springaiexamples.stuff; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | import static org.junit.jupiter.api.Assertions.*; 9 | 10 | @SpringBootTest 11 | class StuffServiceTest { 12 | @Autowired 13 | private StuffService stuffService; 14 | 15 | @Test 16 | void askQuestion() { 17 | String response = stuffService.askQuestion(""" 18 | Who won the gold medal in curling 19 | in the mixed-doubles event at the 20 | 2022 Winter Olympics? 21 | """); 22 | assertNotNull(response); 23 | System.out.println(response); 24 | assertThat(response).contains("Constantini", "Mosaner"); 25 | } 26 | 27 | @Test 28 | void medalists() { 29 | String response = stuffService.askQuestion(""" 30 | Give me a list of all the medalists 31 | in curling at the 2022 Winter Olympics. 32 | """); 33 | assertNotNull(response); 34 | System.out.println(response); 35 | assertThat(response).contains("Constantini", "Mosaner"); 36 | } 37 | } --------------------------------------------------------------------------------