> 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/5.-tool.md). Agents can also search and read this documentation through its [MCP server](https://organization-bht.gitbook.io/it/~gitbook/mcp).

# 5. Tool

<figure><img src="https://3572862491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUON3CGxVeoUR2YdtAhxl%2Fuploads%2FcuR2Is3QyahrULtyYVon%2Fimage.png?alt=media&amp;token=c9602a00-2d6d-4ea9-80cd-3eb5de80b3a6" alt=""><figcaption></figcaption></figure>

## Tool

* LLM은 기본적으로 **텍스트 생성**만 가능하다. 즉, 수학 연산이나 데이터베이스 호출, 외부 API호출등이 불가능하다.
* LLM이 외부 세계와 상호작용하여 자체 기능 범위를 확장할 수 있도록 도와주는 **외부 도구 또는 함수를 Tool**이라고 부른다
* 즉, AI를 활용하여 인터넷 검색이나 데이터베이스 연결, 외부 api호출 등 LLM자체의 기능에서 벗어난 동작을 수행해야 하는 경우 **Tool**을 통해 해결할 수 있다.

### ToolCalling 방법

#### 1. Tool정의

* Tool사용할 함수를 정의한다
* 이 함수의 스키마를 정의한다.

```python
# 곱셈연산을 지원하는 함수.
def multiply(a: int, b: int) -> int:
    """
    두 정수 a와 b를 곱합니다. 이 도구는 복잡한 곱셈 계산에 사용됩니다.
    Args:
        a: 첫 번째 정수
        b: 두 번째 정수
    """
    return a * b

# 2. 도구 스키마 정의(Tool Schema)
tools = [
    {
        "type": "function",
        "function": {
            "name": "multiply",
            "description": "두 정수 a와 b를 곱합니다.",
            "parameters": {
                "type": "object",
                "properties": {
                    "a": {"type": "integer", "description": "첫 번째 정수"},
                    "b": {"type": "integer", "description": "두 번째 정수"}
                },
                "required": ["a", "b"]
            }
        }
    }
]
```

#### 2. Tool Binding

```python
# llm 요청시 tool을 함께 전달.
user_query = "137에 45를 곱하면 얼마야?"

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "user", "content": user_query}
    ],
    tools=tools,
    tool_choice="auto"  # 모델이 알아서 도구 쓸지 판단
)

message = response.choices[0].message
print("=== 1차 응답 ===")
print(message)
```

#### 3. 도구 실행 및 결과 반환

```python
import json

if message.tool_calls:
    tool_call = message.tool_calls[0]

    tool_name = tool_call.function.name
    tool_args = json.loads(tool_call.function.arguments)
    tool_call_id = tool_call.id

    print("\n=== 도구 실행 ===")
    print("도구:", tool_name)
    print("인자:", tool_args)

    if tool_name == "multiply":
        tool_result = multiply(**tool_args)

    print("결과:", tool_result)

```

#### 4. 도구 호출 결과를 LLM에게 전달

```python
second_response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "user", "content": user_query},
        message,  # LLM의 tool_call 메시지
        {
            "role": "tool",
            "tool_call_id": tool_call_id,
            "content": str(tool_result)
        }
    ]
)

final_message = second_response.choices[0].message
print("\n=== 최종 응답 ===")
print(final_message.content)

```
