1.引入SpringAI的依赖

基于Gradle构建Kotlin项目,依赖如下:

plugins {
    kotlin("jvm") version "1.9.25"
    kotlin("plugin.spring") version "1.9.25"
    id("org.springframework.boot") version "3.4.4"
    id("io.spring.dependency-management") version "1.1.7"
}

group = "com.wanna.project.ai"
version = "0.0.1-SNAPSHOT"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

configurations {
    compileOnly {
        extendsFrom(configurations.annotationProcessor.get())
    }
}

repositories {
    mavenCentral()
}

extra["springAiVersion"] = "1.0.0-M7"

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.springframework.ai:spring-ai-starter-model-openai")
    compileOnly("org.projectlombok:lombok")
    annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
    annotationProcessor("org.projectlombok:lombok")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

dependencyManagement {
    imports {
        mavenBom("org.springframework.ai:spring-ai-bom:${property("springAiVersion")}")
    }
}

kotlin {
    compilerOptions {
        freeCompilerArgs.addAll("-Xjsr305=strict")
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
}

2.SpringBoot配置使用的大模型

下面使用OpenAI的GPT4大模型:

# openai大模型
spring.ai.openai.chat.options.model=gpt-4
spring.ai.openai.chat.options.temperature=0
# openai大模型地址, 这里使用的是第三方的中转地址
spring.ai.openai.base-url=https://hk.xty.app
# 访问大模型的apiKey
spring.ai.openai.api-key=sk-xxxxxx

接着,在项目中配置大模型的配置,其中model需要换为自己想要使用的实现,这里使用的是OpenAI的GPT大模型:

@Configuration(proxyBeanMethods = false)
class ChatClientConfiguration {

    @Bean
    fun chatMemory(): ChatMemory {
        return InMemoryChatMemory()
    }

    @Bean
    fun chatClient(model: OpenAiChatModel, chatMemory: ChatMemory): ChatClient {
        return ChatClient.builder(model)
            .defaultAdvisors(
                MessageChatMemoryAdvisor(chatMemory),
                SimpleLoggerAdvisor()
            )
            .build()
    }
}

说明:

  • 1.ChatMemory是什么?ChatClient和大模型之间进行的交互,默认是没有记忆的,也就是说上一句和下一句的聊天之间,是不连贯的。如果需要有交互,需要怎么办呢?此时就需要是用到SpringAI提供的记忆功能ChatMemory,我们这里使用的是基于内存的ChatMemory实现,真实项目中可以使用Redis/MySQL的ChatMemory实现。
  • 2.SimpleLoggerAdvisor是什么?它是用于SpringAI和大模型进行交互时,可以把交互的消息以日志的方式输出出来的Advisor,可以方便我们和AI的调试。注意需要在SpringBoot的application.properties中去开启如下的配置:logging.level.org.springframework.ai=debug

3.测试ChatClient的功能

接着,编写一个测试类,测试一下ChatClient的聊天功能:

@SpringBootTest
class MyAiProjectApplicationTests {

    @Autowired
    private lateinit var chatClient: ChatClient

    @Test
    fun testContextWithConversationId() {
        val conversationId = UUID.randomUUID().toString();

        val response = chatClient
            .prompt("12个苹果分成3批, 每批分几个?")
            .advisors { it.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, conversationId) }
            .call()

        println(response.content())

        val response2 = chatClient
            .prompt("分成4批呢?")
            .advisors { it.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, conversationId) }
            .call()
        println(response2.content())
    }

}

下面是它的执行结果:

12个苹果分成3批,每批分4个苹果。因为 \( 12 \div 3 = 4 \)。
如果12个苹果分成4批,每批分3个苹果。因为 \( 12 \div 4 = 3 \)。