OpenAI API를 처음 사용하려는 개발자가 가장 많이 막히는 지점이 있습니다. API 키 발급은 했는데 실제 앱에 어떻게 연동하는지, 스트리밍은 어떻게 구현하는지, 비용을 어떻게 관리하는지 — 이 세 가지입니다. 13년 차 엔지니어로서 수십 개의 GPT 연동 프로젝트를 경험하며 얻은 실전 지식을 이 글에 모두 담겠습니다.
importjsonimportrequests# 1. 도구 스키마 정의tools =[{"type":"function","function":{"name":"get_weather","description":"특정 도시의 현재 날씨를 조회합니다.","parameters":{"type":"object","properties":{"city":{"type":"string","description":"조회할 도시 이름 (예: Seoul, Tokyo)"},"unit":{"type":"string","enum":["celsius","fahrenheit"],"description":"온도 단위"}},"required":["city"]}}}]# 2. 실제 함수 구현defget_weather(city:str, unit:str="celsius")->dict:"""날씨 API 호출 (예시)"""# 실제로는 OpenWeatherMap 같은 API 호출return{"city": city,"temperature":22,"unit": unit,"condition":"맑음"}# 3. Function Calling 흐름defrun_with_tools(user_message:str)->str: messages =[{"role":"user","content": user_message}]# 첫 번째 호출: GPT가 도구 사용 여부 결정 response = client.chat.completions.create( model="gpt-4o", messages=messages, tools=tools, tool_choice="auto",# GPT가 자동으로 도구 선택) message = response.choices[0].message
# 도구 호출이 필요한 경우if message.tool_calls: messages.append(message)# GPT 응답 추가for tool_call in message.tool_calls: func_name = tool_call.function.name
func_args = json.loads(tool_call.function.arguments)# 실제 함수 실행if func_name =="get_weather": result = get_weather(**func_args)# 도구 결과를 메시지에 추가 messages.append({"role":"tool","tool_call_id": tool_call.id,"content": json.dumps(result, ensure_ascii=False)})# 두 번째 호출: 도구 결과를 포함해 최종 응답 생성 final_response = client.chat.completions.create( model="gpt-4o", messages=messages,)return final_response.choices[0].message.content
return message.content
print(run_with_tools("서울 날씨 알려줘"))
importtiktokendefcount_tokens(text:str, model:str="gpt-4o")->int:"""텍스트의 토큰 수를 사전 계산""" encoding = tiktoken.encoding_for_model(model)returnlen(encoding.encode(text))# 비용 예측defestimate_cost(input_text:str, output_tokens:int=500)->float: input_tokens = count_tokens(input_text)# gpt-4o 기준: 입력 $2.50/1M, 출력 $10/1M input_cost =(input_tokens /1_000_000)*2.50 output_cost =(output_tokens /1_000_000)*10.00return input_cost + output_cost
text ="Python 비동기 프로그래밍에 대해 자세히 설명해 주세요."print(f"예상 비용: ${estimate_cost(text):.6f}")
MODEL_TIERS ={"simple":"gpt-4o-mini",# 분류, 추출, 단순 요약"standard":"gpt-4o",# 일반적인 생성, 번역"complex":"gpt-4o",# 복잡한 추론, 코드 생성}defget_model(complexity:str)->str:return MODEL_TIERS.get(complexity,"gpt-4o-mini")
단순 작업에 gpt-4o-mini를 쓰면 비용이 gpt-4o 대비 약 16분의 1로 줄어듭니다.