Table of Contents
Catalog
How does OpenAI function call work?
Quick Example: Weather API
Step 1: Define the function
Step 2: Call the model using the defined function
Step 3: Execute the function
Step 4: Provide results to the model
Step 5: Get the final response
Best Practice for Function Calls
Summary
Home Technology peripherals AI Checkout the OpenAI Function Calling Guide

Checkout the OpenAI Function Calling Guide

Mar 10, 2025 am 10:07 AM

OpenAI releases a new function call guide to help developers expand their model capabilities! This guide integrates user feedback, reduces 50% shorter, has clearer content, and contains complete examples of best practices, in-document function generation, and use of the weather API. OpenAI is committed to simplifying AI tools to make them easier for developers to use, thereby making it more efficient to utilize function calling capabilities.

OpenAI releases a brand new guide to function calling!

We have made important improvements based on your feedback:

-- 50% shorter, making it clearer and easier to understand – New best practices (see below for details?) – Supports in-document function generation! – Provides a complete feature example of using the weather API

View the guide and share your thoughts... pic.twitter.com/Id89E9PEff

— ilan bigio (@ilanbigio) January 13, 2025

Catalog

  • How does OpenAI function call work?
  • Quick Example: Weather API
    • Step 1: Define the function
    • Step 2: Call the model using the defined function
    • Step 3: Execute the function
    • Step 4: Provide results to the model
    • Step 5: Get the final response
  • Best Practice for Function Calls
  • Summary

How does OpenAI function call work?

Function calls allow the OpenAI model to interact with developer-defined tools, enabling it to perform more tasks beyond text or audio generation. The following is a simplified process:

  1. Define function: Create a function that the model can call (for example, get_weather).
  2. Model determines calling functions: Based on system prompts and user input, the model determines when to call functions.
  3. Execute function: Run the function code and return the result.
  4. Integration Results: The model uses the output of the function to generate the final response.

Checkout the OpenAI Function Calling Guide

This image shows the process of function calls between the developer and the AI ​​model. Here are the step-by-step instructions:

  • Tool Definition Message: The developer defines the tool (function) and sends a message. In this example, the get_weather(location) function is defined, and the user asks: "What is the weather in Paris?"
  • Tool call: Model recognition requires the use of the parameter "paris" to call the get_weather function.
  • Execute function code: The developer (or system) executes the actual get_weather("paris") function. The function returns the response, for example: {"temperature": 14}.
  • Result: The result of the function ({"temperature": 14}) is returned to the model with all previous messages.
  • Final response: The model uses the function results to generate a natural language response, for example: "The current temperature in Paris is 14°C."

Please read also: 6 top LLMs that support function calls

Quick Example: Weather API

Let's look at a practical example using the get_weather function. This function retrieves the current temperature of the given coordinates.

Step 1: Define the function

<code>import requests

def get_weather(latitude, longitude):
    response = requests.get(f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m")
    data = response.json()
    return data['current']['temperature_2m']</code>
Copy after login

Step 2: Call the model using the defined function

<code>from openai import OpenAI
import json

client = OpenAI(api_key="sk-api_key”)

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "获取提供的坐标(摄氏度)的当前温度。",
        "parameters": {
            "type": "object",
            "properties": {
                "latitude": {"type": "number"},
                "longitude": {"type": "number"}
            },
            "required": ["latitude", "longitude"],
            "additionalProperties": False
        },
        "strict": True
    }
}]

messages = [{"role": "user", "content": "今天巴黎的天气怎么样?"}]

completion = client.chat.completions.create(
    model="gpt-4o",
    messages=messages,
    tools=tools,
)</code>
Copy after login

Step 3: Execute the function

<code>tool_call = completion.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)

result = get_weather(args["latitude"], args["longitude"])</code>
Copy after login

Step 4: Provide results to the model

<code># 附加模型的工具调用消息
messages.append(completion.choices[0].message)

# 将结果消息作为字符串附加
messages.append({
    "role": "tool",
    "tool_call_id": tool_call.id,
    "content": json.dumps({"temperature": result})  # 将结果转换为JSON字符串
})

# 创建第二个聊天完成
completion_2 = client.chat.completions.create(
    model="gpt-4o",
    messages=messages,
    tools=tools,
)</code>
Copy after login

Step 5: Get the final response

<code>print(completion_2.choices[0].message.content)</code>
Copy after login

Output:

<code>巴黎目前的温度是-2.8°C。</code>
Copy after login

Best Practice for Function Calls

To help you make the most of your function calls, here are some professional tips:

  1. Writing a clear and detailed description
    • Clearly describe the purpose, parameters and output of the function.
    • Use the system prompts to guide the model when (and when not) to use functions.
  2. Best Practice of Application Software Engineering
    • Make the function intuitive and easy to understand.
    • Use enumerations and object structures to prevent invalid states.
  3. Reduce the burden on the model
    • Do not let the model fill in parameters you know.
    • Merge functions that are always called sequentially.
  4. The number of functions is small
    • To improve accuracy, use up to less than 20 functions at a time.
  5. Utilize OpenAI resources
    • Use Playground to generate and iterate function patterns.
    • Consider fine-tuning for complex tasks or large numbers of functions.

For more information, please visit OpenAI.

Summary

OpenAI's improved function call guide enables developers to seamlessly integrate custom tools to make AI easier to access and use. By simplifying processes, providing clear examples, and prioritizing user feedback, OpenAI enables developers to innovate and build solutions that leverage the full potential of AI, thereby driving real-world applications and creativity.

The above is the detailed content of Checkout the OpenAI Function Calling Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

I Tried Vibe Coding with Cursor AI and It's Amazing! I Tried Vibe Coding with Cursor AI and It's Amazing! Mar 20, 2025 pm 03:34 PM

Vibe coding is reshaping the world of software development by letting us create applications using natural language instead of endless lines of code. Inspired by visionaries like Andrej Karpathy, this innovative approach lets dev

Top 5 GenAI Launches of February 2025: GPT-4.5, Grok-3 & More! Top 5 GenAI Launches of February 2025: GPT-4.5, Grok-3 & More! Mar 22, 2025 am 10:58 AM

February 2025 has been yet another game-changing month for generative AI, bringing us some of the most anticipated model upgrades and groundbreaking new features. From xAI’s Grok 3 and Anthropic’s Claude 3.7 Sonnet, to OpenAI’s G

How to Use YOLO v12 for Object Detection? How to Use YOLO v12 for Object Detection? Mar 22, 2025 am 11:07 AM

YOLO (You Only Look Once) has been a leading real-time object detection framework, with each iteration improving upon the previous versions. The latest version YOLO v12 introduces advancements that significantly enhance accuracy

Best AI Art Generators (Free & Paid) for Creative Projects Best AI Art Generators (Free & Paid) for Creative Projects Apr 02, 2025 pm 06:10 PM

The article reviews top AI art generators, discussing their features, suitability for creative projects, and value. It highlights Midjourney as the best value for professionals and recommends DALL-E 2 for high-quality, customizable art.

Is ChatGPT 4 O available? Is ChatGPT 4 O available? Mar 28, 2025 pm 05:29 PM

ChatGPT 4 is currently available and widely used, demonstrating significant improvements in understanding context and generating coherent responses compared to its predecessors like ChatGPT 3.5. Future developments may include more personalized interactions and real-time data processing capabilities, further enhancing its potential for various applications.

Which AI is better than ChatGPT? Which AI is better than ChatGPT? Mar 18, 2025 pm 06:05 PM

The article discusses AI models surpassing ChatGPT, like LaMDA, LLaMA, and Grok, highlighting their advantages in accuracy, understanding, and industry impact.(159 characters)

How to Use Mistral OCR for Your Next RAG Model How to Use Mistral OCR for Your Next RAG Model Mar 21, 2025 am 11:11 AM

Mistral OCR: Revolutionizing Retrieval-Augmented Generation with Multimodal Document Understanding Retrieval-Augmented Generation (RAG) systems have significantly advanced AI capabilities, enabling access to vast data stores for more informed respons

Best AI Chatbots Compared (ChatGPT, Gemini, Claude & More) Best AI Chatbots Compared (ChatGPT, Gemini, Claude & More) Apr 02, 2025 pm 06:09 PM

The article compares top AI chatbots like ChatGPT, Gemini, and Claude, focusing on their unique features, customization options, and performance in natural language processing and reliability.

See all articles