Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using OpenAI API for Data Analysis

Introduction

This tutorial demonstrates how to utilize the OpenAI API for data analysis with various file formats (Excel, CSV, PDF, JSON). It covers integrating the API, analyzing data from different file types, and plotting trends.

API Setup

Before starting, ensure you have an API key from OpenAI. Replace YOUR_API_KEY with your actual API key in the examples below.

JavaScript Example

Using OpenAI API for Data Analysis in JavaScript

Example of performing data analysis tasks using the OpenAI API in JavaScript with different file formats.

Example Code

// Example in JavaScript

const axios = require('axios');
const fs = require('fs');

const API_KEY = 'YOUR_API_KEY';

// Function to analyze data from Excel, CSV, PDF, JSON
const analyzeData = async (file) => {
    let fileData = await fs.promises.readFile(file);
    let requestData = {
        model: "text-davinci-002",
        file: fileData.toString('base64'), // Convert file to base64
        max_tokens: 150
    };

    try {
        const response = await axios.post('https://api.openai.com/v1/completions', requestData, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${API_KEY}`
            }
        });
        return response.data.choices[0].text.trim();
    } catch (error) {
        console.error('Error:', error.message);
        return 'Error occurred during analysis.';
    }
};

// Example usage
const fileToAnalyze = 'path/to/your/file.xlsx'; // Replace with your file path
analyzeData(fileToAnalyze).then(response => {
    console.log('Analysis Result:', response);
});
                    

Plotting Trends in JavaScript

Example of plotting trends after data analysis using a JavaScript library.

Example Code

// Example of plotting trends with Chart.js
const data = {
    labels: ['January', 'February', 'March', 'April', 'May'],
    datasets: [{
        label: 'Sales Data',
        data: [65, 59, 80, 81, 56],
        fill: false,
        borderColor: 'rgb(75, 192, 192)',
        tension: 0.1
    }]
};

const config = {
    type: 'line',
    data: data,
    options: {}
};

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, config);
                    
sales

Python Example

Using OpenAI API for Data Analysis in Python

Example of performing data analysis tasks using the OpenAI API in Python with different file formats.

Example Code

# Example in Python

import openai
import base64

API_KEY = 'YOUR_API_KEY'
openai.api_key = API_KEY

# Function to analyze data from Excel, CSV, PDF, JSON
def analyze_data(file):
    with open(file, "rb") as f:
        file_data = f.read()
    file_data_base64 = base64.b64encode(file_data).decode('utf-8')

    prompt = file_data_base64
    response = openai.Completion.create(
        engine="text-davinci-002",
        prompt=prompt,
        max_tokens=150
    )
    return response.choices[0].text.strip()

# Example usage
file_to_analyze = 'path/to/your/file.xlsx'  # Replace with your file path
analysis_result = analyze_data(file_to_analyze)
print('Analysis Result:', analysis_result)
                    

Plotting Trends in Python

Example of plotting trends after data analysis using a Python library.

Example Code

# Example of plotting trends with Matplotlib
import matplotlib.pyplot as plt

# Data for plotting
months = ['January', 'February', 'March', 'April', 'May']
sales_data = [65, 59, 80, 81, 56]

plt.plot(months, sales_data, marker='o', linestyle='-', color='b', label='Sales Data')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.title('Sales Trend')
plt.legend()
plt.grid(True)
plt.show()
                    
sales

Integration Tips

Tips for integrating OpenAI API into data analysis workflows:

  • Handle different file formats (Excel, CSV, PDF, JSON) by converting to base64 for API consumption.
  • Utilize appropriate libraries for plotting trends based on analysis results.
  • Experiment with different AI models and file types to optimize analysis and visualization.

Conclusion

Integrating OpenAI API for data analysis with various file formats enhances the capability to process and visualize data efficiently. By leveraging JavaScript and Python examples, developers can effectively integrate AI-driven analysis and visualization into applications.