AIDevKit - AI Suite for Unity
API ReferencesDiscordGlitch9
  • Introduction
    • AI Dev Kit 3.7.0
    • Troubleshooting
    • FAQ
    • Update Logs
  • Provider Setup
    • API Key Setup
    • OpenAI
    • Google Gemini
    • ElevenLabs
    • Ollama
    • OpenRouter
  • Editor Tools
    • Introduction
    • Editor Chat
    • Model Library
    • Voice Library
  • GEN Tasks
    • Overview
    • Prefixes
    • Response
    • Chat
    • Image
    • Video
    • SoundFX
    • Speech
    • Transcript
    • Voice Change
    • Audio Isolation
  • Advanced API (Pro)
    • Assistants
      • How it works
      • Creating custom functions
      • Creating assistants API
    • Realtime
  • Legacy API
    • OpenAI
      • 💬Chat completions
      • 🖼️Image operations
      • 🗣️Text to speech
      • 🎙️Speech to text
        • Recording real-time in Unity
      • 💾Files
      • 🔎Embeddings
      • 🛡️Moderations
      • ⚙️Fine-tuning
    • Google Gemini
      • 📝System instructions
      • 💬Text generation
      • ⚙️Fine-tuning
      • ▶️Fucntion calling
      • 🔎Embeddings
      • 🛡️Safety
      • 💻Code execution
  • Legacy Documents
    • AI Dev Kit 1.0
      • Preperation
      • Scriptable Toolkits
        • Chat Streamer
        • Image Generator
        • Voice Transcriber
        • Voice Generator
      • Editor Tools
      • Troubleshooting (Legacy)
        • ❗Build Error: The name 'UnityMenu' does not exist in the current context
        • ❗The type or namespace name 'AndroidJavaObject' could not be found
        • ❗The type or namaspace name 'Plastic' does not exist
        • ❗Build Error: The name 'Asset Database' does not exist in the current context
        • ❗'ModelData.Create(Provider, string, UnixTime?, string)': not all code paths return a value
      • Code Generators
        • C# Script Generator
        • Unity Component Generator
    • AI Dev Kit 2.0
      • Event Handlers
      • Editor Chat
      • Editor Vision (TTI, ITI)
      • Editor Speech (TTS)
      • Management Tools
        • Prompt History Viewer
        • AI Model Manager
        • TTS Voice Manager
        • OpenAI File Manager
        • OpenAI Assistant Manager
        • ElevenLabs Voice Library
Powered by GitBook
On this page
  • TokenValidator
  • UsageHandler
  • ErrorHandler
  • Implementing Callbacks
  1. Legacy Documents
  2. AI Dev Kit 2.0

Event Handlers

In the context of the OpenAIClient class, callbacks are a pivotal mechanism for integrating real-time response handling, error management, and token validation into your application's workflow with the OpenAI API. Here's a detailed explanation of each callback type available within OpenAIClient and how they can be utilized to enhance your application's interaction with OpenAI services.

TokenValidator

public delegate bool TokenValidator(int tokens);
  • Purpose: This delegate is used to determine if the user has enough tokens to make a request to the OpenAI API. It's particularly useful in scenarios where you need to manage or monitor API usage to prevent exceeding quota limits.

  • Usage: Implement this callback to check the user's token balance before attempting an API call. If the balance is insufficient, you can prevent the request, thus avoiding potential errors or quota exceedances.

UsageHandler

public delegate void UsageHandler(GPTModel model, Usage usage);
  • Purpose: Post-request, this delegate allows you to handle or process the Usage data returned by the OpenAI API. It's essential for applications that need to track or report on the usage statistics of the OpenAI services, such as the number of tokens consumed by each request.

  • Usage: Use this callback to log usage data, update UI elements to reflect token consumption, or perform any necessary actions based on the response's Usage object.

ErrorHandler

public delegate void ErrorHandler(OpenAiError error);
  • Purpose: This delegate provides a centralized mechanism for handling errors that occur during API interaction. Implementing this callback is crucial for robust error management in your application, allowing for consistent logging, user notification, or automatic retry mechanisms.

  • Usage: Implement this callback to capture and process any errors returned by the OpenAI API or generated by the OpenAIClient itself. This could involve displaying error messages to the user, logging errors for later analysis, or attempting to recover from recoverable errors automatically.

Implementing Callbacks

Implementing these callbacks in your application involves assigning delegate methods to the corresponding properties of the OpenAIClient instance. Here's a brief example of how each callback can be implemented:

OpenAiClient client = OpenAIClient.DefaultInstance;

// Token validation
client.OnTokensValidated = (int tokens) =>
{
    return CheckUserTokenBalance(tokens); // Your method to check tokens
};

// Usage handling
client.OnTokensConsumed = (GPTModel model, Usage usage) =>
{
    LogUsageData(model, usage); // Your method to log or process usage data
};

// Error handling
client.OnError = (OpenAiError error) =>
{
    HandleApiError(error); // Your method to handle errors
};
PreviousAI Dev Kit 2.0NextEditor Chat