Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Text Completion using OpenAI API

Introduction

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

Endpoint Overview

The text completion endpoint generates text continuation or completion based on the context provided in the prompt. It's useful for generating natural language responses and completing sentences.

Using the Text Completion Endpoint

API Request

To use the text completion 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": 50
}
                    

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

API Response

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

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

{
    "choices": [
        {
            "text": " there was a beautiful princess who lived in a castle."
        },
        {
            "text": " there lived a young boy named Jack who loved adventures."
        }
    ]
}
                    

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

Parameters

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

  • prompt: The starting text or context to complete.
  • 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 completion endpoint in JavaScript:

const axios = require('axios');

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

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

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

getTextCompletion('Once upon a time');
                

Examples in Python

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

import requests
import json

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

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

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

get_text_completion('Once upon a time')
                

Conclusion

The text completion endpoint in the OpenAI API is a powerful tool for generating natural language text based on provided prompts. By understanding its usage, parameters, and seeing examples in JavaScript and Python, you can integrate text completion functionality into various applications effectively.