Vision: Analyzing Images with AI

Send images to vision-capable models for analysis, description, and understanding. This example shows how to analyze an image from a URL using GPT-4o with high detail processing for better accuracy.
response, err := client.ChatCompletionRequest(context.Background(), &schemas.BifrostRequest{
	Provider: schemas.OpenAI,
	Model:    "gpt-4o", // Using vision-capable model
	Input: schemas.RequestInput{
		ChatCompletionInput: &[]schemas.BifrostMessage{
			{
				Role: schemas.ModelChatMessageRoleUser,
				Content: schemas.MessageContent{
					ContentBlocks: &[]schemas.ContentBlock{
						{
							Type: schemas.ContentBlockTypeText,
							Text: bifrost.Ptr("What do you see in this image? Please describe it in detail."),
						},
						{
							Type: schemas.ContentBlockTypeImage,
							ImageURL: &schemas.ImageURLStruct{
								URL:    "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
								Detail: bifrost.Ptr("high"), // Optional: can be "low", "high", or "auto"
							},
						},
					},
				},
			},
		},
	},
})

if err != nil {
	panic(err)
}

fmt.Println("Response:", *response.Choices[0].Message.Content.ContentStr)

Text-to-Speech: Converting Text to Audio

Convert text into natural-sounding speech using AI voice models. This example demonstrates generating an MP3 audio file from text using the “alloy” voice. The result is saved to a local file for playback.
response, err := client.SpeechRequest(context.Background(), &schemas.BifrostRequest{
	Provider: schemas.OpenAI,
	Model:    "tts-1", // Using text-to-speech model
	Input: schemas.RequestInput{
		SpeechInput: &schemas.SpeechInput{
			Input: "Hello! This is a sample text that will be converted to speech using Bifrost's speech synthesis capabilities. The weather today is wonderful, and I hope you're having a great day!",
			VoiceConfig: schemas.SpeechVoiceInput{
				Voice: bifrost.Ptr("alloy"),
			},
			ResponseFormat: "mp3",
		},
	},
})

if err != nil {
	panic(err)
}

// Handle speech synthesis response
if response.Speech != nil && len(response.Speech.Audio) > 0 {
	// Save the audio to a file
	filename := "output.mp3"
	err := os.WriteFile("output.mp3", response.Speech.Audio, 0644)
	if err != nil {
		panic(fmt.Sprintf("Failed to save audio file: %v", err))
	}

	fmt.Printf("Speech synthesis successful! Audio saved to %s, file size: %d bytes\n", filename, len(response.Speech.Audio))
}

Speech-to-Text: Transcribing Audio Files

Convert audio files into text using AI transcription models. This example shows how to transcribe an MP3 file using OpenAI’s Whisper model, with an optional context prompt to improve accuracy.
// Read the audio file for transcription
audioFilename := "output.mp3"
audioData, err := os.ReadFile(audioFilename)
if err != nil {
	panic(fmt.Sprintf("Failed to read audio file %s: %v. Please make sure the file exists.", audioFilename, err))
}

fmt.Printf("Loaded audio file %s (%d bytes) for transcription...\n", audioFilename, len(audioData))

response, err := client.TranscriptionRequest(context.Background(), &schemas.BifrostRequest{
	Provider: schemas.OpenAI,
	Model:    "whisper-1", // Using Whisper model for transcription
	Input: schemas.RequestInput{
		TranscriptionInput: &schemas.TranscriptionInput{
			File:   audioData,
			Prompt: bifrost.Ptr("This is a sample audio transcription from Bifrost speech synthesis."), // Optional: provide context
		},
	},
})

if err != nil {
	panic(err)
}

fmt.Printf("Transcription Result: %s\n", response.Transcribe.Text)

Advanced Vision Examples

Multiple Images

Send multiple images in a single request for comparison or analysis. This is useful for comparing products, analyzing changes over time, or understanding relationships between different visual elements.
response, err := client.ChatCompletionRequest(context.Background(), &schemas.BifrostRequest{
	Provider: schemas.OpenAI,
	Model:    "gpt-4o",
	Input: schemas.RequestInput{
		ChatCompletionInput: &[]schemas.BifrostMessage{
			{
				Role: schemas.ModelChatMessageRoleUser,
				Content: schemas.MessageContent{
					ContentBlocks: &[]schemas.ContentBlock{
						{
							Type: schemas.ContentBlockTypeText,
							Text: bifrost.Ptr("Compare these two images. What are the differences?"),
						},
						{
							Type: schemas.ContentBlockTypeImage,
							ImageURL: &schemas.ImageURLStruct{
								URL: "https://example.com/image1.jpg",
							},
						},
						{
							Type: schemas.ContentBlockTypeImage,
							ImageURL: &schemas.ImageURLStruct{
								URL: "https://example.com/image2.jpg",
							},
						},
					},
				},
			},
		},
	},
})

Base64 Images

Process local images by encoding them as base64 data URLs. This approach is ideal when you need to analyze images stored locally on your system without uploading them to external URLs first.
// Read and encode image
imageData, err := os.ReadFile("local_image.jpg")
if err != nil {
	panic(err)
}
base64Image := base64.StdEncoding.EncodeToString(imageData)
dataURL := fmt.Sprintf("data:image/jpeg;base64,%s", base64Image)

response, err := client.ChatCompletionRequest(context.Background(), &schemas.BifrostRequest{
	Provider: schemas.OpenAI,
	Model:    "gpt-4o",
	Input: schemas.RequestInput{
		ChatCompletionInput: &[]schemas.BifrostMessage{
			{
				Role: schemas.ModelChatMessageRoleUser,
				Content: schemas.MessageContent{
					ContentBlocks: &[]schemas.ContentBlock{
						{
							Type: schemas.ContentBlockTypeText,
							Text: bifrost.Ptr("Analyze this image and describe what you see."),
						},
						{
							Type: schemas.ContentBlockTypeImage,
							ImageURL: &schemas.ImageURLStruct{
								URL:    dataURL,
								Detail: bifrost.Ptr("high"),
							},
						},
					},
				},
			},
		},
	},
})

Audio Configuration Options

Voice Selection for Speech Synthesis

OpenAI provides six distinct voice options, each with different characteristics. This example generates sample audio files for each voice so you can compare and choose the one that best fits your application.
// Available voices: alloy, echo, fable, onyx, nova, shimmer
voices := []string{"alloy", "echo", "fable", "onyx", "nova", "shimmer"}

for _, voice := range voices {
	response, err := client.SpeechRequest(context.Background(), &schemas.BifrostRequest{
		Provider: schemas.OpenAI,
		Model:    "tts-1",
		Input: schemas.RequestInput{
			SpeechInput: &schemas.SpeechInput{
				Input: fmt.Sprintf("This is the %s voice speaking.", voice),
				VoiceConfig: schemas.SpeechVoiceInput{
					Voice: bifrost.Ptr(voice),
				},
				ResponseFormat: "mp3",
			},
		},
	})
	
	if err == nil && response.Speech != nil {
		filename := fmt.Sprintf("sample_%s.mp3", voice)
		os.WriteFile(filename, response.Speech.Audio, 0644)
		fmt.Printf("Generated %s\n", filename)
	}
}

Audio Formats

Generate audio in different formats depending on your use case. MP3 for general use, Opus for web streaming, AAC for mobile apps, and FLAC for high-quality audio applications.
formats := []string{"mp3", "opus", "aac", "flac"}

for _, format := range formats {
	response, err := client.SpeechRequest(context.Background(), &schemas.BifrostRequest{
		Provider: schemas.OpenAI,
		Model:    "tts-1",
		Input: schemas.RequestInput{
			SpeechInput: &schemas.SpeechInput{
				Input:          "Testing different audio formats.",
				VoiceConfig:    schemas.SpeechVoiceInput{Voice: bifrost.Ptr("alloy")},
				ResponseFormat: format,
			},
		},
	})
	
	if err == nil && response.Speech != nil {
		filename := fmt.Sprintf("output.%s", format)
		os.WriteFile(filename, response.Speech.Audio, 0644)
	}
}

Transcription Options

Language Specification

Improve transcription accuracy by specifying the source language. This is particularly helpful for non-English audio or when the audio contains technical terms or specific domain vocabulary.
response, err := client.TranscriptionRequest(context.Background(), &schemas.BifrostRequest{
	Provider: schemas.OpenAI,
	Model:    "whisper-1",
	Input: schemas.RequestInput{
		TranscriptionInput: &schemas.TranscriptionInput{
			File:     audioData,
			Language: bifrost.Ptr("es"), // Spanish
			Prompt:   bifrost.Ptr("This is a Spanish audio recording about technology."),
		},
	},
})

Response Formats

Choose between simple text output or detailed JSON responses with timestamps. The verbose JSON format provides word-level and segment-level timing information, useful for creating subtitles or analyzing speech patterns.
// Text only
response, err := client.TranscriptionRequest(context.Background(), &schemas.BifrostRequest{
	Provider: schemas.OpenAI,
	Model:    "whisper-1",
	Input: schemas.RequestInput{
		TranscriptionInput: &schemas.TranscriptionInput{
			File:           audioData,
			ResponseFormat: bifrost.Ptr("text"),
		},
	},
})

// JSON with timestamps
response, err := client.TranscriptionRequest(context.Background(), &schemas.BifrostRequest{
	Provider: schemas.OpenAI,
	Model:    "whisper-1",
	Input: schemas.RequestInput{
		TranscriptionInput: &schemas.TranscriptionInput{
			File:           audioData,
			ResponseFormat: bifrost.Ptr("verbose_json"),
			TimestampGranularities: &[]string{"word", "segment"},
		},
	},
})

Provider Support

Different providers support different multimodal capabilities:
ProviderVisionText-to-SpeechSpeech-to-Text
OpenAI✅ GPT-4V, GPT-4o✅ TTS-1, TTS-1-HD✅ Whisper
Anthropic✅ Claude 3 Sonnet/Opus
Google Vertex✅ Gemini Pro Vision
Azure OpenAI✅ GPT-4V✅ Whisper

Next Steps