Generator Public

Code #4322

RapidAPI GPT Chat Completion

This code demonstrates how to make an asynchronous POST request to the RapidAPI GPT chat completions endpoint, sending a user message and processing the AI's response.

Code
// main.js

/**
 * Asynchronously calls the RapidAPI GPT chat completions endpoint
 * with a predefined message and processes the response.
 *
 * @param {object} ctx - The context object (can be used for additional parameters or state).
 * @returns {Promise<object>} A promise that resolves to an object containing the AI's answer.
 * @throws {Error} Throws an error if the API request fails or returns a non-200 status.
 */
export default async function main(ctx) {
  // Retrieve the RapidAPI key from environment variables for secure access.
  // It's crucial not to hardcode API keys directly in the code.
  const apiKey = process.env.RAPIDAPI_KEY;

  // Define the URL for the RapidAPI GPT chat completions endpoint.
  const url = 'https://double-gpt.p.rapidapi.com/chat/completions';

  // Prepare the request body according to the API's specifications.
  // This includes the desired AI model and a list of messages.
  const data = {
    model: 'gpt-5',
    messages: [
      {
        role: 'user',
        content: 'How many days in 3 weeks.'
      }
    ]
  };

  // Execute the asynchronous HTTP POST request to the API.
  // The 'fetch' API is used for making network requests.
  const res = await fetch(url, {
    method: 'POST',
    headers: {
      // RapidAPI host and key headers are required for authentication.
      'x-rapidapi-key': apiKey,
      'x-rapidapi-host': 'double-gpt.p.rapidapi.com',
      // 'Content-Type' header indicates that the request body is JSON.
      'Content-Type': 'application/json'
    },
    // Convert the JavaScript object 'data' into a JSON string for the request body.
    body: JSON.stringify(data)
  });

  // Check if the HTTP response status indicates an error (e.g., 4xx or 5xx).
  if (!res.ok) {
    // If there's an error, throw an exception with the status code and response text.
    throw new Error(`Error: ${res.status} - ${await res.text()}`);
  }

  // Parse the JSON response body into a JavaScript object.
  const json = await res.json();

  // Extract the AI's answer from the parsed JSON response.
  // Uses optional chaining (?.) to safely access nested properties and nullish coalescing (??)
  // to provide 'null' if the content is not found.
  const answer = json.choices?.[0]?.message?.content ?? null;

  // Log the full raw response for debugging purposes.
  console.log('Resposta bruta:', JSON.stringify(json, null, 2));
  // Log just the extracted text answer.
  console.log('Só o texto:', answer);

  // Return the extracted answer.
  return { answer };
}
Prompt: export default async function main(ctx) { const apiKey = process.env.RAPIDAPI_KEY; const url = "https://double-gpt.p.rapidapi.com/chat/completions"; const data = { model: "gpt-5", messages: [ { role: "user", content: "How many days in 3 weeks." } ] }; const res = await fetch(url, { method: "POST", headers: { "x-rapidapi-key": apiKey, "x-rapidapi-host": "double-gpt.p.rapidapi.com", "Content-Type": "application/json" }, body: JSON.stringify(data) }); if (!res.ok) { throw new Error(`Erro: ${res.status} - ${await res.text()}`); } const json = await res.json(); const answer = json.choices?.[0]?.message?.content ?? null; console.log("Resposta bruta:", JSON.stringify(json, null, 2)); console.log("Só o texto:", answer); return { answer }; }