File size: 2,241 Bytes
1dbc34b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
 * Prompt building utilities for constructing prompts with images
 *
 * Provides standardized prompt building that:
 * - Combines text prompts with image attachments
 * - Handles content block array generation
 * - Optionally includes image paths in text
 * - Supports both vision and non-vision models
 */

import { convertImagesToContentBlocks, formatImagePathsForPrompt } from './image-handler.js';

/**
 * Content that can be either simple text or structured blocks
 */
export type PromptContent =
  | string
  | Array<{
      type: string;
      text?: string;
      source?: object;
    }>;

/**
 * Result of building a prompt with optional images
 */
export interface PromptWithImages {
  content: PromptContent;
  hasImages: boolean;
}

/**
 * Build a prompt with optional image attachments
 *
 * @param basePrompt - The text prompt
 * @param imagePaths - Optional array of image file paths
 * @param workDir - Optional working directory for resolving relative paths
 * @param includeImagePaths - Whether to append image paths to the text (default: false)
 * @returns Promise resolving to prompt content and metadata
 */
export async function buildPromptWithImages(
  basePrompt: string,
  imagePaths?: string[],
  workDir?: string,
  includeImagePaths: boolean = false
): Promise<PromptWithImages> {
  // No images - return plain text
  if (!imagePaths || imagePaths.length === 0) {
    return { content: basePrompt, hasImages: false };
  }

  // Build text content with optional image path listing
  let textContent = basePrompt;
  if (includeImagePaths) {
    textContent += formatImagePathsForPrompt(imagePaths);
  }

  // Build content blocks array
  const contentBlocks: Array<{
    type: string;
    text?: string;
    source?: object;
  }> = [];

  // Add text block if we have text
  if (textContent.trim()) {
    contentBlocks.push({ type: 'text', text: textContent });
  }

  // Add image blocks
  const imageBlocks = await convertImagesToContentBlocks(imagePaths, workDir);
  contentBlocks.push(...imageBlocks);

  // Return appropriate format
  const content: PromptContent =
    contentBlocks.length > 1 || contentBlocks[0]?.type === 'image' ? contentBlocks : textContent;

  return { content, hasImages: true };
}