Skip to content

Commit 7d62d83

Browse files
committed
new blog
1 parent 282fbe4 commit 7d62d83

12 files changed

+1508
-15
lines changed

_posts/2025-04-14-ai-agent.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ layout: post
33
title: "AI Agent 구현해보기"
44
subtitle: "ChatGPT를 이용한 간단한 주식 agent 봇 만들기"
55
feature-img: "assets/img/2025-04-14/0.webp"
6-
tags: [머신러닝]
6+
tags: [LLMOps]
77
---
88

99
# AI Agent 구현해보기
@@ -213,7 +213,7 @@ def answer_paraphrase(answer_data: dict, user_input: str) -> str | None:
213213

214214
이렇게 구축된 코드를 실행하면 아래와 같은 간단한 AI Agen가 생성한다.
215215

216-
실행 결과물 예시
216+
실행 결과물 예시:
217217

218218
```txt
219219
유저의 질문: 기아 자동차 주가가 얼마지?

_posts/2025-05-03-gke-iam-role.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ layout: post
33
title: "GKE에서 AWS IAM Role 연동: Access Key 없이 안전하게 AWS 리소스 접근하기"
44
subtitle: "GKE Workload Identity와 AWS IAM Role을 활용한 안전한 멀티클라우드 접근 방식"
55
feature-img: "assets/img/2025-05-03/0.webp"
6-
tags: [머신러닝]
6+
tags: [Infra]
77
---
88

99
## 들어가며: 멀티클라우드 환경에서의 보안

_posts/2025-05-07-llm-function-calling.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
---
22
layout: post
3-
title: "[LLM] Function Calling 구현하기"
4-
subtitle: ""
5-
feature-img: "assets/img/2025-05-03/0.webp"
6-
tags: [머신러닝]
3+
title: "AI 에이전트의 핵심, LLM Function Calling 파헤치기"
4+
subtitle: "Python과 OpenAI API를 활용해 LLM이 외부 함수를 호출하고 실제 작업을 수행하는 방법을 알아봅니다."
5+
feature-img: "assets/img/2025-05-07/0.webp"
6+
tags: [LLMOps]
77
---
88

99
최근 대규모 언어 모델(LLM) 분야에서 **Function Calling**이라는 흥미로운 개념이 등장했습니다.
@@ -43,7 +43,7 @@ ReAct 에이전트와 Function Calling 에이전트의 차이점에 대해 더
4343

4444
먼저 yahoo finance 라이브러리를 통해 가격을 조회하는 코드는 다음과 같습니다. (실제 실행을 위해서는 yfinance 라이브러리가 설치되어 있어야 합니다: pip install yfinance)
4545

46-
```
46+
```python
4747
def get_stock_price(stock_code: str) -> dict:
4848
"""주식 가격 정보를 가져오기 위한 함수"""
4949
try:
@@ -85,7 +85,7 @@ def get_stock_price(stock_code: str) -> dict:
8585

8686
이제 이런 함수가 있다는 것을 LLM에게 알려주기 위한 형태로 만들어야 합니다.
8787

88-
```
88+
```python
8989
tools = [
9090
{
9191
"type": "function",
@@ -109,7 +109,7 @@ def get_stock_price(stock_code: str) -> dict:
109109

110110
이제 이 tools 정보를 포함하여 GPT를 호출합니다. (실제 API 호출을 위해서는 openai 라이브러리가 필요하며, API 키 설정이 필요합니다.)
111111

112-
```
112+
```python
113113
messages: list[ChatCompletionMessageParam] = [
114114
{
115115
"role": "user",
@@ -130,7 +130,7 @@ def get_stock_price(stock_code: str) -> dict:
130130

131131
위 코드를 실행하면 (실제 API 호출 시), LLM은 사용자의 질문을 이해하고 get\_stock\_price 함수를 호출해야 한다고 판단할 경우 다음과 유사한 응답을 반환합니다.
132132

133-
```
133+
```shell
134134
ChatCompletion(id='chatcmpl-BUYpFct1sxYpeNUb7IBeegqOb6XJS',
135135
choices=[Choice(finish_reason='tool_calls', index=0, logprobs=None,
136136
message=ChatCompletionMessage(content=None, refusal=None, role='assistant',
@@ -149,7 +149,7 @@ prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0)))
149149

150150
이제 개발자는 이 응답을 바탕으로 실제로 위에서 정의한 get\_stock\_price 함수를 실행합니다.
151151

152-
```
152+
```python
153153
if response.choices and response.choices[0].message.tool_calls:
154154
tool_call = response.choices[0].message.tool_calls[0]
155155
if tool_call.function.name == "get_stock_price":
@@ -170,7 +170,7 @@ prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0)))
170170

171171
마지막으로, 이 answer\_data (함수 실행 결과)를 다시 LLM에게 전달하여 사용자에게 친절한 형태로 답변을 생성하도록 요청합니다.
172172

173-
```
173+
```python
174174
messages = [
175175
{
176176
"role": "system",

_posts/2025-05-16-nvidia-triton-inference-server.md

Lines changed: 345 additions & 0 deletions
Large diffs are not rendered by default.

_posts_en/2025-04-14-ai-agent.md

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
---
2+
layout: post
3+
title: "Implementing an AI Agent"
4+
subtitle: "Creating a simple stock agent bot using ChatGPT"
5+
feature-img: "assets/img/2025-04-14/0.webp"
6+
tags: [LLMOps]
7+
---
8+
9+
# Implementing an AI Agent
10+
11+
Since ChatGPT was released to the world on November 30, 2022, we have been experiencing a wave of rapid change.
12+
13+
Among these changes, the concept of the AI Agent is particularly noteworthy. Although a bit late, to keep up with the times, I want to take a closer look at this concept and try to implement a simple AI Agent myself.
14+
15+
## AI Agent??
16+
17+
When I first encountered the term AI Agent, I thought it was just another name for the existing AI Assistant.
18+
19+
However, there is a significant difference between the two, which I want to clarify first.
20+
21+
While searching for related information, I found useful information in the [GCP docs](https://cloud.google.com/discover/what-are-ai-agents). The link is below.
22+
23+
This document defines an AI Agent as "a software system that uses AI to pursue goals and complete tasks on behalf of a user."
24+
25+
On the other hand, the AI Assistant, which I was confused about, is described as "an AI agent designed to collaborate directly with users, understand and respond to natural language and input, and perform tasks."
26+
27+
For example, an AI Assistant, like Apple's Siri or Amazon's Alexa, answers user questions and performs tasks by interacting with the user.
28+
29+
In contrast, an AI Agent has a higher level of autonomy and makes independent decisions to achieve specific goals, much like an autonomous driving system.
30+
31+
Of course, it is difficult to draw a clear line between an AI Assistant and an AI Agent.
32+
33+
<img src="/assets/img/2025-04-14/1.png">
34+
35+
The speaker uses Cursor as an IDE. (I've become someone who can't develop without Cursor...)
36+
37+
Cursor has already introduced an AI Agent.
38+
39+
<img src="/assets/img/2025-04-14/2.png">
40+
41+
As shown in the picture above, when you give the Agent a goal, it performs the goal in various ways, such as checking my folder structure, using the knowledge that the LLM has, and searching the web if necessary.
42+
43+
If an error occurs during a task, it finds the cause on its own and solves the problem in a different way.
44+
45+
## AI Agent Practice: Implementing it myself
46+
47+
The easiest way to understand is to practice it myself, so I'm going to implement a simple AI Agent.
48+
49+
The AI Agent to be implemented is a simple bot that checks stock prices.
50+
51+
The environment used is as follows.
52+
53+
### Environment Used
54+
55+
- python 3.12
56+
- openai - gpt4o-mini
57+
- yfinance
58+
59+
The complete code can be found in the [GitHub repository](https://github.com/ppippi-dev/ai-agent-test) below.
60+
61+
### Simple Flow Introduction
62+
63+
The bot to be implemented operates in the following order.
64+
65+
1. The user enters a question.
66+
2. GPT extracts the stock name from the question and returns the corresponding stock code.
67+
3. The yfinance library retrieves the stock information for the stock code.
68+
4. GPT organizes the data and prints it in a user-friendly way.
69+
70+
Now let's implement the above flow with code.
71+
72+
First, I will implement the necessary functions for each step and call them from the main function.
73+
74+
The functions that make up the Agent are as follows.
75+
76+
- `act()`: A function that controls the main flow
77+
- `get_stock_code_from_gpt()`: A function that extracts the stock code
78+
- `get_stock_price()`: A function that retrieves stock price information
79+
- `answer_paraphrase()`: A function that generates the final answer
80+
81+
Let's look at the implementation of each function.
82+
83+
First, let's look at the `act()` function for the flow.
84+
85+
```python
86+
def act(user_input):
87+
"""Determine action based on user input"""
88+
89+
stock_code = get_stock_code_from_gpt(user_input)
90+
add_ks_mark = f"{stock_code.stock_code}.KS"
91+
stock_info = get_stock_price(add_ks_mark)
92+
answer = answer_paraphrase(stock_info, user_input)
93+
return answer
94+
```
95+
96+
This function manages the entire flow of receiving user input, querying stock information, and generating a response.
97+
98+
It's easier to think of it as a simple LLM pipeline.
99+
100+
Next is the main function that processes the user's question.
101+
102+
```python
103+
def main():
104+
"""main function"""
105+
agent = StockAgent()
106+
107+
while True:
108+
user_input = input("User's question: ")
109+
if user_input == "exit":
110+
break
111+
response = agent.act(user_input)
112+
print(response)
113+
```
114+
115+
This function processes the user's question through a simple while loop.
116+
117+
Now, this is the part where we actually implement the AI Agent.
118+
119+
It extracts the stock included in the user's question through GPT and returns the code for that stock.
120+
121+
```python
122+
class StockCode(BaseModel):
123+
"""Model to return stock code"""
124+
125+
stock_code: str
126+
127+
def get_stock_code_from_gpt(user_input: str) -> StockCode | None:
128+
"""Function to return stock code"""
129+
messages = [
130+
{
131+
"role": "system",
132+
"content": "You are a program that finds the stock code of the stock item included in the user's question. Find the stock code of the stock item included in the user's question and return the stock code.",
133+
},
134+
{
135+
"role": "user",
136+
"content": f"Please tell me the stock code through the question below. The stock code consists of 6 digits, like '000000'. \n User's question: {user_input}",
137+
},
138+
]
139+
response = client.beta.chat.completions.parse(
140+
model="gpt-4o-mini",
141+
messages=messages,
142+
max_tokens=150,
143+
temperature=0.7,
144+
response_format=StockCode,
145+
)
146+
return response.choices[0].message.parsed
147+
```
148+
149+
I configured the prompt to extract the stock code if there is a stock item in the user's question.
150+
151+
Then, it extracts stock information data using the extracted stock code and the yfinance library.
152+
153+
```python
154+
def get_stock_price(ticker_symbol: str) -> dict:
155+
"""Function to get stock price information"""
156+
try:
157+
# Get stock information using the yfinance library
158+
ticker = yf.Ticker(ticker_symbol)
159+
info = ticker.info
160+
161+
# Extract necessary information
162+
current_price = info.get("currentPrice", "No information")
163+
previous_close = info.get("previousClose", "No information")
164+
company_name = info.get("longName", ticker_symbol)
165+
166+
# Calculate price change
167+
if current_price != "No information" and previous_close != "No information":
168+
change = current_price - previous_close
169+
change_percent = (change / previous_close) * 100
170+
change_str = f"{change:.2f} ({change_percent:.2f}%)"
171+
else:
172+
change_str = "No information"
173+
174+
return {
175+
"success": True,
176+
"company_name": company_name,
177+
"ticker": ticker_symbol,
178+
"current_price": current_price,
179+
"previous_close": previous_close,
180+
"change": change_str,
181+
}
182+
except Exception as e:
183+
return {"success": False, "error": str(e)}
184+
```
185+
186+
yfinance is a library that retrieves data for stock codes through Yahoo Finance, but it doesn't seem to have all domestic stock items.
187+
188+
Finally, it generates an answer through GPT with the obtained data.
189+
190+
```python
191+
def answer_paraphrase(answer_data: dict, user_input: str) -> str | None:
192+
"""Paraphrasing function for answering with stock information data"""
193+
messages = [
194+
{
195+
"role": "system",
196+
"content": "You are a program that creates answers to user questions. Please create an answer to the user's question.",
197+
},
198+
{
199+
"role": "user",
200+
"content": f"User's question: {user_input}, Data: {answer_data}",
201+
},
202+
]
203+
response = client.beta.chat.completions.parse(
204+
model="gpt-4o-mini",
205+
messages=messages,
206+
temperature=0.7,
207+
)
208+
return response.choices[0].message.content
209+
```
210+
211+
Running the code built this way creates a simple AI Agent as shown below.
212+
213+
Example of execution result:
214+
215+
```txt
216+
User's question: What is the stock price of Kia Motors?
217+
The current stock price of Kia Motors is 84,300 won. The previous closing price was 84,600 won, and the current price has fallen by 300 won (-0.35%).
218+
User's question: How much is Samsung Electronics?
219+
The current stock price of Samsung Electronics is 53,500 won. The previous closing price was 53,200 won, and today it has risen by 300 won (0.56%).
220+
```
221+
222+
## Afterword
223+
224+
I have implemented a simple AI Agent as above. In fact, most LLMs already perform agent functions through web searches with internal logic without the need for the above method.
225+
226+
In particular, looking at the process by which inference models (Chain of Thought) obtain answers, it is presumed that the following process is included.
227+
228+
For reference, OpenAI has already created an [API to easily build agents](https://openai.com/index/new-tools-for-building-agents/).
229+

0 commit comments

Comments
 (0)