Visione

Analisi delle immagini ed elaborazione dei documenti per interazioni multimodali

Panoramica#

Il sistema Vision permette agli agent di elaborare e analizzare immagini, fornendo capacità AI multimodali per interazioni più ricche. Supporta più formati di immagine, offre varie modalità di analisi e si integra perfettamente con i provider OpenAI, Claude, Gemini e Ollama locale per opzioni di deployment flessibili.

Abilitare la Vision#

Abilita le capacità di visione per un agent impostando l'opzione vision su true:

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

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

Sistema di allegati#

Astreus supporta un sistema di allegati intuitivo per lavorare con le immagini:

typescript
// 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' }
  ]
});

Il sistema di allegati automaticamente:

  • Rileva il tipo di file e seleziona gli strumenti appropriati
  • Arricchisce il prompt con le informazioni dell'allegato
  • Abilita l'utilizzo degli strumenti quando sono presenti allegati

Capacità Vision#

Il sistema di visione fornisce tre capacità principali tramite strumenti integrati:

1. Analisi generale delle immagini#

Analizza le immagini con prompt personalizzati e livelli di dettaglio configurabili:

typescript
// 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. Descrizione delle immagini#

Genera descrizioni strutturate per diversi casi d'uso:

typescript
// 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. Estrazione del testo (OCR)#

Estrai e trascrivi il testo dalle immagini:

typescript
// 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);

Formati supportati#

Il sistema di visione supporta questi formati di immagine:

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

Sorgenti di input#

Percorsi di file#

Analizza immagini dal file system locale:

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

Dati Base64#

Analizza immagini da dati codificati in base64:

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

Configurazione#

Configurazione del modello Vision#

Specifica il modello vision direttamente nella configurazione dell'agent:

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

Variabili d'ambiente#

bash
# 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

Il sistema di visione seleziona automaticamente il provider appropriato in base al visionModel specificato nella configurazione dell'agent.

Opzioni di analisi#

Configura il comportamento dell'analisi con queste opzioni:

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

Esempi di utilizzo#

Analisi degli screenshot#

typescript
const agent = await Agent.create({
  name: 'UIAnalyzer',
  model: 'gpt-6-astra',
  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);

Elaborazione dei documenti#

typescript
// 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');

Conversazioni multimodali#

typescript
// 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"
);

Confronto tra provider#

FunzionalitàOpenAI (gpt-4o)Claude (claude-sonnet-5)Gemini (gemini-1.5-pro)Ollama (llava)
Qualità dell'analisiEccellenteEccellenteEccellenteBuona
Velocità di elaborazioneVeloceVeloceVeloceVariabile
CostoA consumoA consumoA consumoGratuito (locale)
PrivacyBasato su cloudBasato su cloudBasato su cloudElaborazione locale
Livelli di dettaglioBasso/Alto/AutoStandardStandardStandard
Supporto linguisticoEstesoEstesoEstesoBuono

Provider OpenAI#

  • Ideale per: applicazioni di produzione che richiedono elevata precisione
  • Modello predefinito: gpt-4o-mini
  • Funzionalità: controllo del livello di dettaglio, eccellente riconoscimento del testo

Provider Claude#

  • Ideale per: analisi sfumate e descrizioni dettagliate
  • Modello predefinito: Nessuno. Imposta visionModel in modo esplicito, ad esempio claude-sonnet-5
  • Funzionalità: ragionamento solido, eccellente comprensione del contesto

Provider Gemini#

  • Ideale per: task multimodali e analisi di documenti
  • Modello predefinito: gemini-1.5-pro
  • Funzionalità: supporto per contesti lunghi, adatto a immagini complesse

Provider Ollama (locale)#

  • Ideale per: applicazioni sensibili alla privacy o sviluppo
  • Modello predefinito: llava
  • Funzionalità: elaborazione locale, nessun costo API, funzionamento offline

Elaborazione in batch#

Elabora più immagini in modo efficiente:

typescript
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);

Strumenti Vision integrati#

Quando la visione è abilitata, questi strumenti sono automaticamente disponibili:

analyze_image#

  • Parametri:
    • image_path (string, obbligatorio): percorso del file immagine
    • prompt (string, opzionale): prompt di analisi personalizzato
    • detail (string, opzionale): livello di dettaglio 'low' o 'high'

describe_image#

  • Parametri:
    • image_path (string, obbligatorio): percorso del file immagine
    • style (string, opzionale): stile della descrizione ('detailed', 'concise', 'accessibility', 'technical')

extract_text_from_image#

  • Parametri:
    • image_path (string, obbligatorio): percorso del file immagine
    • language (string, opzionale): suggerimento sulla lingua per una migliore precisione OCR

Tipi di risposta#

I metodi Vision restituiscono risposte in forma di stringa contenenti i risultati dell'analisi.

Risposta di Analyze Image#

L'analisi dell'immagine restituisce una stringa descrittiva basata sul tuo prompt:

typescript
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."

Risposta di Describe Image#

Describeimage restituisce una stringa di descrizione formattata:

typescript
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."

Risposta di Extract Text from Image#

L'OCR restituisce il testo estratto come stringa:

typescript
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"

Risposta di Analyze Image from Base64#

Anche l'analisi delle immagini in base64 restituisce una stringa:

typescript
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."