Gemini Live API는 세션이라고 하는 연속적인 오디오 또는 텍스트 스트림을 처리합니다. 초기 핸드셰이크부터 단계적 종료까지 세션 수명 주기를 관리할 수 있습니다.
세션 제한
Live API의 경우 세션은 동일한 연결을 통해 입력과 출력이 지속적으로 스트리밍되는 영구 연결을 의미합니다.
세션이 다음 한도 중 하나라도 초과하면 연결이 종료됩니다.
연결 길이는 약 10분으로 제한됩니다.
세션 길이는 입력 모달리티에 따라 다릅니다.
- 오디오 전용 입력 세션은 15분으로 제한됩니다.
- 동영상 + 오디오 입력은 2분으로 제한됩니다.
세션 컨텍스트 윈도우는 토큰 128,000개로 제한됩니다.
연결이 종료되기 전에 종료 예정 알림이 전송되므로 추가 조치를 취할 수 있습니다.
세션 시작
세션을 시작하는 방법을 보여주는 전체 스니펫은 Live API 시작 가이드를 참고하세요.
세션 중 업데이트
Live API 모델은 세션 중 업데이트를 위해 다음과 같은 고급 기능을 지원합니다.
시스템 안내 업데이트 (Vertex AI Gemini API만 해당)
증분 콘텐츠 업데이트 추가
활성 세션 중에 증분 업데이트를 추가할 수 있습니다. 텍스트 입력을 전송하거나, 세션 컨텍스트를 설정하거나, 세션 컨텍스트를 복원하는 데 사용합니다.
컨텍스트가 긴 경우 후속 상호작용을 위해 컨텍스트 윈도우를 확보할 수 있도록 단일 메시지 요약을 제공하는 것이 좋습니다.
짧은 컨텍스트의 경우 아래 스니펫과 같이 정확한 이벤트 순서를 나타내기 위해 차례대로 상호작용을 보낼 수 있습니다.
Swift
// Define initial turns (history/context).
let turns: [ModelContent] = [
ModelContent(role: "user", parts: [TextPart("What is the capital of France?")]),
ModelContent(role: "model", parts: [TextPart("Paris")]),
]
// Send history, keeping the conversational turn OPEN (false).
await session.sendContent(turns, turnComplete: false)
// Define the new user query.
let newTurn: [ModelContent] = [
ModelContent(role: "user", parts: [TextPart("What is the capital of Germany?")]),
]
// Send the final query, CLOSING the turn (true) to trigger the model response.
await session.sendContent(newTurn, turnComplete: true)
Kotlin
Not yet supported for Android apps - check back soon!
Java
Not yet supported for Android apps - check back soon!
Web
const turns = [{ text: "Hello from the user!" }];
await session.send(
turns,
false // turnComplete: false
);
console.log("Sent history. Waiting for next input...");
// Define the new user query.
const newTurn [{ text: "And what is the capital of Germany?" }];
// Send the final query, CLOSING the turn (true) to trigger the model response.
await session.send(
newTurn,
true // turnComplete: true
);
console.log("Sent final query. Model response expected now.");
Dart
// Define initial turns (history/context).
final List turns = [
Content(
"user",
[Part.text("What is the capital of France?")],
),
Content(
"model",
[Part.text("Paris")],
),
];
// Send history, keeping the conversational turn OPEN (false).
await session.send(
input: turns,
turnComplete: false,
);
// Define the new user query.
final List newTurn = [
Content(
"user",
[Part.text("What is the capital of Germany?")],
),
];
// Send the final query, CLOSING the turn (true) to trigger the model response.
await session.send(
input: newTurn,
turnComplete: true,
);
Unity
// Define initial turns (history/context).
List turns = new List {
new ModelContent("user", new ModelContent.TextPart("What is the capital of France?") ),
new ModelContent("model", new ModelContent.TextPart("Paris") ),
};
// Send history, keeping the conversational turn OPEN (false).
foreach (ModelContent turn in turns)
{
await session.SendAsync(
content: turn,
turnComplete: false
);
}
// Define the new user query.
ModelContent newTurn = ModelContent.Text("What is the capital of Germany?");
// Send the final query, CLOSING the turn (true) to trigger the model response.
await session.SendAsync(
content: newTurn,
turnComplete: true
);
세션 중에 시스템 요청 사항 업데이트
| Vertex AI Gemini API를 API 제공업체로 사용하는 경우에만 사용할 수 있습니다. |
활성 세션 중에 시스템 안내를 업데이트할 수 있습니다. 이를 사용하여 모델의 대답을 조정합니다(예: 대답 언어 변경 또는 어조 수정).
세션 중에 시스템 요청 사항을 업데이트하려면 system 역할로 텍스트 콘텐츠를 전송하면 됩니다. 업데이트된 시스템 요청 사항이 남은 세션 동안 적용됩니다.
Swift
await session.sendContent(
[ModelContent(
role: "system",
parts: [TextPart("new system instruction")]
)],
turnComplete: false
)
Kotlin
Not yet supported for Android apps - check back soon!
Java
Not yet supported for Android apps - check back soon!
Web
Not yet supported for Web apps - check back soon!
Dart
try {
await _session.send(
input: Content(
'system',
[Part.text('new system instruction')],
),
turnComplete: false,
);
} catch (e) {
print('Failed to update system instructions: $e');
}
Unity
try
{
await session.SendAsync(
content: new ModelContent(
"system",
new ModelContent.TextPart("new system instruction")
),
turnComplete: false
);
}
catch (Exception e)
{
Debug.LogError($"Failed to update system instructions: {e.Message}");
}
세션이 종료되는 시점 감지
세션이 종료되기
다음 예시에서는 going away 알림을 리슨하여 임박한 세션 종료를 감지하는 방법을 보여줍니다.
Swift
for try await response in session.responses {
switch response.payload {
case .goingAwayNotice(let goingAwayNotice):
// Prepare for the session to close soon
if let timeLeft = goingAwayNotice.timeLeft {
print("Server going away in \(timeLeft) seconds")
}
}
}
Kotlin
for (response in session.responses) {
when (val message = response.payload) {
is LiveServerGoAway -> {
// Prepare for the session to close soon
val remaining = message.timeLeft
logger.info("Server going away in $remaining")
}
}
}
Java
session.getResponses().forEach(response -> {
if (response.getPayload() instanceof LiveServerResponse.GoingAwayNotice) {
LiveServerResponse.GoingAwayNotice notice = (LiveServerResponse.GoingAwayNotice) response.getPayload();
// Prepare for the session to close soon
Duration timeLeft = notice.getTimeLeft();
}
});
Web
for await (const message of session.receive()) {
switch (message.type) {
...
case "goingAwayNotice":
console.log("Server going away. Time left:", message.timeLeft);
break;
}
}
Dart
Future _handleLiveServerMessage(LiveServerResponse response) async {
final message = response.message;
if (message is GoingAwayNotice) {
// Prepare for the session to close soon
developer.log('Server going away. Time left: ${message.timeLeft}');
}
}
Unity
foreach (var response in session.Responses) {
if (response.Payload is LiveSessionGoingAway notice) {
// Prepare for the session to close soon
TimeSpan timeLeft = notice.TimeLeft;
Debug.Log($"Server going away notice received. Remaining: {timeLeft}");
}
}