Даже базовая реализация Live API позволяет создавать привлекательные и эффективные способы взаимодействия с пользователями. При желании вы можете настроить дополнительные параметры:
Обнаружение голосовой активности (VAD), например для обработки прерываний.
Голос и язык ответов
Вы можете настроить модель так, чтобы она отвечала определенным голосом и на разных языках.
Как выбрать голос для ответов
|
Нажмите на название своего поставщика Gemini API, чтобы посмотреть контент и код, относящиеся к нему. |
Live API поддерживает 30 синтезированных HD-голосов с разными характеристиками. Чтобы посмотреть список вариантов голоса и послушать их демоверсии, разверните раздел ниже.
Если вы не укажете голос, по умолчанию будет использоваться Puck.
Чтобы указать голос для ответов, задайте название голоса в объекте speechConfig в конфигурации модели.
Swift
// ...
let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
modelName: "GEMINI_LIVE_API_MODEL_NAME",
// Configure the model to use a specific voice for its audio response.
generationConfig: LiveGenerationConfig(
responseModalities: [.audio],
speech: SpeechConfig(voiceName: "VOICE_NAME")
)
)
// ...
Kotlin
// ...
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
modelName = "GEMINI_LIVE_API_MODEL_NAME",
// Configure the model to use a specific voice for its audio response.
generationConfig = liveGenerationConfig {
responseModality = ResponseModality.AUDIO
speechConfig = SpeechConfig(voice = Voice("VOICE_NAME"))
}
)
// ...
Java
// ...
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
"GEMINI_LIVE_API_MODEL_NAME",
// Configure the model to use a specific voice for its audio response.
new LiveGenerationConfig.Builder()
.setResponseModality(ResponseModality.AUDIO)
.setSpeechConfig(new SpeechConfig(new Voice("VOICE_NAME")))
.build()
);
// ...
Web
// ...
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
const liveModel = getLiveGenerativeModel(ai, {
model: "GEMINI_LIVE_API_MODEL_NAME",
// Configure the model to use a specific voice for its audio response.
generationConfig: {
responseModalities: [ResponseModality.AUDIO],
speechConfig: {
voiceConfig: {
prebuiltVoiceConfig: { voiceName: "VOICE_NAME" },
},
},
},
});
// ...
Dart
// ...
final _liveModel = FirebaseAI.googleAI().liveGenerativeModel(
model: 'GEMINI_LIVE_API_MODEL_NAME',
// Configure the model to use a specific voice for its audio response.
liveGenerationConfig: LiveGenerationConfig(
responseModalities: [ResponseModalities.audio],
speechConfig: SpeechConfig(voiceName: 'VOICE_NAME'),
),
);
// ...
Unity
// ...
var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
modelName: "GEMINI_LIVE_API_MODEL_NAME",
// Configure the model to use a specific voice for its audio response
liveGenerationConfig: new LiveGenerationConfig(
responseModalities: new[] { ResponseModality.Audio },
speechConfig: SpeechConfig.UsePrebuiltVoice("VOICE_NAME")
)
);
// ...
Как повлиять на язык ответа
Модели Live API автоматически выбирают подходящий язык для ответов.
Если вы хотите, чтобы модель отвечала на другом языке или всегда на определенном языке, вы можете повлиять на ее ответы, используя системные инструкции, как в следующих примерах:
Укажите модели, что ответ на другом языке может быть уместен.
Listen to the speaker carefully. If you detect a non-English language, respond in the language you hear from the speaker. You must respond unmistakably in the speaker's language.Как указать, на каком языке модель должна отвечать
RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.
Расшифровка аудиоввода и аудиовывода
|
Нажмите на название своего поставщика Gemini API, чтобы посмотреть контент и код, относящиеся к нему. |
В ответе модели вы можете получить расшифровки аудиозапроса и аудиоответа. Вы задаете эту конфигурацию в рамках конфигурации модели.
Чтобы расшифровать аудиоввод, добавьте
inputAudioTranscription.Чтобы получить расшифровку аудиоответа модели, добавьте
outputAudioTranscription.
Обратите внимание:
Вы можете настроить модель так, чтобы она возвращала расшифровки как входных, так и выходных данных (как показано в примере ниже), или только одного из них.
Расшифровки передаются вместе с аудио, поэтому лучше всего собирать их так же, как и текстовые части, при каждом повороте.
Язык расшифровки определяется на основе аудиоввода и аудиоответа модели.
Swift
// ...
let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
modelName: "GEMINI_LIVE_API_MODEL_NAME",
// Configure the model to return transcriptions of the audio input and output.
generationConfig: LiveGenerationConfig(
responseModalities: [.audio],
inputAudioTranscription: AudioTranscriptionConfig(),
outputAudioTranscription: AudioTranscriptionConfig()
)
)
var inputTranscript: String = ""
var outputTranscript: String = ""
do {
let session = try await liveModel.connect()
for try await response in session.responses {
if case let .content(content) = response.payload {
if let inputText = content.inputAudioTranscription?.text {
// Handle transcription text of the audio input.
inputTranscript += inputText
}
if let outputText = content.outputAudioTranscription?.text {
// Handle transcription text of the audio output.
outputTranscript += outputText
}
if content.isTurnComplete {
// Log the transcripts after the current turn is complete.
print("Input audio: \(inputTranscript)")
print("Output audio: \(outputTranscript)")
// Reset the transcripts for the next turn.
inputTranscript = ""
outputTranscript = ""
}
}
}
} catch {
// Handle error
}
// ...
Kotlin
// ...
val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
modelName = "GEMINI_LIVE_API_MODEL_NAME",
// Configure the model to return transcriptions of the audio input and output.
generationConfig = liveGenerationConfig {
responseModality = ResponseModality.AUDIO
inputAudioTranscription = AudioTranscriptionConfig()
outputAudioTranscription = AudioTranscriptionConfig()
}
)
val liveSession = liveModel.connect()
fun handleTranscription(input: Transcription?, output: Transcription?) {
input?.text?.let { text ->
// Handle transcription text of the audio input.
println("Input Transcription: $text")
}
output?.text?.let { text ->
// Handle transcription text of the audio output.
println("Output Transcription: $text")
}
}
liveSession.startAudioConversation(null, ::handleTranscription)
// ...
Java
// ...
ExecutorService executor = Executors.newFixedThreadPool(1);
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
"GEMINI_LIVE_API_MODEL_NAME",
// Configure the model to return transcriptions of the audio input and output.
new LiveGenerationConfig.Builder()
.setResponseModality(ResponseModality.AUDIO)
.setInputAudioTranscription(new AudioTranscriptionConfig())
.setOutputAudioTranscription(new AudioTranscriptionConfig())
.build()
);
LiveModelFutures liveModel = LiveModelFutures.from(lm);
ListenableFuture<LiveSessionFutures> sessionFuture = liveModel.connect();
Futures.addCallback(sessionFuture, new FutureCallback<LiveSessionFutures>() {
@Override
public void onSuccess(LiveSessionFutures ses) {
LiveSessionFutures session = ses;
session.startAudioConversation((Transcription input, Transcription output) -> {
if (input != null) {
// Handle transcription text of the audio input.
System.out.println("Input Transcription: " + input.getText());
}
if (output != null) {
// Handle transcription text of the audio output.
System.out.println("Output Transcription: " + output.getText());
}
return null;
});
}
@Override
public void onFailure(Throwable t) {
// Handle exceptions
t.printStackTrace();
}
}, executor);
// ...
Web
// ...
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
const liveModel = getLiveGenerativeModel(ai, {
model: 'GEMINI_LIVE_API_MODEL_NAME',
// Configure the model to return transcriptions of the audio input and output.
generationConfig: {
responseModalities: [ResponseModality.AUDIO],
inputAudioTranscription: {},
outputAudioTranscription: {},
},
});
const liveSession = await liveModel.connect();
liveSession.sendAudioRealtime({ data, mimeType: "audio/pcm" });
const messages = liveSession.receive();
for await (const message of messages) {
switch (message.type) {
case 'serverContent':
if (message.inputTranscription) {
// Handle transcription text of the audio input.
console.log(`Input transcription: ${message.inputTranscription.text}`);
}
if (message.outputTranscription) {
// Handle transcription text of the audio output.
console.log(`Output transcription: ${message.outputTranscription.text}`);
} else {
// Handle other message types (modelTurn, turnComplete, interruption).
}
default:
// Handle other message types (toolCall, toolCallCancellation).
}
}
// ...
Dart
// ...
final _liveModel = FirebaseAI.googleAI().liveGenerativeModel(
model: 'GEMINI_LIVE_API_MODEL_NAME',
// Configure the model to return transcriptions of the audio input and output.
liveGenerationConfig: LiveGenerationConfig(
responseModalities: [ResponseModalities.audio],
inputAudioTranscription: AudioTranscriptionConfig(),
outputAudioTranscription: AudioTranscriptionConfig(),
),
);
final LiveSession _session = await _liveModel.connect();
await for (final response in _session.receive()) {
if (response.message case LiveServerContent message) {
if (message.inputTranscription?.text case final inputText?) {
// Handle transcription text of the audio input.
print('Input: $inputText');
}
if (message.outputTranscription?.text case final outputText?) {
// Handle transcription text of the audio output.
print('Output: $outputText');
}
}
}
// ...
Unity
// ...
var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
modelName: "GEMINI_LIVE_API_MODEL_NAME",
// Configure the model to return transcriptions of the audio input and output
liveGenerationConfig: new LiveGenerationConfig(
responseModalities: new[] { ResponseModality.Audio },
inputAudioTranscription: new AudioTranscriptionConfig(),
outputAudioTranscription: new AudioTranscriptionConfig()
)
);
try
{
var session = await liveModel.ConnectAsync();
var stream = session.ReceiveAsync();
await foreach (var response in stream) {
if (response.Message is LiveSessionContent sessionContent) {
if (!string.IsNullOrEmpty(sessionContent.InputTranscription?.Text)) {
// handle transcription text of input audio
}
if (!string.IsNullOrEmpty(sessionContent.OutputTranscription?.Text)) {
// handle transcription text of output audio
}
}
}
}
catch (Exception e)
{
// Handle error
}
// ...
Обнаружение голосовой активности (VAD)
Обнаружение голосовой активности (VAD) позволяет модели распознавать, когда говорит человек. Это важно для естественного общения, поскольку позволяет прерывать модель в любой момент. По умолчанию функция VAD включена.
Вы можете настроить поведение VAD, в том числе обработку прерываний. Вы также можете отключить автоматическое определение активности голоса, чтобы полностью контролировать реплики в разговоре вручную (например, для интерфейса push-to-talk).
Настройте обнаружение голосовой активности (VAD)
|
Нажмите на название своего поставщика Gemini API, чтобы посмотреть контент и код, относящиеся к нему. |
В примере ниже показано, как настроить поведение VAD, задав realtimeInputConfig в конфигурации модели.
Доступные настройки для этой конфигурации приведены в таблице ниже.
Swift
// ...
let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
modelName: "GEMINI_LIVE_API_MODEL_NAME",
generationConfig: LiveGenerationConfig(
responseModalities: [.audio],
// Configure voice activity detection (VAD), interruption handling, and turn coverage.
// IMPORTANT: Example values shown here. Make sure to update for your use case.
realtimeInputConfig: RealtimeInputConfig(
automaticActivityDetection: ActivityDetectionConfig(
startSensitivity: .low,
endSensitivity: .low,
prefixPadding: .milliseconds(20),
silenceDuration: .milliseconds(500)
),
activityHandling: .interrupt,
turnCoverage: .onlyActivity
)
)
)
Kotlin
// ...
val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
modelName = "GEMINI_LIVE_API_MODEL_NAME",
generationConfig = liveGenerationConfig {
responseModality = ResponseModality.AUDIO
// Configure voice activity detection (VAD), interruption handling, and turn coverage.
// IMPORTANT: Example values shown here. Make sure to update for your use case.
realtimeInputConfig = realtimeInputConfig {
automaticActivityDetection = ActivityDetectionConfig.builder()
.setStartSensitivity(ActivityDetectionConfig.Sensitivity.LOW)
.setEndSensitivity(ActivityDetectionConfig.Sensitivity.LOW)
.setPrefixPaddingMs(20)
.setSilenceDurationMs(500)
.build()
activityHandling = RealtimeInputConfig.ActivityHandling.INTERRUPT
turnCoverage = RealtimeInputConfig.TurnCoverage.ONLY_ACTIVITY
}
}
)
Java
// ...
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
"GEMINI_LIVE_API_MODEL_NAME",
new LiveGenerationConfig.Builder()
.setResponseModality(ResponseModality.AUDIO)
// Configure voice activity detection (VAD), interruption handling, and turn coverage.
// IMPORTANT: Example values shown here. Make sure to update for your use case.
.setRealtimeInputConfig(RealtimeInputConfig.builder()
.setAutomaticActivityDetection(ActivityDetectionConfig.builder()
.setStartSensitivity(ActivityDetectionConfig.Sensitivity.LOW)
.setEndSensitivity(ActivityDetectionConfig.Sensitivity.LOW)
.setPrefixPaddingMs(20)
.setSilenceDurationMs(500)
.build())
.setActivityHandling(RealtimeInputConfig.ActivityHandling.INTERRUPT)
.setTurnCoverage(RealtimeInputConfig.TurnCoverage.ONLY_ACTIVITY)
.build())
.build()
);
Web
Not yet supported for Web apps - check back soon!
Dart
// ...
final _liveModel = FirebaseAI.googleAI().liveGenerativeModel(
model: 'GEMINI_LIVE_API_MODEL_NAME',
liveGenerationConfig: LiveGenerationConfig(
responseModalities: [ResponseModalities.audio],
// Configure voice activity detection (VAD), interruption handling, and turn coverage.
// IMPORTANT: Example values shown here. Make sure to update for your use case.
realtimeInputConfig: RealtimeInputConfig(
automaticActivityDetection: ActivityDetectionConfig(
startSensitivity: Sensitivity.low,
endSensitivity: Sensitivity.low,
prefixPaddingMS: 20,
silenceDurationMS: 500,
),
activityHandling: ActivityHandling.interrupt,
turnCoverage: TurnCoverage.onlyActivity,
),
),
);
Unity
// ...
var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
modelName: "GEMINI_LIVE_API_MODEL_NAME",
liveGenerationConfig: new LiveGenerationConfig(
responseModalities: new[] { ResponseModality.Audio },
// Configure voice activity detection (VAD), interruption handling, and turn coverage.
// IMPORTANT: Example values shown here. Make sure to update for your use case.
realtimeInputConfig: new RealtimeInputConfig(
automaticActivityDetection: new ActivityDetectionConfig(
startSensitivity: ActivityDetectionConfig.Sensitivity.Low,
endSensitivity: ActivityDetectionConfig.Sensitivity.Low,
prefixPaddingMS: 20,
silenceDurationMS: 500
),
activityHandling: RealtimeInputConfig.ActivityHandling.Interrupt,
turnCoverage: RealtimeInputConfig.TurnCoverage.OnlyActivity
)
)
);
Доступные настройки конфигурации VAD
| Параметр | Допустимые значения | Описание |
|---|---|---|
Автоматическое распознавание активности (automaticActivityDetection)
|
||
startSensitivity |
|
Определяет, насколько быстро сервер обнаруживает, что пользователь начал говорить.
|
endSensitivity |
|
Определяет, насколько быстро сервер определяет, что пользователь закончил говорить.
|
prefixPadding |
Продолжительность в миллисекундах (по умолчанию: нет (0 мс)) |
Определяет, сколько аудиоданных нужно включить до того, как будет обнаружена речь. Этот буфер позволяет модели захватывать начало речи, включая первый слог, который часто начинается до срабатывания детектора.
|
silenceDuration |
Длительность в миллисекундах (по умолчанию: ~800 мс) |
Определяет, как долго сервер ждет тишины, прежде чем завершить речевой ход. Этот параметр определяет, насколько система терпима к естественным паузам в середине предложения (например, когда пользователь думает, дышит или делает паузу между частями предложения).
|
Поведение при прерывании (activityHandling)
|
||
activityHandling |
|
Определяет, как сервер обрабатывает входящие действия пользователя во время генерации ответа:
|
Контекст поворота (turnCoverage)
|
||
turnCoverage |
|
Определяет, какие потоковые входные данные включаются в контекст реплики в разговоре:
|
Как обрабатывать прерывания
Если сервер обнаруживает входящую речь пользователя, когда модель генерирует ответ, а для параметра activityHandling задано значение INTERRUPT (по умолчанию), происходит следующее:
Генерация отменяется. Модель немедленно прекращает генерировать ответ и отменяет все ожидающие вызовы инструментов.
История сеанса усекается. В окне контекста сеанса сохраняется только контент, который был передан в приложение до прерывания.
Отправляется сигнал прерывания. Сервер отправляет ответное сообщение о том, что генерация была прервана (например,
wasInterruptedв Swift илиinterruptedв Kotlin, Java, Web, Flutter и Unity).
Отключить автоматическое обнаружение голосовой активности (VAD)
Чтобы полностью контролировать реплики вручную (например, для интерфейса push-to-talk), вы можете отключить автоматическое обнаружение голосовой активности (VAD) вместо настройки параметров чувствительности.
Если автоматическое определение отключено, сервер не будет автоматически распознавать речь или запускать ответы на основе тишины. Вместо этого приложение должно вручную сигнализировать о границах активности пользователя во время активного сеанса.
1. Отключите автоматическое определение голосовой активности в конфигурации модели.
|
Нажмите на название своего поставщика Gemini API, чтобы посмотреть контент и код, относящиеся к нему. |
Swift
// ...
let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
modelName: "GEMINI_LIVE_API_MODEL_NAME",
generationConfig: LiveGenerationConfig(
responseModalities: [.audio],
// Disable automatic voice activity detection (VAD).
realtimeInputConfig: RealtimeInputConfig(
automaticActivityDetection: .disabled()
)
)
)
Kotlin
// ...
val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
modelName = "GEMINI_LIVE_API_MODEL_NAME",
generationConfig = liveGenerationConfig {
responseModality = ResponseModality.AUDIO
// Disable automatic voice activity detection (VAD).
realtimeInputConfig = realtimeInputConfig {
automaticActivityDetection = ActivityDetectionConfig.disabled()
}
}
)
Java
// ...
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
"GEMINI_LIVE_API_MODEL_NAME",
new LiveGenerationConfig.Builder()
.setResponseModality(ResponseModality.AUDIO)
// Disable automatic voice activity detection (VAD).
.setRealtimeInputConfig(RealtimeInputConfig.builder()
.setAutomaticActivityDetection(ActivityDetectionConfig.disabled())
.build())
.build()
);
Web
Not yet supported for Web apps - check back soon!
Dart
// ...
final _liveModel = FirebaseAI.googleAI().liveGenerativeModel(
model: 'GEMINI_LIVE_API_MODEL_NAME',
liveGenerationConfig: LiveGenerationConfig(
responseModalities: [ResponseModalities.audio],
// Disable automatic voice activity detection (VAD).
realtimeInputConfig: RealtimeInputConfig(
automaticActivityDetection: ActivityDetectionConfig.disabled(),
),
),
);
Unity
// ...
var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
modelName: "GEMINI_LIVE_API_MODEL_NAME",
liveGenerationConfig: new LiveGenerationConfig(
responseModalities: new[] { ResponseModality.Audio },
// Disable automatic voice activity detection (VAD).
realtimeInputConfig: new RealtimeInputConfig(
automaticActivityDetection: ActivityDetectionConfig.Disabled()
)
)
);
2. Как вручную обозначить границы действий пользователя
Если вы отключите VAD, ваше приложение должно вручную разграничивать действия пользователя:
Начало действия. Вызовите
sendStartActivityRealtimeперед отправкой аудиоданных (например, когда пользователь нажимает кнопку "Нажать и говорить").Потоковая передача пользовательского ввода. Непрерывная потоковая передача аудио- или видеоданных с помощью
sendAudioRealtime.Сигнал об окончании действия. Вызовите
sendStopActivityRealtime, когда пользователь закончит говорить (например, отпустит кнопку режима рации). Это сигнализирует о конце реплики пользователя и запускает ответ модели.
Swift
// If you disable automatic voice activity detection (VAD), you need to manually demarcate user activity.
// Signal the start of user activity (for example, on push-to-talk button press).
await session.sendStartActivityRealtime()
// Stream user audio data while the user speaks.
await session.sendAudioRealtime(audioData)
// Signal the end of user activity (for example, on button release) to trigger model response.
await session.sendStopActivityRealtime()
Kotlin
// If you disable automatic voice activity detection (VAD), you need to manually demarcate user activity.
// Signal the start of user activity (for example, on push-to-talk button press).
session.sendStartActivityRealtime()
// Stream user audio data while the user speaks.
session.sendAudioRealtime(audioData)
// Signal the end of user activity (for example, on button release) to trigger model response.
session.sendStopActivityRealtime()
Java
// If you disable automatic voice activity detection (VAD), you need to manually demarcate user activity.
// Signal the start of user activity (for example, on push-to-talk button press).
session.sendStartActivityRealtime();
// Stream user audio data while the user speaks.
session.sendAudioRealtime(audioData);
// Signal the end of user activity (for example, on button release) to trigger model response.
session.sendStopActivityRealtime();
Web
Not yet supported for Web apps - check back soon!
Dart
// If you disable automatic voice activity detection (VAD), you need to manually demarcate user activity.
// Signal the start of user activity (for example, on push-to-talk button press).
await session.sendStartActivityRealtime();
// Stream user audio data while the user speaks.
await session.sendAudioRealtime(audioData);
// Signal the end of user activity (for example, on button release) to trigger model response.
await session.sendStopActivityRealtime();
Unity
// If you disable automatic voice activity detection (VAD), you need to manually demarcate user activity.
// Signal the start of user activity (for example, on push-to-talk button press).
await session.SendStartActivityRealtimeAsync();
// Stream user audio data while the user speaks.
await session.SendAudioRealtimeAsync(audio: audioData);
// Signal the end of user activity (for example, on button release) to trigger model response.
await session.SendStopActivityRealtimeAsync();
Управление сеансами
Ниже вы найдете информацию по следующим темам:
Расширенные возможности, в том числе:
Ограничения, связанные с сеансами, в том числе ограничения на продолжительность подключения и сеанса, ограничения на размер окна контекста сеанса и ограничения частоты запросов.
Варианты обработки ограничений сеанса, в том числе: