Callbacks

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
};

Last updated