2,086 판독값
2,086 판독값

부서진 채팅봇에 지쳤습니까?이 AI 업그레이드가 모든 것을 고쳐줍니다.

~에 의해 Ritesh Modi15m2025/05/05
Read on Terminal Reader
Read this story w/o Javascript

너무 오래; 읽다

기능 호출은 AI 모델이 외부 도구를 언제 사용해야 하는지, 데이터를 올바르게 포맷하는 방법을 식별할 수 있게 해주며, 작업에 대해 이야기하는 것에서 실제로 작업을 수행하는 데 AI를 변화시킵니다.Standard OpenAI 또는 Azure OpenAI를 사용하더라도 핵심 개념은 동일하지만 구현은 클라이언트 초기화, 인증 및 배포 참조에 따라 다릅니다.OpenAI는 개인 및 소규모 팀에게 더 간단한 액세스를 제공하며, Azure OpenAI는 엔터프라이즈 수준의 보안 및 Microsoft 생태계 통합을 제공하며, 더 많은 구성이 필요하지만 향상된 데이터 관리 기능을 제공합니다.
featured image - 부서진 채팅봇에 지쳤습니까?이 AI 업그레이드가 모든 것을 고쳐줍니다.
Ritesh Modi HackerNoon profile picture
0-item

당신이 원하는 것을 얻지 못하는 누군가와 이야기하는 데 갇혀 있습니까? 6시에 공항으로 가야한다고 친구에게 말할 때와 마찬가지로 그들은 대신 좋아하는 공항 레스토랑에 대해 말하기 시작합니까?

Function Calling 란 무엇입니까?

기능 호출은 AI가 작업을 완료하기 위해 외부 도구 또는 서비스를 사용해야한다는 것을 이해할 때입니다.이것은 당신이 원하는 것을 이해할뿐만 아니라 휴대 전화를 꺼내 날씨를 확인하거나 지도를 확인하거나 택시를 호출 할 때를 알고있는 똑똑한 조력자가있는 것과 같습니다.


기술적으로, 기능 호출은 AI 모델이 특정 기능을 언제 사용해야 하는지, 어떤 매개 변수를 전달해야 하는지, 데이터를 올바르게 포맷하는 방법을 식별할 수 있게 해줍니다.

The Dark Ages: Before Function Calling 근처 오락거리

기능을 호출하기 전에, 모든 것이 ... 혼란스러웠습니다. 외부 도구를 사용하기 위해 AI를 원한다면, 당신은 두 가지 똑같이 좌절 한 옵션이있었습니다 :


  1. Train the AI to generate exact API calls (which often went wrong)

  2. Write complex code to parse AI responses and extract parameters


It's like trying to teach someone a dance by describing the moves in words instead of showing them. You'd say something like, "I need weather data for New York" and the AI would respond with text about the weather, not the actual data you needed.


나는 레스토랑 예약을 예약 할 수있는 채팅 봇을 구축하는 것을 기억합니다. 기능 호출없이 사용자에게 "나는 당신의 테이블을 예약했습니다!"라고 기꺼이 말할 것입니다. 실제로 어떤 예약 시스템에 연결하지 않고.

Function Calling Matters의 이유

Function calling bridges the gap between human language and computer systems. 그것은 중요하기 때문에 :


  1. It's more reliable - the AI structures data exactly as functions need it

  2. It's more capable - an AI can access real-time data, control devices, or run calculations

  3. It's more natural - users can make requests in plain language


기능 호출을 AI가 도구 상자에 액세스 할 수 있도록하는 것처럼 생각하십시오. 이전에는 햄버거에 대해서만 이야기 할 수있었습니다.

그것에 대해 생각하는 간단한 방법

당신이 말할 때, "나는 양파 우유와 함께 중간 라트를 좋아한다,"당신은 기본적으로 바리스타를 "필수로 호출"하고있다.

기능은 보일 수 있습니다: The function might look like:


make_coffee(size="medium", drink_type="latte", milk="oat")


바리스트는 알고 있습니다 :


  1. Identify the function needed (make a drink)

  2. Extract the parameters (size, type, milk choice)

  3. Execute the function (make the coffee)

  4. Return the result (your drink)


기능 호출없이, 당신은 같은 응답을 얻을 것이다 : "오리 우유와 함께 중간 라트는 맛있는 소리!"하지만 실제 커피가 없습니다.Hope you get the idea !


Function Calling 뒤에 있는 Core Mechanics

기능 호출의 핵심은 여러 기술 혁신이 함께 작동하기 때문에 작동합니다.


  1. Structured Function Definitions: When you define functions for an AI model to use, you provide a clear schema that includes the function name, description, and parameter specifications with their types and requirements. This JSON schema helps the model understand not just what the function does, but exactly what information it needs to execute properly.


  2. Intent Recognition: The AI model analyzes user input to determine when a function should be called. Modern models like GPT-4 can recognize when a user's request could be satisfied by calling an external function, even when the user doesn't explicitly ask for it.


  3. Parameter Extraction: The model identifies and extracts relevant parameters from natural language, converting them into the structured format required by the function. For example, when someone asks about Microsoft stock, the model knows to extract "MSFT" as the ticker parameter.


  4. Response Formatting: After a function executes, the model receives the result and incorporates it into a natural language response, creating a seamless experience for the user.


  5. Context Awareness: The model maintains context throughout the conversation, allowing it to use previous function calls and responses to inform new function calls.

️ Function Calling에 대한 Scaffolding Code

OpenAI API를 사용하여 함수 호출을 시작하는 데 사용할 수 있는 템플릿이 있습니다: Here is a template you can use to get started with function calling using the OpenAI API:


from openai import OpenAI
import json

# Initialize the client
client = OpenAI()

# Define your functions
functions = [
    {
        "type": "function",
        "function": {
            "name": "your_function_name",
            "description": "Description of what this function does",
            "parameters": {
                "type": "object",
                "properties": {
                    "param1": {
                        "type": "string",
                        "description": "Description of parameter 1"
                    },
                    "param2": {
                        "type": "integer",
                        "description": "Description of parameter 2"
                    }
                },
                "required": ["param1"]
            }
        }
    }
]

# Your actual implementation of the function
def your_function_name(param1, param2=None):
    # Your code here
    result = f"Did something with {param1}"
    if param2:
        result += f" and {param2}"
    return result

# Process messages and handle function calls
def process_with_function_calling(messages):
    # Get response from the model
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        tools=functions,
        tool_choice="auto"
    )
    
    response_message = response.choices[0].message
    
    # Check if the model wants to call a function
    if response_message.tool_calls:
        # Append the model's response to messages
        messages.append(response_message)
        
        # Process each function call
        for tool_call in response_message.tool_calls:
            function_name = tool_call.function.name
            function_args = json.loads(tool_call.function.arguments)
            
            # Call the function
            if function_name == "your_function_name":
                function_response = your_function_name(
                    function_args.get("param1"),
                    function_args.get("param2")
                )
                
                # Append the function response to messages
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "name": function_name,
                    "content": function_response
                })
        
        # Get a new response from the model
        second_response = client.chat.completions.create(
            model="gpt-4o",
            messages=messages
        )
        
        return second_response.choices[0].message.content
    
    return response_message.content

# Example usage
messages = [{"role": "user", "content": "Your user query here"}]
result = process_with_function_calling(messages)
print(result)


☀️ 일하는 예제 : 날씨 검사

Azure OpenAI를 사용하여 간단한 날씨 검사 기능을 사용하여 이것을 실천하자:




from openai import AzureOpenAI
import json
import requests


# Initialize the Azure OpenAI client
client = AzureOpenAI(
    api_key="your key",  
    api_version="2024-10-21",  # Make sure to use a version that supports function calling
    azure_endpoint="your endpoint"
)


# Define the weather function
weather_functions = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City name, e.g., 'San Francisco'"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Implement the weather function
def get_weather(location, unit="celsius"):
    # In a real app, you'd call a weather API here
    # This is a mock implementation
    weather_data = {
        "San Francisco": {"temp": 18, "condition": "Foggy"},
        "New York": {"temp": 22, "condition": "Partly Cloudy"},
        "London": {"temp": 15, "condition": "Rainy"},
        "Tokyo": {"temp": 24, "condition": "Sunny"}
    }
    
    # Get data for the location or return a default
    data = weather_data.get(location, {"temp": 20, "condition": "Unknown"})
    
    # Convert temperature if needed
    temp = data["temp"]
    if unit == "fahrenheit":
        temp = (temp * 9/5) + 32
    
    return f"It's currently {data['condition']} and {temp}°{'F' if unit == 'fahrenheit' else 'C'} in {location}."

# Process messages with weather function
def check_weather(user_query):
    messages = [{"role": "user", "content": user_query}]
    
    # Get response from the model
    response = client.chat.completions.create(
        model="gpt-4o-mini",  # The name you gave your deployment
        messages=[{"role": "user", "content": user_query}],
        tools=weather_functions,
        tool_choice="auto"
    )
    
    response_message = response.choices[0].message
    
    # Check if the model wants to call the weather function
    if response_message.tool_calls:
        # Append the model's response to messages
        messages.append(response_message)
        
        # Process each function call
        for tool_call in response_message.tool_calls:
            function_name = tool_call.function.name
            function_args = json.loads(tool_call.function.arguments)
            
            # Call the weather function
            if function_name == "get_weather":
                function_response = get_weather(
                    function_args.get("location"),
                    function_args.get("unit", "celsius")
                )
                
                # Append the function response to messages
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "name": function_name,
                    "content": function_response
                })
        
        # Get a new response from the model
        second_response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages
        )
        
        return second_response.choices[0].message.content
    
    return response_message.content

# Try it out
result = check_weather("What's the weather like in Tokyo right now?")
print(result)


이 코드를 "지금 도쿄의 날씨는 어떠한가?"라는 쿼리로 실행하면 AI는 다음을 나타냅니다.


  1. Recognize it needs weather data

  2. Call the get_weather function with "Tokyo" as the location

  3. Receive the weather data

  4. Generate a natural response with the information


추측하거나 날씨 정보를 작성하는 대신 기능을 통해 실제 데이터를 제공합니다.


️ 출력: 날씨 기능 Calling in Action


우리가 "지금 도쿄에서 어떤 날씨가 있습니까?"라는 쿼리를 사용하여 날씨 예제를 실행할 때, 호출 기능의 마법이 생성됩니다.{"location": "Tokyo", "unit": "celsius"}이 포맷된 JSON은 저희에게 전송됩니다.get_weather기능은 우리가 정의한 미친 날씨 데이터를 검색합니다: 온도 24°C 및 "태양" 조건.


Output from previous code


Azure OpenAI 대신 OpenAI를 사용하고 싶습니까?


사이의 주요 차이점은OpenAI그리고Azure OpenAI실행에 대한 거짓말how you initialize the clientOpenAI를 사용하면 표준 클라이언트를 직접 API 키로 사용하는 반면 Azure OpenAI는 그 특정 클라이언트와 같은 추가 매개 변수를 필요로 합니다.azure_endpoint그리고api_version기능 호출을 할 때 OpenAI는 기본 이름으로 모델을 참조하는 반면 Azure OpenAI는 Azure 포털에서 만든 배포 이름을 사용해야 합니다.This reflects Azure's enterprise approach, offering additional security and integration with Microsoft's ecosystem at the cost of slightly more complex configuration.


다음은 코드 비교입니다:


# Standard OpenAI implementation
from openai import OpenAI

# Initialize the client
client = OpenAI(
    api_key="your-openai-api-key"
)

# Make an API call
response = client.chat.completions.create(
    model="gpt-4o",  # Standard model name
    messages=[{"role": "user", "content": "What's the weather in Seattle?"}],
    tools=functions,
    tool_choice="auto"
)


# Azure OpenAI implementation
from openai import AzureOpenAI

# Initialize the client - requires more parameters
client = AzureOpenAI(
    api_key="your-azure-openai-api-key",
    api_version="2023-07-01-preview",  # Azure-specific
    azure_endpoint="https://your-resource-name.openai.azure.com"  # Azure-specific
)

# Make an API call
response = client.chat.completions.create(
    model="your-deployed-model-name",  # The name you gave your deployment in Azure
    messages=[{"role": "user", "content": "What's the weather in Seattle?"}],
    tools=functions,
    tool_choice="auto"
)


기회의 새로운 세계

기능 호출은 모든 것을 바꿨습니다. AI는 이제 다음을 할 수 있습니다:


  • Book real appointments

  • Look up real-time data

  • Control smart home devices

  • Query databases

  • Process payments

  • And much more


그것은 세계에 대해 이야기 할 수있는 AI와 실제로 그것과 상호 작용 할 수있는 것 사이의 차이입니다.


다음 번에 오늘의 뉴스를 채팅 봇에게 요청하거나 조명을 켜는 경우, 그것은 마법을 무대 뒤에서 일으키는 기능을 호출하는 것을 기억하십시오.


요약하기

기능 호출은 인간의 언어와 컴퓨터 시스템 사이의 격차를 니다.이 기능은 적절하게 포맷 된 데이터를 사용하여 외부 도구와 서비스를 호출 할 때 AI를 이해할 수 있습니다 - OpenAI 직접 또는 Azure OpenAI 서비스를 사용하든.우리는 인공지능이 수동적인 응답자에서 활성 에이전트로 변환하는 방법을 탐구했습니다 자연 언어 요청에 따라 구체적인 조치를 취할 수 있습니다.두 플랫폼은 이 혁신적인 기능을 지원하지만 구현 세부 사항, 보안 모델 및 생태계 통합에 차이가 있습니다.

앞을 바라보며

기능 호출의 진정한 힘은 오늘날 할 수있는 것이 아니라 내일 할 수있는 것입니다.더 많은 시스템이 API 엔드포인트를 노출하고 인증 및 보안 표준이 진화함에 따라 자연 언어가 디지털 시스템에 대한 보편적 인 인터페이스가되는 세계에 접근하고 있습니다.이전에 필요한 전문 프로그래밍 지식은 대화를 통해 점점 더 접근 할 수 있습니다.

최종 생각

진정한 혁명은 AI가 이제 행동을 취할 수 있다는 것뿐만 아니라 생각과 행동 사이의 장벽이 해체되고 있다는 것입니다.Function calling은 단순히 기술적 특징이 아닙니다.It is the moment AI stepped beyond the page and into the world, transforming from an observer into a participant.

Trending Topics

blockchaincryptocurrencyhackernoon-top-storyprogrammingsoftware-developmenttechnologystartuphackernoon-booksBitcoinbooks
OSZAR »