> For the complete documentation index, see [llms.txt](https://organization-bht.gitbook.io/it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://organization-bht.gitbook.io/it/ai/2/undefined.md). Agents can also search and read this documentation through its [MCP server](https://organization-bht.gitbook.io/it/~gitbook/mcp).

# 실습문제

## 1. 다음 조건을 만족하는 코드를 구현하시오

**1단계:  분류기**

사용자의 질문을 보고 의도를 `WEATHER | MATH | SMALL_TALK` 중 하나로 분류하고, 필요한 인자를 뽑아 **간결한 JSON**으로 반환할 수 있도록 프롬프트를 구성

**JSON예시)**

```
{
  "intent": "WEATHER | MATH | SMALL_TALK",
  "args": {
    "city": "string (선택)",
    "date": "string (선택, ex)오늘/내일)",
    "expression": "string (선택, ex) 3*(2+5))"
  }
}
```

***

**2단계: 실행기**

1단계의 JSON을 받아서

* `WEATHER`면 **날씨 API**(실습용 모의 API) 호출
* `MATH`면 **수학 API**(실습용 계산기) 호출
* `SMALL_TALK`면 **API 없이** 바로 응답 을 수행하고 **최종 답변**을 생성한다.

***

#### 함수

<pre class="language-python"><code class="lang-python">import os
from openai import OpenAI
from dotenv import load_dotenv

# .env파일 로드
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=api_key)

# 1. math, weater함수

<strong>import json
</strong>def get_current_weather(location, unit="celsius"):
    """
    주어진 위치의 현재 날씨를 가져옵니다.
    """
    weather_data = {
        "seoul": {"location": "Seoul", "temperature": "10", "unit": unit},
        "san francisco": {"location": "San Francisco", "temperature": "72", "unit": unit},
        "paris": {"location": "Paris", "temperature": "22", "unit": unit}
    }
    
    # 소문자로 변환하여 일치하는 도시 찾기
    location = location.lower()
    if location in weather_data:
        return json.dumps(weather_data[location])
    else:
        return json.dumps({"location": location, "temperature": "unknown", "unit": unit})

def calculator(expression):
    """
    주어진 수학 표현식을 계산합니다.
    """
    try:
        # eval() 함수를 사용하여 문자열 형태의 수식을 계산합니다.
        result = eval(expression.replace(' ', '')) # 공백 제거 후 계산
        return json.dumps({"expression": expression, "result": result})
    except Exception as e:
        # 유효하지 않은 수식일 경우 오류 메시지 반환
        return json.dumps({"expression": expression, "error": str(e)})

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "주어진 위치의 현재 날씨를 가져옵니다. 예를 들어, '서울의 날씨는 어때?'와 같은 질문에 사용됩니다.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "도시 이름 (예: 서울, 샌프란시스코)",
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "온도 단위 (섭씨 또는 화씨)",
                    },
                },
                "required": ["location"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "calculator",
            "description": "주어진 수학 표현식을 계산합니다. 예를 들어, '10+5*2'나 '3*(2+5)'와 같은 질문에 사용됩니다.",
            "parameters": {
                "type": "object",
                "properties": {
                    "expression": {
                        "type": "string",
                        "description": "계산할 수학 표현식 (예: '10+5*2')",
                    }
                },
                "required": ["expression"],
            },
        },
    }
]

<strong># 1. 분류기
</strong>#  - 사용자의 질문에서 의도(intent)를 파악하고 
def run_conversation(user_query):
    # 1. 사용자 질문을 바탕으로 모델에게 함수 호출을 요청
    messages = [{"role": "user", "content": user_query}]
    response = client.chat.completions.create(
        model="gpt-4",
        messages=messages,
        tools=tools,
        tool_choice="auto"
    )
    response_message = response.choices[0].message
    tool_calls = response_message.tool_calls

    # 2. 함수 호출이 필요한 경우, 함수를 실행하고 결과를 메시지에 추가
    if tool_calls:
        # 호출 가능한 함수들을 딕셔너리에 저장
        available_functions = {
            "get_current_weather": get_current_weather,
            "calculator": calculator
        }
        
        # 모델 응답 메시지를 메시지 리스트에 추가
        messages.append(response_message)
        
        # 함수 호출 및 결과 처리
        for tool_call in tool_calls:
            function_name = tool_call.function.name
            function_to_call = available_functions[function_name]
            function_args = json.loads(tool_call.function.arguments)
            
            # 함수 이름에 따라 인자를 다르게 전달
            if function_name == "get_current_weather":
                function_response = function_to_call(
                    location=function_args.get("location"),
                    unit=function_args.get("unit")
                )
            elif function_name == "calculator":
                function_response = function_to_call(
                    expression=function_args.get("expression")
                )
            else:
                function_response = json.dumps({"error": "Unknown function"})
            print(f"함수 '{function_name}' 실행 결과: {function_response}")
            # 함수 실행 결과와 함께 메시지를 다시 모델에 전송
            messages.append(
                {
                    "tool_call_id": tool_call.id,
                    "role": "tool",
                    "name": function_name,
                    "content": function_response,
                }
            )

        # 3. 함수 실행 결과에 대한 최종 응답 생성
        second_response = client.chat.completions.create(
            model="gpt-4",
            messages=messages,
        )
        return second_response.choices[0].message.content
    else:
        # 함수 호출이 필요 없는 경우 (SMALL_TALK 등)
        return response_message.content
    
print("사용자 질문: 서울 날씨는 어때?")
print("AI 응답:", run_conversation("서울 날씨는 어때?"))
print("--------------------")
print("사용자 질문: 3 * (20 + 5)의 결과는?")
print("AI 응답:", run_conversation("3 * (20 + 5)의 결과는?"))
print("--------------------")
print("사용자 질문: 안녕, 반가워!")
print("AI 응답:", run_conversation("안녕, 반가워!"))
</code></pre>
