Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Text Generation using OpenAI API

Introduction

The text generation endpoint of the OpenAI API allows you to generate coherent and contextually relevant text based on given prompts. This tutorial covers how to use the text generation endpoint effectively, its parameters, and examples in JavaScript and Python.

Endpoint Overview

The text generation endpoint creates human-like text based on the input prompt and the selected model's knowledge. It's useful for generating creative writing, articles, and more.

Using the Text Generation Endpoint

API Request

To use the text generation endpoint, send a POST request to the endpoint URL with your API key and the prompt text.

POST /v1/engines/davinci/completions HTTP/1.1
Host: api.openai.com
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{
    "prompt": "Once upon a time",
    "max_tokens": 100
}
                    

In this example, a prompt "Once upon a time" is provided with a maximum token limit of 100 tokens.

API Response

The API responds with the generated text based on the provided prompt.

HTTP/1.1 200 OK
Content-Type: application/json

{
    "choices": [
        {
            "text": "Once upon a time, in a faraway kingdom, there lived a brave knight named Sir Richard."
        },
        {
            "text": "Once upon a time, there was a magical forest where the trees whispered secrets to each other."
        }
    ]
}
                    

The generated text is returned in the JSON response under the "choices" array.

Parameters

Here are some common parameters you can use with the text generation endpoint:

  • prompt: The starting text or context to generate from.
  • max_tokens: Maximum number of tokens (words) in the generated text.
  • temperature: Controls randomness in text generation (optional).
  • top_p: Controls diversity of generated responses (optional).

Examples in JavaScript

Here's how you can use the text generation endpoint in JavaScript:

const axios = require('axios');

const apiKey = 'YOUR_API_KEY';
const endpoint = 'https://api.openai.com/v1/engines/davinci/completions';

async function getTextGeneration(prompt) {
    try {
        const response = await axios.post(endpoint, {
            prompt: prompt,
            max_tokens: 100
        }, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            }
        });

        console.log(response.data.choices[0].text);
    } catch (error) {
        console.error('Error:', error);
    }
}

getTextGeneration('Once upon a time');
                

Examples in Python

Here's how you can use the text generation endpoint in Python:

import requests
import json

api_key = 'YOUR_API_KEY'
endpoint = 'https://api.openai.com/v1/engines/davinci/completions'

def get_text_generation(prompt):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    data = {
        'prompt': prompt,
        'max_tokens': 100
    }

    response = requests.post(endpoint, headers=headers, data=json.dumps(data))
    if response.status_code == 200:
        generation = response.json()['choices'][0]['text']
        print(generation)
    else:
        print(f"Error: {response.status_code}, {response.text}")

get_text_generation('Once upon a time')
                

Conclusion

The text generation endpoint in the OpenAI API is a powerful tool for creating human-like text based on given prompts. By understanding its usage, parameters, and seeing examples in JavaScript and Python, you can leverage text generation capabilities in various applications effectively.