Hooks
useVector

useVector Hook

Introduction

useVector is a custom React hook that simplifies interactions with the OpenAI vector store API. This hook provides a set of functions to manage vector stores, including creating, listing, retrieving, modifying, and deleting stores. It also handles API errors and provides an easy way to incorporate these functionalities into your React application.

Usage

To use the useVector hook in your component, first import the hook and initialize it with your OpenAI API key. You can then use the returned functions to interact with the vector store API.

import React, { useState } from "react";
import {useVector} from "use-ai-hooks";
 
const VectorComponent = () => {
  const [storeName, setStoreName] = useState("");
  const {
    error,
    createStore,
    listVectorStore,
    retrieveVectorStore,
    modifyVectorStore,
    deleteVectorStore,
  } = useVector("YOUR_API_KEY_HERE");
 
  const handleCreateStore = async () => {
    try {
      const newStore = await createStore(storeName);
      console.log("New store created:", newStore);
      // Perform any additional actions upon successful store creation
    } catch (error) {
      console.error("Error creating store:", error);
    }
  };
 
  const handleListStores = async () => {
    try {
      const stores = await listVectorStore();
      console.log("Vector stores:", stores);
      // Update component state or perform other actions with the list of stores
    } catch (error) {
      console.error("Error listing stores:", error);
    }
  };
 
  // Additional functions to handle other API interactions...
 
  return (
    <div>
      <h2>Vector Store Management</h2>
      <div>
        <label htmlFor="storeName">Store Name:</label>
        <input
          type="text"
          id="storeName"
          value={storeName}
          onChange={(e) => setStoreName(e.target.value)}
        />
        <button onClick={handleCreateStore}>Create Store</button>
      </div>
      <div>
        <button onClick={handleListStores}>List Stores</button>
      </div>
      {/* Add UI elements for other API interactions if needed */}
      {error && <p>Error: {error.message}</p>}
    </div>
  );
};
 
export default VectorComponent;

API Reference

Parameters

  • apiKey (string): The OpenAI API key used for authentication.

Returns

An object containing the following methods:

  • createStore(name: string) => Promise<any>: Creates a new vector store with the specified name.

    • name (string): The name of the vector store to be created.
    • Returns a Promise that resolves to the created vector store object.
  • listVectorStore() => Promise<any>: Retrieves a list of all vector stores.

    • Returns a Promise that resolves to an array of vector store objects.
  • retrieveVectorStore(storeId: string) => Promise<any>: Retrieves information about a specific vector store.

    • storeId (string): The ID of the vector store to retrieve information for.
    • Returns a Promise that resolves to the vector store object.
  • modifyVectorStore(storeId: string, name: string) => Promise<any>: Modifies the name of a vector store.

    • storeId (string): The ID of the vector store to modify.
    • name (string): The new name for the vector store.
    • Returns a Promise that resolves to the modified vector store object.
  • deleteVectorStore(storeId: string) => Promise<any>: Deletes a vector store.

    • storeId (string): The ID of the vector store to delete.
    • Returns a Promise that resolves when the vector store is successfully deleted.
  • error: A state variable that holds any API errors encountered during requests.

Hook

import { useCallback, useState } from "react";
import axios from "axios";
 
interface APIError {
  message: string;
}
const useVector = (apiKey: string) => {
  const [error, setError] = useState<APIError>();
  const apiRequest = useCallback(
    async (method: string, url: string, data?: any) => {
      try {
        
        const headers = {
          Authorization: `Bearer ${apiKey}`,
          "Content-Type": "application/json",
          "OpenAI-Beta": "assistants=v2",
        };
       
        const result = await axios({
          method,
          url,
          headers,
          data,
        });
        return result.data;
      } catch (err: any) {
        setError({ message: err.message });
        return err;
      }
    },
    []
  );
 
  const createStore = async (name: string) => {
    return await apiRequest("post", "https://api.openai.com/v1/vector_stores", {
      name,
    });
  };
 
  const listVectorStore = async () => {
    return await apiRequest("get", "https://api.openai.com/v1/vector_stores");
  };
 
  const retrieveVectorStore = async (storeId: string) => {
    return await apiRequest(
      "get",
      `https://api.openai.com/v1/vector_stores/${storeId}`
    );
  };
 
  const modifyVectorStore = async (storeId: string, name: string) => {
    return await apiRequest(
      "post",
      `https://api.openai.com/v1/vector_stores/${storeId}`,
      {
        name,
      }
    );
  };
 
  const deleteVectorStore = async (storeId: string) => {
    return await apiRequest(
      "delete",
      `https://api.openai.com/v1/vector_stores/${storeId}`
    );
  };
 
  return {
    error,
    createStore,
    listVectorStore,
    retrieveVectorStore,
    modifyVectorStore,
    deleteVectorStore,
  };
};
 
export default useVector;