=================
== The Archive ==
=================

[Spring AI] ChatClient 생성하기

|

Introduction

ChatClient 생성

Autoconfigured 된 ChatClient.Builder 사용하는 방식

1
2
@Bean
fun chatClientAutoconfigured(chatClientBuilder: ChatClient.Builder): ChatClient = chatClientBuilder.build()

프로그래밍 방식

1
2
3
4
5
6
7
@Bean
fun chatClientProgrammatically(
    @Value("\${spring.ai.openai.api-key}") apiKey: String,
): ChatClient {
    val openAiChatModel = OpenAiChatModel(OpenAiApi(apiKey))
    return ChatClient.create(openAiChatModel)
}

간단하게 응답 받아보기

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@Service
class BasicAiService(
    private val chatClientAutoconfigured: ChatClient,
    private val chatClientProgrammatically: ChatClient,
) {
    fun generationWithAutoconfigured(userInput: String): String =
        chatClientAutoconfigured
            .prompt()
            .user(userInput)
            .call()
            .content()

    fun generationWithProgrammatically(userInput: String): String =
        chatClientProgrammatically
            .prompt()
            .user(userInput)
            .call()
            .content()
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@RestController
class AiController(
    private val basicAiService: BasicAiService,
) {
    @PostMapping("/generation/autoconfigured")
    fun generationWithAutoconfigured(
        @RequestBody question: Question,
    ): Answer = basicAiService.generationWithAutoconfigured(question.text).toAnswer()

    @PostMapping("/generation/programmatically")
    fun generationWithProgrammatically(
        @RequestBody question: Question,
    ): Answer = basicAiService.generationWithProgrammatically(question.text).toAnswer()
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
### Generation With Autoconfigured
POST localhost:8080/generation/autoconfigured
Content-Type: application/json

{
  "text": "Tell me a joke"
}

### generationWithProgrammatically
POST localhost:8080/generation/programmatically
Content-Type: application/json

{
  "text": "Tell me a joke"
}
1
2
3
{
  "text": "Sure, here's a light-hearted joke for you:\n\nWhy don't skeletons fight each other?\n\nThey don't have the guts!"
}
1
2
3
{
  "text": "Sure, here's one for you:\n\nWhy don't scientists trust atoms?\n\nBecause they make up everything!"
}

References

Categories:

Tags: