Skip to content
AJ-comp edited this page Apr 5, 2026 · 2 revisions

Basic Usage

This page covers the fundamental features of Mythosia.AI that have been available since v1.x and v2.x.

Installation

dotnet add package Mythosia.AI

For advanced LINQ operations with streams:

dotnet add package System.Linq.Async

Important Usage Notes

Required Using Statements

Many convenient features are implemented as extension methods and require specific using statements:

// Core models and enums
using Mythosia.AI.Models;        // AIModels, ChatBlock, etc.
using Mythosia.AI.Models.Enums;  // ActorRole, TemperaturePreset, etc.

// For MessageBuilder
using Mythosia.AI.Builders;

// For extension methods (IMPORTANT!)
using Mythosia.AI.Extensions;  // Required for:
                               // - BeginMessage()
                               // - WithSystemMessage()
                               // - WithTemperature()
                               // - WithMaxTokens()
                               // - AskOnceAsync()
                               // - StartNewConversation()
                               // - GetLastAssistantResponse()
                               // - And more...

// Add the namespace for the provider you are using:
using Mythosia.AI.Services.OpenAI;      // OpenAIService
using Mythosia.AI.Services.Anthropic;   // AnthropicService
using Mythosia.AI.Services.Google;      // GoogleAIService
using Mythosia.AI.Services.DeepSeek;    // DeepSeekService
using Mythosia.AI.Services.Perplexity;  // PerplexityService

// For advanced LINQ operations (optional)
using System.Linq;

Common Issue: If BeginMessage() or other extension methods don't appear in IntelliSense, make sure you have added using Mythosia.AI.Extensions; at the top of your file.

Quick Start

Basic Setup

using Mythosia.AI.Models;
using Mythosia.AI.Builders;
using Mythosia.AI.Extensions;
using Mythosia.AI.Services.OpenAI;
using System.Net.Http;

var httpClient = new HttpClient();
var aiService = new OpenAIService("your-api-key", httpClient);

Text-Only Queries

// Simple completion
string response = await aiService.GetCompletionAsync("What is AI?");

// With conversation history
await aiService.GetCompletionAsync("Tell me about machine learning");
await aiService.GetCompletionAsync("How does it differ from AI?"); // Remembers context

// One-off query (no history)
string quickAnswer = await aiService.AskOnceAsync("What time is it in Seoul?");

Streaming Responses

Modern IAsyncEnumerable Streaming (v2.1.0+)

// Basic streaming
await foreach (var chunk in aiService.StreamAsync("Explain quantum computing"))
{
    Console.Write(chunk);
}

// One-off streaming without affecting conversation history
await foreach (var chunk in aiService.StreamOnceAsync("Quick question"))
{
    Console.Write(chunk);
}

// With cancellation support
var cts = new CancellationTokenSource();
await foreach (var chunk in aiService.StreamAsync("Long explanation", cts.Token))
{
    Console.Write(chunk);
    if (chunk.Contains("enough")) cts.Cancel();
}

Traditional Callback Streaming

// Still supported for backward compatibility
await aiService.StreamCompletionAsync("Explain AI", 
    chunk => Console.Write(chunk));

Advanced Streaming with LINQ

// Requires: dotnet add package System.Linq.Async

// Take only first 100 chunks
var limitedResponse = await aiService
    .StreamAsync("Tell me a long story")
    .Take(100)
    .ToListAsync();

// Filter empty chunks
await foreach (var chunk in aiService
    .StreamAsync("Explain something")
    .Where(c => !string.IsNullOrWhiteSpace(c)))
{
    ProcessChunk(chunk);
}

// Collect full response
var fullText = await aiService
    .StreamAsync("Explain AI")
    .ToListAsync()
    .ContinueWith(t => string.Concat(t.Result));

Image Analysis (Multimodal)

Basic Image Analysis

// Analyze a single image
var description = await aiService.GetCompletionWithImageAsync(
    "What's in this image?", 
    "photo.jpg"
);

// Using image URL
var urlAnalysis = await aiService.GetCompletionWithImageUrlAsync(
    "Describe this image",
    "https://example.com/image.jpg"
);

Advanced Multimodal with MessageBuilder

// Compare multiple images using fluent API
var comparison = await aiService
    .BeginMessage()
    .AddText("What are the differences between these images?")
    .AddImage("before.jpg")
    .AddImage("after.jpg")
    .SendAsync();

// Stream image analysis
await foreach (var chunk in aiService
    .BeginMessage()
    .AddText("Describe this artwork in detail")
    .AddImage("painting.jpg")
    .WithHighDetail()
    .StreamAsync())
{
    Console.Write(chunk);
}

// One-off image query (doesn't affect conversation history)
var quickAnalysis = await aiService
    .BeginMessage()
    .AddText("What color is this?")
    .AddImage("sample.jpg")
    .SendOnceAsync();

Stateless Mode

// Enable stateless mode for all requests
aiService.StatelessMode = true;

// Each request is independent
await aiService.GetCompletionAsync("Translate: Hello");  // No history
await aiService.GetCompletionAsync("Translate: World");  // No history

// Or use one-off methods while maintaining conversation
aiService.StatelessMode = false;  // Back to normal

// These don't affect the conversation history
var oneOffResult = await aiService.AskOnceAsync("What time is it?");

await foreach (var chunk in aiService.StreamOnceAsync("Quick question"))
{
    Console.Write(chunk);
}

Fluent Message Building

// Build complex multimodal messages
var result = await aiService
    .BeginMessage()
    .WithRole(ActorRole.User)
    .AddText("Analyze this chart and explain the trend")
    .AddImage("sales-chart.png")
    .WithHighDetail()
    .SendAsync();

// Stream with fluent API
await foreach (var chunk in aiService
    .BeginMessage()
    .AddText("Compare these approaches:")
    .AddText("1. Traditional ML")
    .AddText("2. Deep Learning") 
    .AddImage("comparison.jpg")
    .StreamAsync())
{
    ProcessChunk(chunk);
}

// Using image URLs
var urlAnalysis = await aiService
    .BeginMessage()
    .AddText("What's in this image?")
    .AddImageUrl("https://example.com/image.jpg")
    .SendAsync();

Conversation Management

// Start fresh conversation
aiService.StartNewConversation();

// Start with different model
aiService.StartNewConversation(AIModels.Anthropic.ClaudeSonnet4_250514);

// Switch models mid-conversation
aiService.SwitchModel(AIModels.OpenAI.Gpt4o241120);

// Get conversation info
var summary = aiService.GetConversationSummary();
var lastResponse = aiService.GetLastAssistantResponse();

// Retry last message
var betterResponse = await aiService.RetryLastMessageAsync();

// Clear specific messages
aiService.ActivateChat.RemoveLastMessage();
aiService.ActivateChat.ClearMessages();

// Get completion with context from previous messages
var contextualResponse = await aiService.GetCompletionWithContextAsync(
    "Summarize our discussion",
    contextMessages: 5  // Include last 5 messages as context
);

Configuration

Method Chaining Configuration

// Configure service with fluent API
aiService
    .WithSystemMessage("You are a helpful coding assistant")
    .WithTemperature(0.7f)
    .WithMaxTokens(2000)
    .WithStatelessMode(false);

Direct Configuration

// Configure parameters directly on the service
aiService.Temperature = 0.5f;
aiService.TopP = 0.9f;
aiService.MaxTokens = 4096;
aiService.MaxMessageCount = 20;
aiService.FrequencyPenalty = 0.5f;
aiService.PresencePenalty = 0.5f;

// Change model
aiService.ChangeModel("gpt-4-turbo-preview");

// System message (via ActivateChat)
aiService.ActivateChat.SystemMessage = "You are a helpful assistant.";

Token Management

// Check tokens before sending
uint currentTokens = await aiService.GetInputTokenCountAsync();
if (currentTokens > 3000)
{
    aiService.MaxMessageCount = 10; // Reduce history
}

// Check tokens for specific prompt
uint promptTokens = await aiService.GetInputTokenCountAsync("Long prompt...");

// Configure max tokens
aiService.WithMaxTokens(2000);

Service-Specific Features

OpenAI Models

using Mythosia.AI.Services.OpenAI;

var openAIService = new OpenAIService(apiKey, httpClient);

// Use latest GPT-4o model (supports vision natively)
openAIService.ChangeModel(AIModels.OpenAI.Gpt4oLatest);

// Generate images
byte[] imageData = await openAIService.GenerateImageAsync(
    "A futuristic city at sunset",
    "1024x1024"
);

// Text-to-Speech
byte[] audioData = await openAIService.GetSpeechAsync(
    "Hello, world!", 
    voice: "alloy", 
    model: "tts-1"
);

// Speech-to-Text
string transcription = await openAIService.TranscribeAudioAsync(
    audioData, 
    "audio.mp3", 
    language: "en"
);

// Fine-tune parameters
openAIService.WithOpenAIParameters(
    presencePenalty: 0.6f,
    frequencyPenalty: 0.8f
);

Anthropic Claude Models

using Mythosia.AI.Services.Anthropic;

var claudeService = new AnthropicService(apiKey, httpClient);

// Use latest Claude models
claudeService.ChangeModel(AIModels.Anthropic.ClaudeSonnet4_250514);

// Temperature presets
claudeService.WithTemperaturePreset(TemperaturePreset.Creative);

// Token counting
uint tokens = await claudeService.GetInputTokenCountAsync();

// Download and process image from URL
var message = await claudeService.CreateMessageWithImageUrl(
    "Analyze this image",
    "https://example.com/image.jpg"
);

Google Gemini Models

using Mythosia.AI.Services.Google;

var geminiService = new GoogleAIService(apiKey, httpClient);

// Use latest Gemini models
geminiService.ChangeModel(AIModels.Google.Gemini2_5Pro);

// Configure parameters directly on the service
geminiService.Temperature = 0.7f;
geminiService.MaxTokens = 4096;

DeepSeek Models

using Mythosia.AI.Services.DeepSeek;

var deepSeekService = new DeepSeekService(apiKey, httpClient);

// Use Reasoner model for complex reasoning
deepSeekService.UseReasonerModel();

// Code generation mode
deepSeekService.WithCodeGenerationMode("python");

// Math mode
deepSeekService.WithMathMode();

// Chain of Thought prompting
var solution = await deepSeekService.GetCompletionWithCoTAsync(
    "Solve: 2x^2 + 5x - 3 = 0"
);

Perplexity Sonar Models

using Mythosia.AI.Services.Perplexity;

var sonarService = new PerplexityService(apiKey, httpClient);

// Use enhanced reasoning model
sonarService.UseSonarReasoning();

// Web search with citations
var searchResult = await sonarService.GetCompletionWithSearchAsync(
    "Recent developments in quantum computing",
    domainFilter: new[] { "arxiv.org", "nature.com" },
    recencyFilter: "month"
);

// Access citations
foreach (var citation in searchResult.Citations)
{
    Console.WriteLine($"{citation.Title}: {citation.Url}");
}

Error Handling

try
{
    await foreach (var chunk in aiService.StreamAsync(message))
    {
        Console.Write(chunk);
    }
}
catch (MultimodalNotSupportedException ex)
{
    Console.WriteLine($"Service {ex.ServiceName} doesn't support {ex.RequestedFeature}");
}
catch (TokenLimitExceededException ex)
{
    Console.WriteLine($"Too many tokens: {ex.RequestedTokens} > {ex.MaxTokens}");
}
catch (RateLimitExceededException ex)
{
    Console.WriteLine($"Rate limit hit. Retry after: {ex.RetryAfter}");
}
catch (AIServiceException ex)
{
    Console.WriteLine($"API Error: {ex.Message}");
    Console.WriteLine($"Details: {ex.ErrorDetails}");
}

Static Quick Methods

For one-off queries without managing service instances:

// Quick text query
var answer = await AIService.QuickAskAsync(
    apiKey, 
    "What's the capital of France?",
    AIModels.OpenAI.Gpt4oMini
);

// Quick image analysis
var description = await AIService.QuickAskWithImageAsync(
    apiKey,
    "Describe this image",
    "image.jpg",
    AIModels.OpenAI.Gpt4o240806
);

Model Support Matrix

Service Text Vision Audio Image Gen Web Search Streaming
OpenAI GPT-4o
OpenAI GPT-4o-mini
OpenAI GPT-5
Claude 4
Gemini 2.5
DeepSeek
Sonar

Available Models

OpenAI Models

  • GPT-5 Series: AIModels.OpenAI.Gpt5, AIModels.OpenAI.Gpt5Mini, AIModels.OpenAI.Gpt5Nano, AIModels.OpenAI.Gpt5ChatLatest
  • GPT-4.1 Series: AIModels.OpenAI.Gpt4_1, AIModels.OpenAI.Gpt4_1Mini, AIModels.OpenAI.Gpt4_1Nano
  • GPT-4o Series: AIModels.OpenAI.Gpt4oLatest, AIModels.OpenAI.Gpt4o, AIModels.OpenAI.Gpt4o241120, AIModels.OpenAI.Gpt4o240806, AIModels.OpenAI.Gpt4oMini
  • Legacy: AIModels.OpenAI.Gpt4Vision (deprecated)

Anthropic Claude Models

  • Claude 4.6: AIModels.Anthropic.ClaudeOpus4_6, AIModels.Anthropic.ClaudeSonnet4_6
  • Claude 4.5: AIModels.Anthropic.ClaudeOpus4_5_251101, AIModels.Anthropic.ClaudeSonnet4_5_250929, AIModels.Anthropic.ClaudeHaiku4_5_251001
  • Claude 4: AIModels.Anthropic.ClaudeOpus4_1_250805, AIModels.Anthropic.ClaudeOpus4_250514, AIModels.Anthropic.ClaudeSonnet4_250514

Google Gemini Models

  • Gemini 3 Series (Preview): AIModels.Google.Gemini3ProPreview, AIModels.Google.Gemini3FlashPreview
  • Gemini 2.5 Series: AIModels.Google.Gemini2_5Pro, AIModels.Google.Gemini2_5Flash, AIModels.Google.Gemini2_5FlashLite

DeepSeek Models

  • AIModels.DeepSeek.Chat, AIModels.DeepSeek.Reasoner

Perplexity Models

  • AIModels.Perplexity.Sonar, AIModels.Perplexity.SonarPro, AIModels.Perplexity.SonarReasoning

Best Practices

  1. Model Selection:

    • Use latest model versions for best performance and features
    • Use AIModels.OpenAI.Gpt4o models for vision tasks
    • Use AIModels.OpenAI.Gpt4oMini for cost-effective text tasks
  2. Streaming Best Practices:

    • Use StreamAsync() for better performance with long responses
    • Always handle cancellation tokens for user-initiated stops
    • Consider using StreamOnceAsync() for queries that don't need history
  3. Image Handling:

    • Keep images under 4MB
    • Supported formats: JPEG, PNG, GIF, WebP
    • Use WithHighDetail() for detailed analysis (costs more tokens)
    • For URLs, ensure they are publicly accessible
  4. Performance:

    • Reuse HttpClient instances
    • Monitor token usage to manage costs
    • Use streaming for long responses
    • Enable stateless mode for independent queries
  5. Error Handling:

    • Always wrap API calls in try-catch blocks
    • Check model capabilities before sending multimodal content
    • Handle rate limits gracefully with exponential backoff
    • Log errors for debugging