useTextToVectors Hook
Introduction
The useTextToVectors
custom hook facilitates the conversion of text to vectors using the OpenAI API within React applications. By utilizing this hook, developers can easily extract embeddings for textual data, which can be useful for various natural language processing tasks.
Installation
To use the useTextToVectors
hook in your React application, follow these installation steps:
-
Ensure that React is installed in your project.
-
Install the necessary dependencies:
npm install axios
Usage
import React, { useState } from 'react';
import {useTextToVectors} from 'use-ai-hooks'; // Import the custom hook
const TextToVectorsComponent = () => {
const [text, setText] = useState('');
const apiKey = 'YOUR_API_KEY'; // Your OpenAI API key
const { vectors, error, loading, convertToVectors } = useTextToVectors(apiKey);
const handleConvert = () => {
if (text) {
convertToVectors(text);
}
};
return (
<div>
<h1>Text to Vectors</h1>
<textarea
placeholder="Enter text to convert to vectors"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<button onClick={handleConvert} disabled={loading}>
Convert to Vectors
</button>
{loading && <p>Loading...</p>}
{error && <p>Error: {error.message}</p>}
{vectors && <div>
<h2>Vectors</h2>
<pre>{JSON.stringify(vectors, null, 2)}</pre>
</div>}
</div>
);
};
export default TextToVectorsComponent;
API Reference
Parameters
apiKey
(string): The API key required to authenticate requests to the OpenAI API.
Returns
An object with the following properties:
vectors
(any): The vectors obtained from the OpenAI API.error
(object | null): An object containing information about any errors that occurred during the API request.message
(string): A description of the error that occurred.
loading
(boolean): A boolean indicating whether the API request is currently in progress.convertToVectors(text: string)
: A function to convert the provided text to vectors using the OpenAI API.
Hook
import { useState } from "react";
import axios from "axios";
interface ApiError {
message: string;
}
const useTextToVectors = (apiKey: string) => {
const [vectors, setVectors] = useState<any | null>(null);
const [error, setError] = useState<ApiError | null>(null);
const [loading, setLoading] = useState<boolean>(false);
const convertToVectors = async (text: string) => {
setLoading(true);
setError(null);
try {
const response = await axios.post(
"https://api.openai.com/v1/embeddings",
{
model: "text-embedding-ada-002",
input: text,
encoding_format: "float",
},
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
}
);
setVectors(response || null);
return response;
} catch (err) {
if (axios.isAxiosError(err)) {
setError({ message: err.message });
return err;
} else {
setError({ message: "An unexpected error occurred" });
return err;
}
} finally {
setLoading(false);
}
};
return { vectors, error, loading, convertToVectors };
};
export default useTextToVectors;