Function Calling คือความสามารถที่ทำให้ Large Language Model สามารถทำหน้าที่เป็น "สมองกลาง" ในการตัดสินใจว่าควรเรียกใช้ external tool หรือ API ใดเพื่อตอบคำถามของผู้ใช้ได้อย่างแม่นยำ ในบทความนี้เราจะเจาะลึกทุกแง่มุมตั้งแต่หลักการสถาปัตยกรรมจนถึงการนำไปใช้งานจริงในระดับ production พร้อม benchmark จริงจาก สมัครที่นี่ ซึ่งเป็น API provider ที่รองรับ OpenAI-compatible endpoints ด้วย latency ต่ำกว่า 50ms และราคาที่ประหยัดกว่า 85%

Function Calling คืออะไรและทำงานอย่างไร

เมื่อคุณส่ง request ไปยัง OpenAI API พร้อมกับ tools definition ตัว model จะทำการวิเคราะห์ user query และตัดสินใจว่าควรเรียก function ใด ผลลัพธ์ที่ได้กลับมาคือ JSON object ที่บอกว่า model ต้องการเรียก function ชื่ออะไรพร้อม arguments ที่ควรส่งไป จากนั้นเราจะ execute function จริงแล้วส่งผลลัพธ์กลับไปให้ model ตีความอีกครั้ง

การกำหนด Tools Definition

Tools definition ใช้ format ที่คล้ายกับ JSON Schema โดยเราต้องระบุชื่อ function คำอธิบาย และ parameters ที่ต้องการ

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "ดึงข้อมูลอากาศของเมืองที่ต้องการ",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "ชื่อเมืองที่ต้องการทราบสภาพอากาศ"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "หน่วยอุณหภูมิที่ต้องการ"
                    }
                },
                "required": ["city"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "search_database",
            "description": "ค้นหาข้อมูลในฐานข้อมูลองค์กร",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "คำค้นหา"
                    },
                    "table": {
                        "type": "string",
                        "description": "ชื่อตารางที่ต้องการค้นหา"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "จำนวนผลลัพธ์สูงสุด",
                        "default": 10
                    }
                },
                "required": ["query"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="gpt-4.1",
    messages=[{"role": "user", "content": "สภาพอากาศในกรุงเทพวันนี้เป็นอย่างไร?"}],
    tools=tools,
    tool_choice="auto"
)

การ Execute Function และ Stream Response

เมื่อได้รับ tool_calls จาก model เราต้อง execute function จริงแล้วส่งผลลัพธ์กลับในรูปแบบ tool message

import json
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_HOLYSHEEP_API_KEY",
    base_url="https://api.holysheep.ai/v1"
)

def execute_function_call(function_name, arguments):
    """Execute function ตามชื่อที่ได้รับจาก model"""
    if function_name == "get_weather":
        return get_weather(
            city=arguments["city"],
            unit=arguments.get("unit", "celsius")
        )
    elif function_name == "search_database":
        return search_database(
            query=arguments["query"],
            table=arguments.get("table"),
            limit=arguments.get("limit", 10)
        )
    else:
        return {"error": f"Unknown function: {function_name}"}

def process_conversation(messages, tools):
    """Process การสนทนาพร้อม handle function calls"""
    response = client.chat.completions.create(
        model="gpt-4.1",
        messages=messages,
        tools=tools,
        tool_choice="auto"
    )
    
    assistant_message = response.choices[0].message
    
    if assistant_message.tool_calls:
        messages.append(assistant_message)
        
        for tool_call in assistant_message.tool_calls:
            function_name = tool_call.function.name
            arguments = json.loads(tool_call.function.arguments)
            
            result = execute_function_call(function_name, arguments)
            
            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-4.1",
            messages=messages,
            tools=tools
        )
        return final_response.choices[0].message.content
    
    return assistant_message.content

messages = [{"role": "user", "content": "ค้นหาพนักงานที่มียอดขายสูงสุดในเดือนนี้"}]
result = process_conversation(messages, tools)
print(result)

Parallel Tool Calling เพิ่มความเร็ว

OpenAI models รุ่นใหม่สามารถเรียกหลาย functions พร้อมกันได้ ซึ่งช่วยลด latency ลงอย่างมากเมื่อต้องดึงข้อมูลจากหลายแหล่ง

parallel_tools = [
    {
        "type": "function",
        "function": {
            "name": "get_stock_price",
            "description": "ดึงราคาหุ้นปัจจุบัน",
            "parameters": {
                "type": "object",
                "properties": {
                    "symbol": {"type": "string", "description": "สัญลักษณ์หุ้น เช่น AAPL, GOOGL"}
                },
                "required": ["symbol"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_exchange_rate",
            "description": "ดึงอัตราแลกเปลี่ยน",
            "parameters": {
                "type": "object",
                "properties": {
                    "from_currency": {"type": "string"},
                    "to_currency": {"type": "string"}
                },
                "required": ["from_currency", "to_currency"]
            }
        }
    }
]

def execute_parallel_tools(tool_calls):
    """Execute หลาย functions พร้อมกันใน production environment"""
    import asyncio
    from concurrent.futures import ThreadPoolExecutor
    
    results = {}
    
    def execute_single(tool_call):
        func_name = tool_call.function.name
        args = json.loads(tool_call.function.arguments)
        return tool_call.id, execute_function_call(func_name, args)
    
    with ThreadPoolExecutor(max_workers=4) as executor:
        futures = [executor.submit(execute_single, tc) for tc in tool_calls]
        for future in futures:
            tool_id, result = future.result()
            results[tool_id] = result
    
    return results

response = client.chat.completions.create(
    model="gpt-4.1",
    messages=[{"role": "user", "content": "ราคาหุ้น AAPL และ GOOGL วันนี้เท่าไหร่ พร้อมแปลงเป็นบาท"}],
    tools=parallel_tools
)

if response.choices[0].message.tool_calls:
    results = execute_parallel_tools(response.choices[0].message.tool_calls)
    print(f"Executed {len(results)} functions in parallel")

การ Implement Streaming สำหรับ Real-time Application

สำหรับ application ที่ต้องการ response แบบ real-time เราสามารถใช้ streaming ได้แต่ต้อง handle tool_calls ใน streaming format

การ Optimize Cost ด้วย Function Calling

Function Calling ช่วยลดต้นทุนได้หลายวิธี ประการแรกคือการใช้ model ขนาดเล็กกว่าสำหรับ task ที่ไม่ซับซ้อน ประการที่สองคือการส่งผลลัพธ์จาก function กลับไปให้ model process ซึ่งถูกกว่าการให้ model generate ข้อมูลเอง

ตัวอย่างเช่น หากคุณใช้ สมัครที่นี่ ซึ่งมีราคา DeepSeek V3.2 เพียง $0.42 ต่อล้าน tokens เทียบกับ GPT-4.1 ที่ $8 คุณสามารถใช้ DeepSeek สำหรับ tool decision แล้วส่งผลลัพธ์ไปให้ GPT-4.1 process ต่อได้ ช่วยประหยัดได้ถึง 95%

Modelราคา/MTok (2026)Use Case เหมาะสม
DeepSeek V3.2$0.42

แหล่งข้อมูลที่เกี่ยวข้อง

บทความที่เกี่ยวข้อง

🔥 ลอง HolySheep AI

เกตเวย์ AI API โดยตรง รองรับ Claude, GPT-5, Gemini, DeepSeek — หนึ่งคีย์ ไม่ต้อง VPN

👉 สมัครฟรี →