Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Entity Recognition using OpenAI API

Introduction

Entity recognition with the OpenAI API allows you to identify and classify entities within a text. This tutorial covers how to use the entity recognition endpoint effectively, its parameters, and examples in JavaScript and Python.

Endpoint Overview

The entity recognition endpoint leverages advanced AI models to identify and categorize entities such as names, dates, locations, and more within a given piece of text.

Using the Entity Recognition Endpoint

API Request

To recognize entities, send a POST request to the endpoint URL with your API key and the text.

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

{
    "prompt": "Identify the entities in the following text: 'OpenAI, founded in San Francisco, is a leader in AI research.'",
    "max_tokens": 50
}
                    

In this example, entity recognition is performed on the text: "OpenAI, founded in San Francisco, is a leader in AI research."

API Response

The API responds with the recognized entities and their categories.

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

{
    "choices": [
        {
            "text": "\nEntities:\n- Organization: OpenAI\n- Location: San Francisco",
            "index": 0,
            "logprobs": null,
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 20,
        "completion_tokens": 25,
        "total_tokens": 45
    }
}
                    

The response includes the recognized entities and their categories, such as organizations and locations.

Parameters

Here are some common parameters you can use with the entity recognition endpoint:

  • prompt: The text for which you want to identify entities.
  • max_tokens: The maximum number of tokens to generate in the response.

Examples in JavaScript

Here's how you can use the entity recognition endpoint in JavaScript:

const axios = require('axios');

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

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

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

recognizeEntities('OpenAI, founded in San Francisco, is a leader in AI research.');
                

Examples in Python

Here's how you can use the entity recognition endpoint in Python:

import requests
import json

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

def recognize_entities(text):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    data = {
        'prompt': f"Identify the entities in the following text: '{text}'",
        'max_tokens': 50
    }

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

recognize_entities('OpenAI, founded in San Francisco, is a leader in AI research.');
                

Conclusion

The entity recognition endpoint in the OpenAI API provides a powerful tool to identify and classify entities within a given text. By understanding its usage, parameters, and seeing examples in JavaScript and Python, you can integrate entity recognition seamlessly into various applications for better understanding of textual data.