OpenAI API Calls

Purpose

Demonstrate two chat OpenAI API calls that can be used in production: (1) Standard Chat Completion for natural-language output, and (2) Function/Tool Call for structured JSON (tool name + arguments). This page explores server-side HTTP requests to the GPT-4o-mini and displays the raw response. **Security note: API key loaded server-side from config outside web root.**

When to choose which:

  • Standard Chat Completion: When you need narrative text or loose JSON.
  • Function/Tool: When you need strict args + action execution.

Standard Chat Completion Call

A standard chat completion returns free-form text (you can request JSON-only for formatting but this does not select or execute tools). You ask a question and it answers in natural language. This is ideal for summaries, explanations, and content, but not for executing actions. If you need structure without tools, you can request JSON-only output and parse it yourself, but you won't get a named tool to run.

Output Format

  • Natural language
  • JSON-only (use a JSON-only response mode, still no tool selection)

Side Effects

  • None (you read it and decide what to do)

Use Cases

  • Summarize long documents, logs, or meetings into tight bullets.
  • Explain code, stack traces, or concepts in plain English.
  • Draft copy for emails, help text, release notes, documentation.
  • Transform text by rewriting the tone, translating, expanding, or condensing.
  • Light extraction/classification when perfect schema isn't required.

Code Example

Asks the model a question and prints the free-form answer.

PHP
            
              $payload = [
              "model" => "gpt-4o-mini",
              "messages" => [
                ["role" => "user", "content" => "Explain what a schema is in one sentence."]
                ]
              ];

              $ch = curl_init('https://api.openai.com/v1/chat/completions');
              curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_HTTPHEADER => [
                  'Authorization: Bearer ' . $API_KEY,
                  'Content-Type: application/json'
                ],
                CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_SLASHES),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30
              ]);

              $raw = curl_exec($ch);
              curl_close($ch);

              $res = json_decode($raw, true);
              echo htmlspecialchars($res['choices'][0]['message']['content'] ?? 'No content', ENT_QUOTES);
            
          

(Enter the access code on the Portfolio page to enable this button.)

Function/Tool Call

A function (tool) call returns a structured payload with function_call.name and function_call.arguments. (It is often called a tool call in newer documentation.) You define a JSON schema describing the tool and the model selects the tool and fills the arguments. Your server interprets that intent and runs code. This is the right choice for command-style actions and backends that require strict, predictable data. The key idea is that the model outputs intent + args and then your code performs the action.

Output Format

  • function_call.name + function_call.arguments (JSON)

Side Effects

  • Happen only after your code validates arguments against your schema

Use Cases

  • Execute actions via backend code such as creating tickets, querying DBs, calling third-party APIs, sending emails, and running CLI (Command Line Interface) tasks.
  • Fetch structured data with strict arguments (e.g., city, date, limit).
  • Validate inputs against a JSON schema before touching systems.
  • Orchestrate workflows where the model selects tools and passes precise arguments.

Code Example

Defines a tool schema and the model returns function_call.name + function_call.arguments.

PHP
            
                $functions = [[
                "name" => "get_current_weather",
                "description" => "Get the current weather in a given location",
                "parameters" => [
                  "type" => "object",
                  "properties" => [
                    "location" => ["type" => "string"],
                    "unit" => ["type" => "string", "enum" => ["celsius","fahrenheit"]]
                  ],
                  "required" => ["location"]
                ]
              ]];

              $payload = [
                "model" => "gpt-4o-mini",
                "messages" => [
                  ["role" => "user", "content" => "What's the weather like in Chicago in celsius?"]
                ],
                "functions" => $functions,
                "function_call" => "auto"
              ];

              $ch = curl_init('https://api.openai.com/v1/chat/completions');
              curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_HTTPHEADER => [
                  'Authorization: Bearer ' . $API_KEY,
                  'Content-Type: application/json'
                ],
                CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_SLASHES),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30
              ]);

              $raw = curl_exec($ch);
              curl_close($ch);

              $res = json_decode($raw, true);
              $msg = $res['choices'][0]['message'] ?? [];
              $fn  = $msg['function_call']['name'] ?? '(none)';
              $args = isset($msg['function_call']['arguments']) ? json_decode($msg['function_call']['arguments'], true) : null;

              echo '<strong>function_call.name:</strong> ' . htmlspecialchars($fn, ENT_QUOTES) . '<br>';
              echo '<strong>function_call.arguments:</strong> <pre>' . htmlspecialchars(json_encode($args, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES), ENT_QUOTES) . '</pre>';
            
          

(Enter the access code on the Portfolio page to enable this button.)