AIHelper Documentation

A comprehensive guide to the AIHelper Documentation

AIHelper Documentation

The AIHelper class provides methods for integrating various AI services and models into applications.

Features

Dependencies



Methods

GenerateText

public static async Task GenerateText(
    string prompt,
    AIModel model,
    Dictionary parameters = null)

Generates text using specified AI model.

Parameters:

Returns:

Example:

var response = await AIHelper.GenerateText(
    "Write a product description for a smartwatch",
    AIModel.GPT4,
    new Dictionary
    {
        { "temperature", 0.7 },
        { "maxTokens", 500 }
    }
);

GenerateImage

public static async Task GenerateImage(
    string prompt,
    ImageSize size,
    ImageStyle style)

Generates an image from text description.

Parameters:

Returns:

Example:

var imageBytes = await AIHelper.GenerateImage(
    "A futuristic city at sunset",
    ImageSize.Large,
    ImageStyle.Realistic
);

TranslateText

public static async Task TranslateText(
    string text,
    string targetLanguage,
    string sourceLanguage = null)

Translates text to target language.

Parameters:

Returns:

Example:

var translated = await AIHelper.TranslateText(
    "Hello, world!",
    "es",
    "en"
);

GetTextEmbedding

public static async Task GetTextEmbedding(
    string text,
    EmbeddingModel model)

Generates text embeddings for semantic search.

Parameters:

Returns:

Example:

var embedding = await AIHelper.GetTextEmbedding(
    "Sample text for embedding",
    EmbeddingModel.Ada
);

AnalyzeSentiment

public static async Task AnalyzeSentiment(
    string text,
    string language = "en")

Analyzes text sentiment.

Parameters:

Returns:

Example:

var sentiment = await AIHelper.AnalyzeSentiment(
    "Great product, highly recommended!",
    "en"
);

Supporting Types

AIModel

public enum AIModel
{
    GPT4,
    GPT35Turbo,
    Claude2,
    PaLM2,
    Llama2
}

ImageSize

public enum ImageSize
{
    Small,    // 256x256
    Medium,   // 512x512
    Large,    // 1024x1024
    Custom    // Custom dimensions
}

SentimentResult

public class SentimentResult
{
    public float PositiveScore { get; set; }
    public float NegativeScore { get; set; }
    public float NeutralScore { get; set; }
    public string Sentiment { get; set; }
    public Dictionary Emotions { get; set; }
}

Common Use Cases

  1. Content Generation
public class ContentGenerator
{
    private readonly AIHelper _aiHelper;
    private readonly Dictionary _defaultParams;

    public async Task GenerateArticle(string topic, int wordCount)
    {
        var prompt = $"Write an article about {topic}. " +
                    $"The article should be approximately {wordCount} words.";

        return await AIHelper.GenerateText(
            prompt,
            AIModel.GPT4,
            new Dictionary
            {
                { "temperature", 0.8 },
                { "maxTokens", wordCount * 2 }
            }
        );
    }

    public async Task> GenerateSocialPosts(
        string product,
        int count)
    {
        var posts = new List();
        for (int i = 0; i < count; i++)
        {
            var prompt = $"Write an engaging social media post about {product}";
            var post = await AIHelper.GenerateText(
                prompt,
                AIModel.GPT35Turbo
            );
            posts.Add(post);
        }
        return posts;
    }
}
  1. Multilingual Support
public class LanguageProcessor
{
    public async Task> TranslateToMultipleLanguages(
        string text,
        List targetLanguages)
    {
        var translations = new Dictionary();
        
        foreach (var language in targetLanguages)
        {
            var translated = await AIHelper.TranslateText(
                text,
                language
            );
            translations[language] = translated;
        }

        return translations;
    }

    public async Task> AnalyzeMultilingualSentiment(
        Dictionary texts)
    {
        var results = new Dictionary();
        
        foreach (var (language, text) in texts)
        {
            var sentiment = await AIHelper.AnalyzeSentiment(
                text,
                language
            );
            results[language] = sentiment;
        }

        return results;
    }
}
  1. Semantic Search
public class SemanticSearchEngine
{
    private readonly List<(string Text, float[] Embedding)> _documents;

    public async Task IndexDocument(string text)
    {
        var embedding = await AIHelper.GetTextEmbedding(
            text,
            EmbeddingModel.Ada
        );
        _documents.Add((text, embedding));
    }

    public async Task> Search(string query, int topK = 5)
    {
        var queryEmbedding = await AIHelper.GetTextEmbedding(
            query,
            EmbeddingModel.Ada
        );

        return _documents
            .OrderByDescending(doc => 
                CosineSimilarity(queryEmbedding, doc.Embedding))
            .Take(topK)
            .Select(doc => doc.Text)
            .ToList();
    }
}

Performance Considerations

Error Handling

Best Practices

  1. Model Management
public class ModelManager
{
    private readonly Dictionary _tokenLimits;
    private readonly Dictionary _costPerToken;

    public async Task GenerateWithCostControl(
        string prompt,
        decimal maxCost)
    {
        var model = SelectModelForBudget(maxCost);
        var tokenEstimate = EstimateTokens(prompt);
        
        if (EstimateCost(model, tokenEstimate) > maxCost)
        {
            throw new CostLimitExceededException();
        }

        return await AIHelper.GenerateText(
            prompt,
            model,
            new Dictionary
            {
                { "maxTokens", tokenEstimate }
            }
        );
    }
}
  1. Content Moderation
public class ContentModerator
{
    public async Task IsContentSafe(string text)
    {
        var moderationResult = await AIHelper.ModerateContent(text);
        
        return !moderationResult.Any(category => 
            category.Value > 0.5f);
    }

    public async Task GenerateSafeContent(string prompt)
    {
        var content = await AIHelper.GenerateText(
            prompt,
            AIModel.GPT4,
            new Dictionary
            {
                { "safe_mode", true }
            }
        );

        if (!await IsContentSafe(content))
        {
            throw new UnsafeContentException();
        }

        return content;
    }
}
  1. Resource Optimization
public class AIResourceOptimizer
{
    private readonly ConcurrentDictionary _embeddingCache;
    private readonly SemaphoreSlim _rateLimiter;

    public async Task GetCachedEmbedding(string text)
    {
        var hash = ComputeHash(text);
        
        if (_embeddingCache.TryGetValue(hash, out var cached))
        {
            return cached;
        }

        await _rateLimiter.WaitAsync();
        try
        {
            var embedding = await AIHelper.GetTextEmbedding(
                text,
                EmbeddingModel.Ada
            );
            _embeddingCache[hash] = embedding;
            return embedding;
        }
        finally
        {
            _rateLimiter.Release();
        }
    }
}

Legal Disclaimer

This documentation and associated helper scripts are provided "as is" without warranty of any kind, either express or implied.

  1. The code examples and helper functions are for illustrative purposes only.
  2. Users should thoroughly test any implementation in their specific environment.
  3. The authors are not responsible for any issues or damages arising from the use of these scripts.
  4. Always follow security best practices and your organization's coding guidelines.