Astreus

Vision

Analyse d'images et traitement de documents pour des interactions multimodales Découvrez les schémas de configuration, les API et les exemples pratiques...

Analyse d'images et traitement de documents pour des interactions multimodales

Vue d'ensemble

Le système Vision permet aux agents de traiter et d'analyser des images, offrant des capacités d'IA multimodale pour des interactions plus riches. Il prend en charge plusieurs formats d'image, propose divers modes d'analyse, et s'intègre parfaitement avec les fournisseurs OpenAI, Claude, Gemini et Ollama local pour des options de déploiement flexibles.

Activer Vision

Activez les capacités Vision pour un agent en définissant l'option vision sur true :

import { Agent } from '@astreus-ai/astreus';

const agent = await Agent.create({
  name: 'VisionAgent',
  model: 'gpt-4o',  // Vision-capable model
  vision: true      // Enable vision capabilities (default: false)
});

Système de pièces jointes

Astreus prend en charge un système intuitif de pièces jointes pour travailler avec des images :

// Clean, modern attachment API
const response = await agent.ask("What do you see in this image?", {
  attachments: [
    { type: 'image', path: '/path/to/image.jpg', name: 'My Photo' }
  ]
});

Le système de pièces jointes effectue automatiquement les actions suivantes :

  • Détecte le type de fichier et sélectionne les outils appropriés
  • Enrichit l'invite avec les informations sur la pièce jointe
  • Active l'utilisation d'outils lorsque des pièces jointes sont présentes

Capacités Vision

Le système Vision offre trois capacités principales via des outils intégrés :

1. Analyse générale d'image

Analysez des images avec des invites personnalisées et des niveaux de détail configurables :

// Using attachments (recommended approach)
const response = await agent.ask("Please analyze this screenshot and describe the UI elements", {
  attachments: [
    { type: 'image', path: '/path/to/screenshot.png', name: 'UI Screenshot' }
  ]
});

// Using the analyze_image tool through conversation
const response2 = await agent.ask("Please analyze the image at /path/to/screenshot.png and describe the UI elements");

// Direct method call
const analysis = await agent.analyzeImage('/path/to/image.jpg', {
  prompt: 'What UI elements are visible in this interface?',
  detail: 'high',
  maxTokens: 1500
});

2. Description d'image

Générez des descriptions structurées pour différents cas d'usage :

// Accessibility-friendly description
const description = await agent.describeImage('/path/to/image.jpg', 'accessibility');

// Available styles:
// - 'detailed': Comprehensive description of all visual elements
// - 'concise': Brief description of main elements  
// - 'accessibility': Screen reader-friendly descriptions
// - 'technical': Technical analysis including composition and lighting

3. Extraction de texte (OCR)

Extrayez et transcrivez du texte à partir d'images :

// Extract text with language hint
const text = await agent.extractTextFromImage('/path/to/document.jpg', 'english');

// The system maintains original formatting and structure
console.log(text);

Formats pris en charge

Le système Vision prend en charge ces formats d'image :

  • JPEG (.jpg, .jpeg)
  • PNG (.png)
  • GIF (.gif)
  • BMP (.bmp)
  • WebP (.webp)

Sources d'entrée

1

Chemins de fichiers

Analysez des images depuis le système de fichiers local :

const result = await agent.analyzeImage('/path/to/image.jpg');
2

Données Base64

Analysez des images à partir de données encodées en base64 :

const base64Image = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...';
const result = await agent.analyzeImageFromBase64(base64Image);

Configuration

Configuration du modèle Vision

Spécifiez le modèle Vision directement dans la configuration de l'agent :

const agent = await Agent.create({
  name: 'VisionAgent',
  model: 'gpt-4o',
  visionModel: 'gpt-4o',  // Specify vision model here
  vision: true
});

Variables d'environnement

# API keys (auto-detected based on model)
OPENAI_API_KEY=your_openai_key               # For OpenAI models
OPENAI_VISION_API_KEY=your_openai_key        # Dedicated vision API key (takes priority)
ANTHROPIC_API_KEY=your_anthropic_key         # For Claude models
ANTHROPIC_VISION_API_KEY=your_anthropic_key  # Dedicated vision API key (takes priority)
GEMINI_API_KEY=your_gemini_key               # For Gemini models
GEMINI_VISION_API_KEY=your_gemini_key        # Dedicated vision API key (takes priority)

# Ollama configuration (local)
OLLAMA_BASE_URL=http://localhost:11434       # Default if not set

Le système Vision sélectionne automatiquement le fournisseur approprié en fonction du visionModel spécifié dans la configuration de l'agent.

Options d'analyse

Configurez le comportement de l'analyse avec ces options :

interface AnalysisOptions {
  prompt?: string;                    // Custom analysis prompt
  maxTokens?: number;                 // Response length limit (default: 1000)
  detail?: 'low' | 'high' | 'auto';   // Analysis detail level (OpenAI only)
}

Exemples d'utilisation

Analyse de capture d'écran

const agent = await Agent.create({
  name: 'UIAnalyzer',
  model: 'gpt-4o',
  vision: true
});

// Analyze a UI screenshot
const analysis = await agent.analyzeImage('/path/to/app-screenshot.png', {
  prompt: 'Analyze this mobile app interface. Identify key UI components, layout structure, and potential usability issues.',
  detail: 'high'
});

console.log(analysis);

Traitement de documents

// Extract text from scanned documents
const documentText = await agent.extractTextFromImage('/path/to/scanned-invoice.jpg', 'english');

// Generate accessible descriptions
const accessibleDesc = await agent.describeImage('/path/to/chart.png', 'accessibility');

Conversations multimodales

// Using attachments for cleaner API
const response = await agent.ask("I'm getting an error. Can you analyze this screenshot and help me fix it?", {
  attachments: [
    { type: 'image', path: '/Users/john/Desktop/error.png', name: 'Error Screenshot' }
  ]
});

// Multiple attachments
const response2 = await agent.ask("Compare these UI mockups and suggest improvements", {
  attachments: [
    { type: 'image', path: '/designs/mockup1.png', name: 'Design A' },
    { type: 'image', path: '/designs/mockup2.png', name: 'Design B' }
  ]
});

// Traditional approach (still works)
const response3 = await agent.ask(
  "Please analyze the error screenshot at /Users/john/Desktop/error.png and suggest how to fix the issue"
);

Comparaison des fournisseurs

FonctionnalitéOpenAI (gpt-4o)Claude (claude-3-5-sonnet)Gemini (gemini-1.5-pro)Ollama (llava)
Qualité d'analyseExcellenteExcellenteExcellenteBonne
Vitesse de traitementRapideRapideRapideVariable
CoûtPaiement à l'usagePaiement à l'usagePaiement à l'usageGratuit (local)
ConfidentialitéBasé sur le cloudBasé sur le cloudBasé sur le cloudTraitement local
Niveaux de détailFaible/Élevé/AutoStandardStandardStandard
Support des languesÉtenduÉtenduÉtenduBon

Fournisseur OpenAI

  • Idéal pour : applications de production nécessitant une haute précision
  • Modèle par défaut : gpt-4o
  • Fonctionnalités : contrôle du niveau de détail, excellente reconnaissance de texte

Fournisseur Claude

  • Idéal pour : analyse nuancée et descriptions détaillées
  • Modèle par défaut : claude-3-5-sonnet-20241022
  • Fonctionnalités : raisonnement solide, excellente compréhension du contexte

Fournisseur Gemini

  • Idéal pour : tâches multimodales et analyse de documents
  • Modèle par défaut : gemini-1.5-pro
  • Fonctionnalités : support de contexte long, adapté aux images complexes

Fournisseur Ollama (local)

  • Idéal pour : applications sensibles à la confidentialité ou développement
  • Modèle par défaut : llava
  • Fonctionnalités : traitement local, pas de coûts d'API, fonctionnement hors ligne

Traitement par lot

Traitez plusieurs images efficacement :

const images = [
  '/path/to/image1.jpg',
  '/path/to/image2.png',
  '/path/to/image3.gif'
];

// Process all images in parallel
const results = await Promise.all(
  images.map(imagePath => 
    agent.describeImage(imagePath, 'concise')
  )
);

console.log('Analysis results:', results);

// Or use task attachments for batch processing
const batchTask = await agent.createTask({
  prompt: 'Analyze all these images and provide a comparative report',
  attachments: images.map(path => ({
    type: 'image',
    path,
    name: path.split('/').pop()
  }))
});

const batchResult = await agent.executeTask(batchTask.id);

Outils Vision intégrés

Lorsque Vision est activé, ces outils sont automatiquement disponibles :

analyze_image

  • Paramètres :
    • image_path (string, requis) : chemin vers le fichier image
    • prompt (string, optionnel) : invite d'analyse personnalisée
    • detail (string, optionnel) : niveau de détail 'low' ou 'high'

describe_image

  • Paramètres :
    • image_path (string, requis) : chemin vers le fichier image
    • style (string, optionnel) : style de description ('detailed', 'concise', 'accessibility', 'technical')

extract_text_from_image

  • Paramètres :
    • image_path (string, requis) : chemin vers le fichier image
    • language (string, optionnel) : indication de langue pour une meilleure précision OCR

Types de réponse

Les méthodes Vision retournent des réponses sous forme de chaînes de caractères contenant les résultats d'analyse.

Réponse Analyze Image

L'analyse d'image retourne une chaîne descriptive basée sur votre invite :

const analysis = await agent.analyzeImage('/path/to/office.jpg', {
  prompt: "What objects are in this image and how is the space organized?",
  detail: "high"
});

// Response: string
"The image shows a modern office workspace with a MacBook Pro laptop, wireless keyboard, and mouse on a wooden desk. To the left is a coffee mug and a notebook. The desk is positioned near a window with natural lighting. The space features a minimalist organization with cable management and a small potted plant."

Réponse Describe Image

Describeimage retourne une chaîne de description formatée :

const description = await agent.describeImage('/path/to/product.jpg');

// Response: string
"A professional product photograph featuring a stainless steel water bottle with a matte black finish. The bottle has a wide mouth opening and is photographed against a white background with soft studio lighting creating subtle highlights along the curved surfaces."

Réponse Extract Text from Image

L'OCR retourne le texte extrait sous forme de chaîne de caractères :

const text = await agent.extractTextFromImage('/path/to/document.png', {
  language: 'en'
});

// Response: string
"INVOICE\nDate: January 15, 2024\nInvoice #: INV-2024-001\n\nBill To:\nAcme Corporation\n123 Main Street\nNew York, NY 10001\n\nDescription          Quantity    Price    Total\nProfessional Services    8 hrs    $150    $1,200\nConsulting Fee           1        $500    $500\n\nSubtotal: $1,700\nTax (8%): $136\nTotal: $1,836"

Réponse Analyze Image from Base64

L'analyse d'image en base64 retourne également une chaîne de caractères :

const base64Image = "data:image/png;base64,iVBORw0KG...";
const result = await agent.analyzeImageFromBase64(base64Image, {
  prompt: "Identify the main subject and mood of this image"
});

// Response: string
"The main subject is a sunset landscape with mountains in the background. The mood is serene and peaceful, with warm orange and pink tones dominating the sky. The composition creates a sense of tranquility and natural beauty."

Dernière mise à jour : 6 juillet 2026