בקשה להפעלת פונקציה במודלים של Grok

התכונה "קריאה להפעלת פונקציות" מאפשרת לכם להגדיר פונקציות בהתאמה אישית ולתת למודלים גדולים של שפה (LLM) את היכולת לקרוא להן כדי לאחזר מידע בזמן אמת או לקיים אינטראקציה עם מערכות חיצוניות, כמו מסדי נתונים של SQL או כלים לשירות לקוחות.

מידע נוסף על קריאה להפעלת פונקציות זמין במאמר מבוא לקריאה להפעלת פונקציות.

איך משתמשים בקריאה להפעלת פונקציות עם Responses API

התבניות הבאות מראות איך להשתמש בקריאה להפעלת פונקציות עם Responses API:

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python שמפורטות במאמר התחלה מהירה של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

לפני שמריצים את הדוגמה הזו, צריך להגדיר את משתנה הסביבה OPENAI_BASE_URL או להגדיר את פרטי הכניסה ל-OAuth. מידע נוסף זמין במאמר אימות ופרטי כניסה.

from openai import OpenAI
client = OpenAI()

response = client.responses.create( model="MODEL", input=[ {"role": "user", "content": "CONTENT"} ], tools=[ { "type": "function", "name": "FUNCTION_NAME", "description": "FUNCTION_DESCRIPTION", "parameters": PARAMETERS_OBJECT, } ], tool_choice="auto", )

  • ‫MODEL: שם המודל שבו רוצים להשתמש, לדוגמה xai/grok-4.20-reasoning.
  • ‫CONTENT: ההנחיה של המשתמש שנשלחת למודל.
  • ‫FUNCTION_NAME: שם הפונקציה שרוצים להפעיל.
  • ‫FUNCTION_DESCRIPTION: תיאור הפונקציה.
  • ‫PARAMETERS_OBJECT: מילון שמגדיר את הפרמטרים של הפונקציה, לדוגמה:
    {"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט ב- Cloud de Confiance .
  • ‫MODEL: שם המודל שבו רוצים להשתמש, לדוגמה xai/grok-4.20-reasoning.
  • ‫INPUT: ההנחיה או הקלט למודל.
  • ‫FUNCTION_NAME: שם הפונקציה שרוצים להפעיל.
  • ‫FUNCTION_DESCRIPTION: תיאור הפונקציה.
  • ‫PARAMETERS_OBJECT: אובייקט JSON שמגדיר את הפרמטרים של הפונקציה.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/responses

גוף בקשת JSON:

{
  "model": "MODEL",
  "input": [
    {"role": "user", "content": "INPUT"}
  ],
  "tools": [
    {
      "type": "function",
      "name": "FUNCTION_NAME",
      "description": "FUNCTION_DESCRIPTION",
      "parameters": PARAMETERS_OBJECT
    }
  ],
  "tool_choice": "auto"
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/responses"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/responses" | Select-Object -Expand Content
 

דוגמה

הדוגמאות הבאות ממחישות איך להשתמש בקריאה לפונקציות עם Responses API:

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python שמפורטות במאמר התחלה מהירה של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

לפני שמריצים את הדוגמה הזו, צריך להגדיר את משתנה הסביבה OPENAI_BASE_URL או להגדיר את פרטי הכניסה ל-OAuth. מידע נוסף זמין במאמר אימות ופרטי כניסה.

from openai import OpenAI
client = OpenAI()

response = client.responses.create( model="xai/grok-4.20-reasoning", input=[ {"role": "user", "content": "What is the temperature in San Francisco?"} ], tools=[ { "type": "function", "name": "get_temperature", "description": "Get current temperature for a location", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "City name"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "default": "fahrenheit"} }, "required": ["location"] } } ], tool_choice="auto", ) print(response)

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/responses -d \
'{
  "model": "xai/grok-4.20-reasoning",
  "input": [
    {"role": "user", "content": "What is the temperature in San Francisco?"}
  ],
  "tools": [
    {
      "type": "function",
      "name": "get_temperature",
      "description": "Get current temperature for a location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {"type": "string", "description": "City name"},
          "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "default": "fahrenheit"}
        },
        "required": ["location"]
      }
    }
  ]
}'
  • ‫PROJECT_ID: מזהה הפרויקט ב- Cloud de Confiance .

תשובה לדוגמה

הדוגמה הבאה ממחישה איך הפלט מהמודל יכול להיראות:

{
  "background": false,
  "completed_at": 1778893466,
  "created_at": 1778893464,
  "error": null,
  "frequency_penalty": 0,
  "id": "mMIHaqfCCIjUmAb_mMIHaqfCCIjUmAb_6LbAAg",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {
    "system_fingerprint": "fp_39c5j0a3e9"
  },
  "model": "xai/grok-4.20-reasoning",
  "object": "response",
  "output": [
    {
      "arguments": "{\"location\":\"San Francisco\"}",
      "call_id": "call-81ad585c-9e8d-47bd-85ef-2ced8a8fc898-0",
      "id": "fc_mMIHaqfCCIjUmAb_6LbAAg",
      "name": "get_temperature",
      "status": "completed",
      "type": "function_call"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "reasoning": {
    "effort": "medium",
    "summary": "detailed"
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": true,
  "temperature": 0.7,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [
    {
      "description": "Get current temperature for a location",
      "name": "get_temperature",
      "parameters": {
        "properties": {
          "location": {
            "description": "City name",
            "type": "string"
          },
          "unit": {
            "default": "fahrenheit",
            "enum": [
              "celsius",
              "fahrenheit"
            ],
            "type": "string"
          }
        },
        "required": [
          "location"
        ],
        "type": "object"
      },
      "strict": false,
      "type": "function"
    }
  ],
  "top_logprobs": 0,
  "top_p": 0.95,
  "truncation": "disabled",
  "usage": {
    "extra_properties": {
      "google": {
        "traffic_type": "ON_DEMAND"
      }
    },
    "input_tokens": 462,
    "input_tokens_details": {
      "cached_tokens": 320
    },
    "num_server_side_tools_used": 0,
    "num_sources_used": 0,
    "output_tokens": 187,
    "output_tokens_details": {
      "reasoning_tokens": 175
    },
    "total_tokens": 649
  },
  "user": null
}

איך משתמשים בקריאה להפעלת פונקציות עם Chat Completions API

הדוגמאות הבאות מראות איך להשתמש בקריאה להפעלת פונקציות עם השלמות צ'אט.

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python שמפורטות במאמר התחלה מהירה של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

לפני שמריצים את הדוגמה הזו, צריך להגדיר את משתנה הסביבה OPENAI_BASE_URL או להגדיר את פרטי הכניסה ל-OAuth. מידע נוסף זמין במאמר אימות ופרטי כניסה.

from openai import OpenAI
client = OpenAI()

response = client.chat.completions.create( model="MODEL", messages=[ {"role": "user", "content": "CONTENT"} ], tools=[ { "type": "function", "function": { "name": "FUNCTION_NAME", "description": "FUNCTION_DESCRIPTION", "parameters": PARAMETERS_OBJECT, } } ], tool_choice="auto", )

  • ‫MODEL: שם המודל שבו רוצים להשתמש, לדוגמה xai/grok-4.1-fast-reasoning.
  • ‫CONTENT: ההנחיה של המשתמש שנשלחת למודל.
  • ‫FUNCTION_NAME: שם הפונקציה שרוצים להפעיל.
  • ‫FUNCTION_DESCRIPTION: תיאור הפונקציה.
  • ‫PARAMETERS_OBJECT: מילון שמגדיר את הפרמטרים של הפונקציה, לדוגמה:
    {"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב-Google Cloud.
  • ‫LOCATION: אזור שתומך במודלים של Grok.
  • ‫MODEL: שם המודל שבו רוצים להשתמש, לדוגמה xai/grok-4.1-fast-reasoning.
  • ‫CONTENT: ההנחיה של המשתמש שנשלחת למודל.
  • ‫FUNCTION_NAME: שם הפונקציה שרוצים להפעיל.
  • ‫FUNCTION_DESCRIPTION: תיאור הפונקציה.
  • ‫PARAMETERS_OBJECT: אובייקט סכימת JSON שמגדיר את הפרמטרים של הפונקציה, לדוגמה:
    {"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions

גוף בקשת JSON:

{
  "model": "MODEL",
  "messages": [
    {
      "role": "user",
      "content": "CONTENT"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "FUNCTION_NAME",
        "description": "FUNCTION_DESCRIPTION",
        "parameters": PARAMETERS_OBJECT
      }
    }
  ],
  "tool_choice": "auto"
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions" | Select-Object -Expand Content

אמורים לקבל קוד סטטוס של הצלחה (2xx) ותגובה ריקה.

דוגמה

הפלט המלא שצפוי להתקבל אחרי שימוש בפונקציה get_current_weather כדי לאחזר מידע מטאורולוגי:

Python

from openai import OpenAI
client = OpenAI()

response = client.chat.completions.create(
  model="xai/grok-4.1-fast-reasoning",
  messages=[
    {
      "role": "user",
      "content": "Which city has a higher temperature, Boston or New Delhi and by how much in F?"
    },
    {
      "role": "assistant",
      "content": "I'll check the current temperatures for Boston and New Delhi in Fahrenheit and compare them. I'll call the weather function for both cities.",
      "tool_calls": [{"function":{"arguments":"{\"location\":\"Boston, MA\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"},{"function":{"arguments":"{\"location\":\"New Delhi, India\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"}]
    },
    {
      "role": "tool",
      "content": "The temperature in Boston is 75 degrees Fahrenheit.",
      "tool_call_id": "get_current_weather"
    },
    {
      "role": "tool",
      "content": "The temperature in New Delhi is 50 degrees Fahrenheit.",
      "tool_call_id": "get_current_weather"
    }
  ],
  tools=[
    {
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location"]
        }
      }
    }
  ],
  tool_choice="auto"
)

curl

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1/projects/sample-project/locations/us-central1/endpoints/openapi/chat/completions -d \
'{
  "model": "xai/grok-4.1-fast-reasoning",
  "messages": [
    {
      "role": "user",
      "content": "Which city has a higher temperature, Boston or New Delhi and by how much in F?"
    },
    {
      "role": "assistant",
      "content": "I'll check the current temperatures for Boston and New Delhi in Fahrenheit and compare them. I'll call the weather function for both cities.",
      "tool_calls": [{"function":{"arguments":"{\"location\":\"Boston, MA\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"},{"function":{"arguments":"{\"location\":\"New Delhi, India\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"}]
    },
    {
      "role": "tool",
      "content": "The temperature in Boston is 75 degrees Fahrenheit.",
      "tool_call_id": "get_current_weather"
    },
    {
      "role": "tool",
      "content": "The temperature in New Delhi is 50 degrees Fahrenheit.",
      "tool_call_id": "get_current_weather"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}'
אחרי שהמודל מקבל את המידע שאוחזר באמצעות קריאה לפונקציה החיצונית `get_current_weather`, הוא יכול לסנתז את המידע משתי התגובות של `tool` ולענות על השאלה של המשתמש. הנה דוגמה לפלט מהמודל:
{
 "choices": [
  {
   "finish_reason": "stop",
   "index": 0,
   "logprobs": null,
   "message": {
    "content": "Based on the current weather data:\n\n- **Boston, MA**: 75°F
    \n- **New Delhi, India**: 50°F  \n\n**Comparison**:
    \nBoston is **25°F warmer** than New Delhi.  \n\n**Answer**:
    \nBoston has a higher temperature than New Delhi by 25 degrees Fahrenheit.",
    "role": "assistant"
   }
  }
 ],
 "created": 1750450289,
 "id": "2025-06-20|13:11:29.240295-07|6.230.75.101|-987540014",
 "model": "xai/grok-4.1-fast-reasoning",
 "object": "chat.completion",
 "system_fingerprint": "",
 "usage": {
  "completion_tokens": 66,
  "prompt_tokens": 217,
  "total_tokens": 283
 }
}

המאמרים הבאים