인공지능 기술의 급속한 발전으로 우리는 이제 더욱 강력하고 유연한 AI 도구들을 손쉽게 활용할 수 있게 되었습니다. 그 중에서도 Azure OpenAI 서비스의 Assistant 기능은 개발자와 기업들에게 큰 주목을 받고 있습니다. 이 기능은 OpenAI에서 먼저 선보인 Assistant API를 기반으로 Azure 플랫폼에 맞춰 최적화되어 제공되고 있습니다.
이번 블로그 글에서는 Azure OpenAI 서비스의 Assistant 기능에 대해 깊이 있게 살펴보고자 합니다. 특히, 이 기능을 Langchain의 Agent와 유사하기 때문에 두 가지를 비교하여 각각의 장단점을 분석할 예정입니다. 또한, Assistant의 강력한 기능 중 하나인 함수 호출(Function Calling) 기능을 활용하여 실시간 주식 및 암호화폐 가격을 조회하는 실용적인 예제를 구현해 보겠습니다.
[Assistant의 주요 구성 요소]

https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/assistants?wt.mc_id=AZ-MVP-5002068
- Assistant: 특정 목적을 위해 설계된 AI 모델로, OpenAI의 언어 모델과 다양한 도구를 활용합니다.
- Thread: 사용자와 Assistant 간의 대화 세션을 나타내며, 메시지를 저장하고 컨텍스트를 관리합니다.
- Message: Assistant 또는 사용자가 생성한 텍스트, 이미지, 파일 등의 콘텐츠입니다.
- Run: Assistant가 특정 Thread에서 작업을 수행하는 인스턴스입니다.
- Run Step: Run의 일부로, Assistant가 수행하는 세부 단계를 나타냅니다.
[Assistant의 핵심 기능]
- 맞춤형 지침 제공: Assistant의 성격과 기능을 특정 지침에 맞게 조정할 수 있습니다.
- 다양한 도구 지원: 코드 인터프리터, 파일 검색, 함수 호출 등 다양한 도구를 활용할 수 있습니다.
- 영구적인 Thread: 대화 내역을 저장하고 관리하여 장기적인 컨텍스트 유지가 가능합니다.
- 파일 관리 및 생성: 다양한 형식의 파일을 공유하거나 생성할 수 있습니다.
[OpenAI Assistant vs LangChain Agent]
OpenAI의 Assistant 기능은 Langchain의 Agent와 기능이 유사하기 때문에 주로 비교가 많이됩니다. 기능은 비슷하지만 몇 가지 다른 점이 있으며, 아래와 같이 접근 방식, 모델, 기능 통합, 상태 관리, 학습 곡선에 따라 차이가 있다고 볼 수 있습니다.

각 항목별 상세하게 비교한 내용은 아래 같습니다.
접근 방식
OpenAI Assistant는 개발자들이 AI 기반 애플리케이션을 쉽고 효율적으로 구축할 수 있도록 설계된 통합 솔루션입니다. 반면 LangChain Agent는 더 유연하고 커스터마이즈 가능한 프레임워크를 제공하여 개발자들에게 더 많은 제어권을 줍니다.
모델 선택
OpenAI Assistant는 OpenAI의 모델(예: GPT-4, GPT-3.5-turbo)에 제한되어 있습니다. 반면 LangChain Agent는 다양한 LLM을 지원하여 개발자가 프로젝트에 가장 적합한 모델을 선택할 수 있는 유연성을 제공합니다.
기능 통합
OpenAI Assistant는 코드 인터프리터, 파일 검색, 함수 호출 등 내장된 도구와 기능을 제공합니다. LangChain Agent는 사용자 정의 도구와 외부 API를 더 쉽게 통합할 수 있어, 개발자가 특정 요구사항에 맞는 도구를 만들고 연결할 수 있습니다.
상태 관리
OpenAI Assistant는 대화 내역을 저장하고 관리하여 장기적인 컨텍스트 유지가 가능한 내장된 상태 관리 기능을 제공합니다. LangChain Agent는 상태 관리를 위해 추가적인 구현이 필요할 수 있지만, 이를 통해 더 세밀한 제어가 가능합니다.
학습 곡선
OpenAI Assistant는 상대적으로 낮은 학습 곡선을 가져 빠르게 구현할 수 있습니다. LangChain Agent는 더 높은 학습 곡선을 가지지만, 이를 통해 개발자는 더 많은 제어와 커스터마이제이션 옵션을 얻을 수 있습니다.
추가적으로, OpenAI Assistant는 메모리와 컨텍스트 윈도우가 자동으로 관리되는 반면, LangChain에서는 이를 직접 관리해야 한다는 점도 주목할 만합니다. 또한, LangChain은 자연어 입력 처리와 컨텍스트 기반 액션 선택에 있어 더 큰 유연성을 제공합니다.
결론적으로, 프로젝트의 요구사항과 개발자의 경험 수준에 따라 적합한 도구를 선택해야 합니다. OpenAI Assistant는 빠른 구현과 간편한 사용을 원하는 경우에 적합하며, LangChain Agent는 더 많은 커스터마이제이션과 제어가 필요한 복잡한 프로젝트에 적합합니다.
그러면 실제로 Azure OpenAI의 Assistant 기능을 간단한 예제를 통해서 알아보도록 하겠습니다.
[주식 및 코인 가격 데이터 확인 예제]
Azure AI Foundry (AI Studio) 활용 방법- Azure AI Foundry에 로그인합니다.
- 새로운 프로젝트를 생성하고 “Assistant” 템플릿을 선택합니다.
- Assistant의 역할을 “금융 데이터 분석가”로 설정합니다.
- 다음과 같은 지침을 추가합니다:
“당신은 주식과 암호화폐 가격 정보를 제공하는 전문가입니다. 사용자가 특정 주식이나 코인의 가격을 물어보면, 최신 데이터를 조회하여 정확한 정보를 제공해주세요.”

5. 함수 호출 기능을 활성화하고, 주식 및 코인 가격을 조회하는 함수를 정의합니다.

6. Assistant를 배포하고 테스트합니다.

출력 결과를 보면 중간에 get_crypto_price 함수를 호출하여 답변이 출력되는 것을 볼 수 있습니다.
Assistant API를 이용한 코드 예제코드의 주요 부분을 나누어 설명하겠습니다.
1. 라이브러리 임포트 및 Azure OpenAI 클라이언트 설정
import os
from openai import AzureOpenAI
import time
import requests
import json
import concurrent.futures
# 환경 변수에서 API 키와 엔드포인트 가져오기
api_key = os.getenv("AZURE_OPENAI_API_KEY")
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
alpha_vantage_api_key = os.getenv("ALPHA_VANTAGE_API_KEY")
# Azure OpenAI 클라이언트 설정
client = AzureOpenAI(
api_key=api_key, # API 키
api_version="2024-02-15-preview", # API 버전
azure_endpoint=azure_endpoint # Azure OpenAI 엔드포인트
)
print("Azure OpenAI 클라이언트 설정 완료")
이 부분에서는 필요한 라이브러리를 임포트하고 Azure OpenAI 클라이언트를 설정합니다. API 키, 버전, 엔드포인트를 지정하여 클라이언트를 초기화합니다.
2. 암호화폐 및 주식 가격 조회 함수
# Coinone API에서 가격 정보를 가져오는 함수
def get_crypto_price(crypto_symbol):
url = "https://api.coinone.co.kr/ticker?currency=all" # Coinone API URL
response = requests.get(url) # API 요청
data = response.json() # JSON 응답 파싱
print(f"Coinone API 응답 데이터: {data}")
if crypto_symbol.lower() in data: # 요청한 암호화폐 심볼이 데이터에 있는지 확인
return float(data[crypto_symbol.lower()]['last']) # 마지막 가격 반환
else:
return None # 심볼이 없으면 None 반환
# Alpha Vantage API에서 주식 가격을 가져오는 함수
def get_stock_price(stock_symbol):
url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={stock_symbol}&apikey={alpha_vantage_api_key}"
response = requests.get(url)
data = response.json()
print(f"Alpha Vantage API 응답 데이터: {data}")
if "Global Quote" in data and "05. price" in data["Global Quote"]:
return float(data["Global Quote"]["05. price"])
else:
print(f"Error fetching stock price: {data}")
return None
이 두 함수는 각각 Coinone API와 Alpha Vantage API를 사용하여 암호화폐와 주식의 현재 가격을 조회합니다. API 응답을 파싱하여 필요한 가격 정보를 추출합니다.
3. AI 어시스턴트 생성
# Assistant 생성
assistant = client.beta.assistants.create(
name="Financial Data Checker", # Assistant 이름
instructions="You are a financial data checker. Use the get_crypto_price function for cryptocurrencies and get_stock_price function for stocks to provide current prices.",
model="gpt-4o", # 모델 설정
tools=[
{
"type": "function", # 도구 타입
"function": {
"name": "get_crypto_price", # 함수 이름
"description": "Get the current price of a cryptocurrency", # 함수 설명
"parameters": {
"type": "object", # 파라미터 타입
"properties": {
"crypto_symbol": {
"type": "string", # 파라미터 데이터 타입
"description": "The symbol of the cryptocurrency (e.g., BTC, ETH)" # 파라미터 설명
}
},
"required": ["crypto_symbol"] # 필수 파라미터
}
}
},
{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "Get the current price of a stock",
"parameters": {
"type": "object",
"properties": {
"stock_symbol": {
"type": "string",
"description": "The symbol of the stock (e.g., AAPL, GOOGL)"
}
},
"required": ["stock_symbol"]
}
}
}]
)
print("Assistant 생성 완료")
여기서는 Azure OpenAI를 사용하여 금융 데이터 체커 어시스턴트를 생성합니다. 어시스턴트에게 사용할 수 있는 도구(함수)를 정의하고, 지시사항을 제공합니다.
4. 대화 스레드 생성 및 실행
# 대화 스레드 생성
thread = client.beta.threads.create(
messages=[
{
"role": "user",
"content": "현재 디즈니 주식 가격과 리플 가격은 얼마인가요?"
}
]
)
print("대화 스레드 생성 완료")
# Assistant 실행
run = client.beta.threads.runs.create(
thread_id=thread.id, # 스레드 ID
assistant_id=assistant.id # Assistant ID
)
print("Assistant 실행 시작")
사용자의 질문으로 대화 스레드를 생성하고, 어시스턴트를 실행합니다.
5. 도구 호출 처리
# 도구 호출을 처리하는 함수
def process_tool_call(tool_call):
print(f"도구 호출 처리 시작: {tool_call}")
if tool_call.function.name == "get_crypto_price":
arguments = json.loads(tool_call.function.arguments)
crypto_symbol = arguments.get("crypto_symbol")
price = get_crypto_price(crypto_symbol)
print(f"암호화폐 가격 조회 결과: {price}")
return {
"tool_call_id": tool_call.id,
"output": str(price)
}
elif tool_call.function.name == "get_stock_price":
arguments = json.loads(tool_call.function.arguments)
stock_symbol = arguments.get("stock_symbol")
price = get_stock_price(stock_symbol)
print(f"주식 가격 조회 결과: {price}")
return {
"tool_call_id": tool_call.id,
"output": str(price)
}
# 병렬로 도구 호출을 처리하고 결과를 수집하는 함수
def process_tool_calls_parallel(tool_calls):
tool_outputs = []
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = [executor.submit(process_tool_call, tool_call) for tool_call in tool_calls]
for future in concurrent.futures.as_completed(futures):
tool_outputs.append(future.result())
print(f"도구 호출 결과: {tool_outputs}")
return tool_outputs
이 함수들은 어시스턴트가 요청한 도구 호출을 처리합니다. process_tool_calls_parallel
함수는 여러 도구 호출을 병렬로 처리하여 효율성을 높입니다.
6. 실행 상태 모니터링 및 결과 처리
# 실행 상태 조회 및 도구 출력 제출
while True:
run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
print(f"Run status: {run.status}")
if run.status in ['queued', 'in_progress']:
time.sleep(2)
elif run.status == 'requires_action':
tool_calls = run.required_action.submit_tool_outputs.tool_calls
tool_outputs = process_tool_calls_parallel(tool_calls)
client.beta.threads.runs.submit_tool_outputs(
thread_id=thread.id,
run_id=run.id,
tool_outputs=tool_outputs
)
else:
break
# 응답 메시지 조회 및 출력
messages = client.beta.threads.messages.list(thread_id=thread.id) # 메시지 리스트 조회
for message in reversed(list(messages)): # 메시지 역순으로 출력
print(f"{message.role}: {message.content[0].text.value}") # 메시지 내용 출력
이 부분에서는 어시스턴트의 실행 상태를 모니터링하고, 필요한 경우 도구 호출을 처리합니다. 실행이 완료되면 대화 내용을 출력합니다.

#### 출력 결과 #####
Azure OpenAI 클라이언트 설정 완료
Assistant 생성 완료
대화 스레드 생성 완료
Assistant 실행 시작
Run status: queued
Run status: in_progress
Run status: requires_action
도구 호출 처리 시작: RequiredActionFunctionToolCall(id='call_jduBE5HGA2yMPCHk7xLpiTL9', function=Function(arguments='{"stock_symbol": "DIS"}', name='get_stock_price'), type='function')
도구 호출 처리 시작: RequiredActionFunctionToolCall(id='call_xHxRAY5JxlSyVud34ji7KHcf', function=Function(arguments='{"crypto_symbol": "XRP"}', name='get_crypto_price'), type='function')
Coinone API 응답 데이터: {'result': 'success', 'errorCode': '0', 'timestamp': '1737346514', 'orca': {'currency': 'orca', 'first': '6000.0', 'low': '5250.0', 'high': '6950.0', 'last': '5400.0', 'volume': '17507.04647138', 'yesterday_first': '5500.0', 'yesterday_low': '5500.0', 'yesterday_high': '6500.0', 'yesterday_last': '6000.0', 'yesterday_volume': '29511.63319802'}, 'clv': {'currency': 'clv', 'first': '74.5',...}}
암호화폐 가격 조회 결과: 4672.0
Alpha Vantage API 응답 데이터: {'Global Quote': {'01. symbol': 'DIS', '02. open': '106.8300', '03. high': '107.7400', '04. low': '106.5400', '05. price': '107.0200', '06. volume': '7144263', '07. latest trading day': '2025-01-17', '08. previous close': '106.4600', '09. change': '0.5600', '10. change percent': '0.5260%'}}
주식 가격 조회 결과: 107.02
도구 호출 결과: [{'tool_call_id': 'call_xHxRAY5JxlSyVud34ji7KHcf', 'output': '4672.0'}, {'tool_call_id': 'call_jduBE5HGA2yMPCHk7xLpiTL9', 'output': '107.02'}]
Run status: in_progress
Run status: in_progress
Run status: completed
user: 현재 디즈니 주식 가격과 리플 가격은 얼마인가요?
assistant: 현재 디즈니 (DIS) 주식 가격은 $107.02이며, 리플 (XRP)의 가격은 $0.4672입니다.
이 코드는 Azure OpenAI를 활용하여 실시간 금융 데이터를 조회하고 사용자 질문에 답변하는 지능형 어시스턴트를 구현한 것입니다. 암호화폐와 주식 가격을 실시간으로 조회하여 정확한 정보를 제공할 수 있습니다.