Skip to content

Commit 2bead6f

Browse files
add post '[Spring AI] Structured Output using Function Calling'
1 parent 517227f commit 2bead6f

File tree

2 files changed

+108
-0
lines changed

2 files changed

+108
-0
lines changed
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
---
2+
layout: "post"
3+
title: "[Spring AI] Structured Output using Function Calling"
4+
description: "Spring AI를 활용한 Function Calling을 통해 모델이 JSON 형식으로 구조화된 출력을 생성하는 방법을\
5+
\ 설명합니다. 예시 코드에서는 사용자의 선호에 맞는 도시 목록을 반환하는 함수를 정의하고, Spring AI의 BeanOutputConverter를\
6+
\ 이용해 자동으로 원하는 형태로 데이터를 매핑합니다. 이 과정은 안정적인 데이터 형식을 제공하여 API의 정상 작동을 보장합니다."
7+
categories:
8+
- "스터디-자바"
9+
tags:
10+
- "Spring"
11+
- "Spring AI"
12+
- "Structured Output"
13+
- "Function Calling"
14+
- "Agents"
15+
- "AI Agents"
16+
- "Json"
17+
- "BeanOutputConverter"
18+
date: "2025-03-17 00:00:00 +0000"
19+
toc: true
20+
image:
21+
path: "/assets/thumbnails/2025-03-17-spring-ai-function-calling.jpg"
22+
---
23+
24+
# Structured Output using Function Calling
25+
26+
[Google Agents Whitepapers](https://www.kaggle.com/whitepaper-agents) 를 보면 Function Calling 에 대해서 다음과 같이 설명하는 부분이 있다.
27+
28+
> With Function Calling, we can teach a model to format this output in a structured style (like JSON) that’s more convenient for another system to parse.
29+
30+
그와 함께 아래와 같은 예시를 보여준다.
31+
32+
```python
33+
def display_cities(cities: list[str], preferences: Optional[str] = None):
34+
"""Provides a list of cities based on the user's search query and preferences.
35+
Args:
36+
preferences (str): The user's preferences for the search, like skiing,
37+
beach, restaurants, bbq, etc.
38+
cities (list[str]): The list of cities being recommended to the user.
39+
Returns:
40+
list[str]: The list of cities being recommended to the user.
41+
"""
42+
return cities
43+
```
44+
45+
```python
46+
from vertexai.generative_models import GenerativeModel, Tool, FunctionDeclaration
47+
48+
model = GenerativeModel("gemini-1.5-flash-001")
49+
50+
display_cities_function = FunctionDeclaration.from_func(display_cities)
51+
tool = Tool(function_declarations=[display_cities_function])
52+
53+
message = "I’d like to take a ski trip with my family but I’m not sure where to go."
54+
55+
res = model.generate_content(message, tools=[tool])
56+
57+
print(f"Function Name: {res.candidates[0].content.parts[0].function_call.name}")
58+
print(f"Function Args: {res.candidates[0].content.parts[0].function_call.args}")
59+
60+
> Function Name: display_cities
61+
> Function Args: {'preferences': 'skiing', 'cities': ['Aspen', 'Vail', 'Park City']}
62+
```
63+
64+
이 코드를 Spring AI 에서 구현한다면 어떨까 생각이 들어 직접 구현해보았다.
65+
66+
## Spring AI 에서 적용시켜보기
67+
68+
참고: [Structured Output](https://docs.spring.io/spring-ai/reference/api/structured-output-converter.html)
69+
70+
Spring AI 에서는 손쉽게 Structured Ouput 으로 변환할 수 있도록 컨버터들을 제공해주고 있다.
71+
72+
이 부분을 Spring AI를 기준으로 변경해본다면 다음과 같이 변경해볼 수 있을 것이다.
73+
74+
```java
75+
CitiesByPreferences citiesByPreferences = ChatClient.builder(chatModel).build()
76+
.prompt()
77+
.user("I'd like to take a ski trip with my family but I'm not sure where to go.")
78+
.call()
79+
.entity(CitiesByPreferences.class);
80+
```
81+
82+
```java
83+
@JsonPropertyOrder({"preferences", "cities"})
84+
record CitiesByPreferences(String preferences, List<String> cities) {}
85+
```
86+
87+
실행시켜보면 다음과 같이 결과가 나온다.
88+
89+
```json
90+
{
91+
"preferences": "Family-friendly ski resorts with a variety of slopes and activities.",
92+
"cities": [
93+
"Aspen", "Colorado", "Park City", "Utah", "Vail", ...
94+
]
95+
}
96+
```
97+
98+
## 내부 동작
99+
100+
우리는 객체(record)만 제공해줬을 뿐인데, 자동으로 우리가 원하는 형태로 값이 채워져서 반환받았다.
101+
102+
그렇게 될 수 있었던 이유는 `Spring AI``BeanOutputConverter` 클래스 내부에서 타겟 타입에 대한 JSON 스키마를 만들어 prompt에 제공하기 때문이다.
103+
104+
그 결과, model은 structured output을 반환하고 Spring AI 에서는 나온 결과 값을 다시 object mapper 를 이용하여 객체에 매핑시킨다.
105+
106+
## 마무리
107+
108+
개발자에게는 안정된 형태의 데이터가 중요하다. 스키마가 다르면 API가 정상적으로 동작하지 않을 가능성이 높기 때문이다. 그런 의미에서 `structured output` 기능을 잘 사용한다면, 개발자에게 필요한 형태로 데이터를 추출할 수 있을 것이다.
1.46 MB
Loading

0 commit comments

Comments
 (0)