Поддержка мультимодальности
Обработка изображений, аудио и текста с помощью LLM. Meridian поддерживает анализ изображений, генерацию изображений, синтез речи и транскрипцию аудио — поверх различных провайдеров.
Vision: анализ изображений
Отправляйте изображения в vision-модели для анализа, описания и понимания. В примере ниже изображение с публичного URL анализируется моделью GPT-4o с детализацией high — это даёт более качественный анализ за счёт большего числа токенов.
curl --location 'http://localhost:8080/v1/chat/completions' \
--header 'Content-Type: application/json' \
--data '{
"model": "openai/gpt-4o",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What do you see in this image? Please describe it in detail."
},
{
"type": "image_url",
"image_url": {
"url": "https://pub-cdead89c2f004d8f963fd34010c479d0.r2.dev/Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
"detail": "high"
}
}
]
}
]
}'Ответ содержит детальный разбор изображения:
{
"choices": [{
"message": {
"role": "assistant",
"content": "I can see a beautiful wooden boardwalk extending through a natural landscape..."
}
}]
}Image Generation: генерация изображений
Генерируйте изображения по текстовым запросам через OpenAI-совместимые модели генерации изображений.
Базовая генерация
Сгенерируйте изображение по текстовому запросу с помощью dall-e-3:
curl --location 'http://localhost:8080/v1/images/generations' \
--header 'Content-Type: application/json' \
--data '{
"model": "openai/dall-e-3",
"prompt": "A futuristic city skyline at sunset with flying cars",
"size": "1024x1024",
"response_format": "url"
}'Формат ответа:
{
"created": 1713833628,
"data": [
{
"url": "https://oaidalleapiprodscus.blob.core.windows.net/...",
"revised_prompt": "A futuristic city skyline at sunset featuring advanced architecture and flying vehicles.",
"index": 0
}
],
"background": "opaque",
"output_format": "png",
"quality": "standard",
"size": "1024x1024",
"usage": {
"input_tokens": 15,
"output_tokens": 1,
"total_tokens": 16
},
"extra_fields": {
"request_type": "image_generation",
"provider": "openai",
"model_requested": "dall-e-3",
"latency": 15265,
"chunk_index": 0
}
}Audio Understanding: анализ аудио
Если ваше чат-приложение поддерживает текстовый ввод, к нему можно добавить аудио-вход и аудио-выход — достаточно указать audio в modalities и использовать audio-модель, например gpt-4o-audio-preview.
Аудио-вход в модель
curl --location 'http://localhost:8080/v1/chat/completions' \
--header 'Content-Type: application/json' \
--data '{
"model": "openai/gpt-4o-audio-preview",
"modalities": ["text"],
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Please analyze this audio recording and summarize what was discussed."
},
{
"type": "input_audio",
"input_audio": {
"data": "<base64-encoded audio data containing the word 'Affirmative'>",
"format": "wav"
}
}
]
}
]
}'Аудио-вывод от модели
{
"choices": [
{
"index": 0,
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "The audio recording captured a brief segment where a speaker simply said \"Affirmative\" in response. There wasn't any detailed discussion or context provided beyond that one-word affirmation. If you have more audio or specific questions, feel free to share!"
}
}
]
}Text-to-Speech: синтез речи
Преобразуйте текст в естественно звучащую речь через TTS-модели. В примере MP3-файл генерируется голосом alloy. Бинарные аудио-данные возвращаются в теле ответа.
curl --location 'http://localhost:8080/v1/audio/speech' \
--header 'Content-Type: application/json' \
--data '{
"model": "openai/tts-1",
"input": "Hello! This is a sample text that will be converted to speech using Meridian speech synthesis capabilities. The weather today is wonderful, and I hope you are having a great day!",
"voice": "alloy",
"response_format": "mp3"
}' \
--output "output.mp3"Сохранение аудио в файл: флаг --output записывает бинарные аудио-данные напрямую в файл; размер файла зависит от длины входного текста.
Speech-to-Text: транскрипция аудио
Преобразуйте аудио-файлы в текст через модели транскрипции. В примере MP3-файл транскрибируется моделью OpenAI Whisper с опциональным подсказывающим контекстом для повышения точности.
curl --location 'http://localhost:8080/v1/audio/transcriptions' \
--form 'file=@"output.mp3"' \
--form 'model="openai/whisper-1"' \
--form 'prompt="This is a sample audio transcription from Meridian speech synthesis."'Формат ответа:
{
"text": "Hello! This is a sample text that will be converted to speech using Meridian speech synthesis capabilities. The weather today is wonderful, and I hope you are having a great day!"
}Расширенные сценарии vision
Несколько изображений
Отправляйте несколько изображений в одном запросе для сравнения или анализа. Подходит для сравнения товаров, отслеживания изменений во времени, анализа взаимосвязей между визуальными элементами.
curl --location 'http://localhost:8080/v1/chat/completions' \
--header 'Content-Type: application/json' \
--data '{
"model": "openai/gpt-4o",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Compare these two images. What are the differences?"
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image1.jpg"
}
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image2.jpg"
}
}
]
}
]
}'Изображения в base64
Обрабатывайте локальные изображения, кодируя их в base64 data URL. Подходит, когда нужно проанализировать локальный файл без публикации его на внешний URL.
# Кодируем локальное изображение в base64
base64_image=$(base64 -i local_image.jpg)
data_url="data:image/jpeg;base64,$base64_image"
curl --location 'http://localhost:8080/v1/chat/completions' \
--header 'Content-Type: application/json' \
--data '{
"model": "openai/gpt-4o",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Analyze this image and describe what you see."
},
{
"type": "image_url",
"image_url": {
"url": "'$data_url'",
"detail": "high"
}
}
]
}
]
}'Параметры синтеза речи
Выбор голоса
OpenAI предоставляет шесть встроенных голосов с разными характеристиками:
alloy— сбалансированный, нейтральный голос;echo— глубокий, резонирующий голос;fable— выразительный, повествовательный голос;onyx— сильный, уверенный голос;nova— яркий, энергичный голос;shimmer— мягкий, успокаивающий голос.
# Пример с другим голосом
curl --location 'http://localhost:8080/v1/audio/speech' \
--header 'Content-Type: application/json' \
--data '{
"model": "openai/tts-1",
"input": "This is the nova voice speaking.",
"voice": "nova",
"response_format": "mp3"
}' \
--output "sample_nova.mp3"Аудио-форматы
Выбирайте формат под сценарий: MP3 — для общего использования, Opus — для web-стриминга, AAC — для мобильных приложений, FLAC — для высококачественного аудио.
# MP3 (по умолчанию)
"response_format": "mp3"
# Opus — для web-стриминга
"response_format": "opus"
# AAC — для мобильных приложений
"response_format": "aac"
# FLAC — для высококачественного аудио
"response_format": "flac"Параметры транскрипции
Указание языка
Чтобы повысить точность транскрипции, явно укажите язык исходного аудио. Особенно полезно для не-английских записей и для текстов с технической терминологией.
curl --location 'http://localhost:8080/v1/audio/transcriptions' \
--form 'file=@"spanish_audio.mp3"' \
--form 'model="openai/whisper-1"' \
--form 'language="es"' \
--form 'prompt="This is a Spanish audio recording about technology."'Форматы ответа
Выбирайте между простым текстом и подробным JSON с тайминг-разметкой. verbose_json возвращает информацию на уровне слов и сегментов — пригодится для генерации субтитров или анализа речи.
# Только текст
curl --location 'http://localhost:8080/v1/audio/transcriptions' \
--form 'file=@"audio.mp3"' \
--form 'model="openai/whisper-1"' \
--form 'response_format="text"'
# JSON с таймингом
curl --location 'http://localhost:8080/v1/audio/transcriptions' \
--form 'file=@"audio.mp3"' \
--form 'model="openai/whisper-1"' \
--form 'response_format="verbose_json"' \
--form 'timestamp_granularities[]=word' \
--form 'timestamp_granularities[]=segment'Возможности мультимодальной обработки зависят от провайдера и модели. Уточняйте поддержку конкретного типа контента в документации соответствующего провайдера.