Yes, you can integrate custom functions with OpenAI models (like GPT-4) to enable them to perform specific tasks or access external data. This is done via the Tools feature (formerly Function Calling), not directly adding the function code to the system prompt, but defining the function's schema so the model knows how to request its use. Here's how to do it:
1. Using the OpenAI API
You define the function's schema (name, description, parameters) in JSON, then pass it to the API via the tools parameter when making a chat completion request.
Example Workflow:
a. Define the Function Schema:
[
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for 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"],
"default": "fahrenheit"
}
},
"required": ["location"]
}
}
}
]
b. Call the API:
Include the schema in the tools parameter. The model will decide if it needs to call the function (or respond directly):
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
tools=YOUR_FUNCTION_SCHEMA,
tool_choice="auto" # Let the model decide to use the tool or not
)
c. Handle the Function Call:
If the model returns a tool_calls object (instead of a direct answer), extract the function name and parameters, run your actual function (e.g., call a weather API), then send the result back to the model as a tool message to get the final response.
2. Using the OpenAI Assistant UI
For no-code setup (via the OpenAI Platform):
- Go to the Assistants tab in the OpenAI dashboard.
- Create or edit an assistant.
- Under Tools, select Add function.
- Fill in the function details:
- Name (e.g.,
get_weather). - Description (explain what the function does).
- Parameters (use the UI form or paste a JSON schema like the one above).
- Name (e.g.,
- Save the assistant. When the assistant is used, it will request function calls as needed (you still need to handle the actual function execution in your backend).
Key Note
The OpenAI model does not execute the function directly. You must implement the function logic in your application (e.g., calling an external API, querying a database) and pass the result back to the model for it to generate a natural language response.
This approach lets you extend the model's capabilities to interact with real-world data or perform custom tasks!


作者声明:本文包含人工智能生成内容。