Live API용 기본 제공 도구

이 가이드에서는 Live API에서 제공되는 기본 제공 도구를 사용하여 모델 상호작용을 개선하는 방법을 보여줍니다. 이 가이드에는 다음 주제가 포함되어 있습니다.

  • 함수 호출: 모델이 외부 시스템과 상호작용하기 위해 호출할 수 있는 맞춤 함수를 정의하는 방법을 설명합니다.
  • 코드 실행: 모델이 계산 작업을 위해 Python 코드를 생성하고 실행하도록 설정하는 방법을 설명합니다.
  • Google 검색으로 그라운딩: 실시간 공개 정보를 기반으로 한 대답을 위해 모델을 Google 검색에 연결하는 방법을 보여줍니다.
  • Vertex AI RAG Engine을 사용한 그라운딩: 자체 비공개 데이터 소스를 사용하여 모델 응답을 그라운딩하는 방법을 자세히 설명합니다.
  • 네이티브 오디오: 사전 대응 응답, 감정적 신호 이해 등 고급 오디오 기능을 다룹니다.

도구를 사용 설정하려면 모델을 초기화할 때 tools 목록에 도구를 포함하세요. 다음 표에서는 사용 가능한 도구를 대략적으로 비교합니다.

도구 설명 사용 사례
함수 호출 모델이 사용자가 정의한 외부 함수를 호출할 수 있도록 지원합니다. 모델은 사용할 함수 이름과 인수를 반환합니다. 외부 API, 데이터베이스 또는 기타 서비스와 통합(예: 날씨 확인 또는 항공편 예약)
코드 실행 모델이 샌드박스 환경에서 Python 코드를 생성하고 실행하여 계산이나 작업을 수행할 수 있습니다. 수학 문제 풀이, 데이터 분석 또는 짧은 Python 스크립트로 완료할 수 있는 작업
Google 검색으로 그라운딩 모델을 Google 검색에 연결하여 최신 공개 웹 정보를 기반으로 대답합니다. 이는 그라운딩의 한 형태입니다. 최신 정보가 중요한 최근 이벤트 또는 주제에 대한 질문에 답변합니다.
Vertex AI RAG Engine을 사용한 그라운딩 검색 증강 생성 (RAG)을 사용하여 모델을 비공개 또는 선별된 데이터 소스에 연결합니다. 회사의 내부 문서 또는 제품 매뉴얼을 기반으로 질문에 답변하는 챗봇을 빌드합니다.

지원되는 모델

다음 모델에서 Live API를 사용할 수 있습니다.

모델 버전 가용성 수준
gemini-live-2.5-flash 비공개 GA*
gemini-live-2.5-flash-preview-native-audio 공개 미리보기

* 액세스를 요청하려면 Google 계정 담당자에게 문의하세요.

함수 호출

함수 호출을 사용하여 함수에 대한 설명을 만든 다음 요청 시 해당 설명을 모델에 전달합니다. 모델의 응답에는 설명과 일치하는 함수의 이름과 함께 이를 호출할 인수가 포함됩니다.

LiveConnectConfig 메시지의 일부로 도구 정의를 전송하여 세션 시작 시 모든 함수를 선언합니다.

함수 호출을 사용 설정하려면 tools 목록에 function_declarations를 포함하세요.

Python

import asyncio
from google import genai
from google.genai import types

client = genai.Client(
    vertexai=True,
    project=GOOGLE_CLOUD_PROJECT,
    location=GOOGLE_CLOUD_LOCATION,
)
model = "gemini-live-2.5-flash"

# Simple function definitions
turn_on_the_lights = {"name": "turn_on_the_lights"}
turn_off_the_lights = {"name": "turn_off_the_lights"}

tools = [{"function_declarations": [turn_on_the_lights, turn_off_the_lights]}]
config = {"response_modalities": ["TEXT"], "tools": tools}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        prompt = "Turn on the lights please"
        await session.send_client_content(turns={"parts": [{"text": prompt}]})

        async for chunk in session.receive():
            if chunk.server_content:
                if chunk.text is not None:
                    print(chunk.text)
            elif chunk.tool_call:
                function_responses = []
                for fc in tool_call.function_calls:
                    function_response = types.FunctionResponse(
                        name=fc.name,
                        response={ "result": "ok" } # simple, hard-coded function response
                    )
                    function_responses.append(function_response)

                await session.send_tool_response(function_responses=function_responses)


if __name__ == "__main__":
    asyncio.run(main())
  

Python

코드 실행

Live API에서 코드 실행을 사용하여 Python 코드를 직접 생성하고 실행할 수 있습니다. 대답에 코드 실행을 사용 설정하려면 tools 목록에 code_execution을 포함하세요.

Python

import asyncio
from google import genai
from google.genai import types


client = genai.Client(
    vertexai=True,
    project=GOOGLE_CLOUD_PROJECT,
    location=GOOGLE_CLOUD_LOCATION,
)
model = "gemini-live-2.5-flash"

tools = [{'code_execution': {}}]
config = {"response_modalities": ["TEXT"], "tools": tools}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        prompt = "Compute the largest prime palindrome under 100000."
        await session.send_client_content(turns={"parts": [{"text": prompt}]})

        async for chunk in session.receive():
            if chunk.server_content:
                if chunk.text is not None:
                    print(chunk.text)
            
                model_turn = chunk.server_content.model_turn
                if model_turn:
                    for part in model_turn.parts:
                      if part.executable_code is not None:
                        print(part.executable_code.code)

                      if part.code_execution_result is not None:
                        print(part.code_execution_result.output)

if __name__ == "__main__":
    asyncio.run(main())
  

tools 목록에 google_search를 포함하여 Live API와 함께 Google 검색을 통한 그라운딩을 사용할 수 있습니다.

Python

import asyncio
from google import genai
from google.genai import types

client = genai.Client(
    vertexai=True,
    project=GOOGLE_CLOUD_PROJECT,
    location=GOOGLE_CLOUD_LOCATION,
)
model = "gemini-live-2.5-flash"


tools = [{'google_search': {}}]
config = {"response_modalities": ["TEXT"], "tools": tools}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        prompt = "When did the last Brazil vs. Argentina soccer match happen?"
        await session.send_client_content(turns={"parts": [{"text": prompt}]})

        async for chunk in session.receive():
            if chunk.server_content:
                if chunk.text is not None:
                    print(chunk.text)

                # The model might generate and execute Python code to use Search
                model_turn = chunk.server_content.model_turn
                if model_turn:
                    for part in model_turn.parts:
                        if part.executable_code is not None:
                        print(part.executable_code.code)

                        if part.code_execution_result is not None:
                        print(part.code_execution_result.output)

if __name__ == "__main__":
    asyncio.run(main())
  

Vertex AI RAG Engine을 사용한 그라운딩 (미리보기)

Live API를 Vertex AI RAG Engine에 연결하여 비공개 데이터 소스에 모델 응답을 그라운딩할 수 있습니다. Vertex AI RAG Engine을 사용한 그라운딩을 사용 설정하려면 VertexRagStore 세부정보를 사용하여 retrieval 도구를 구성하세요.

Python

from google import genai
from google.genai import types
from google.genai.types import (Content, LiveConnectConfig, HttpOptions, Modality, Part)
from IPython import display

PROJECT_ID=YOUR_PROJECT_ID
LOCATION=YOUR_LOCATION
TEXT_INPUT=YOUR_TEXT_INPUT
MODEL_NAME="gemini-live-2.5-flash"

client = genai.Client(
   vertexai=True,
   project=PROJECT_ID,
   location=LOCATION,
)

rag_store=types.VertexRagStore(
   rag_resources=[
       types.VertexRagStoreRagResource(
           rag_corpus=  # Use memory corpus if you want to store context.
       )
   ],
   # Set `store_context` to true to allow Live API sink context into your memory corpus.
   store_context=True
)

async with client.aio.live.connect(
   model=MODEL_NAME,
   config=LiveConnectConfig(response_modalities=[Modality.TEXT],
                            tools=[types.Tool(
                                retrieval=types.Retrieval(
                                    vertex_rag_store=rag_store))]),
) as session:
   text_input=TEXT_INPUT
   print("> ", text_input, "\n")
   await session.send_client_content(
       turns=Content(role="user", parts=[Part(text=text_input)])
   )

   async for message in session.receive():
       if message.text:
           display.display(display.Markdown(message.text))
           continue

자세한 내용은 Gemini Live API에서 Vertex AI RAG Engine 사용을 참고하세요.

(공개 미리보기) 네이티브 오디오

Live API를 사용한 Gemini 2.5 Flash는 네이티브 오디오 기능을 도입하여 표준 Live API 기능을 개선합니다. 네이티브 오디오는 24개 언어30개 HD 음성을 통해 더 풍부하고 자연스러운 음성 상호작용을 제공합니다. 또한 네이티브 오디오 전용의 두 가지 새로운 기능인 프로액티브 오디오 정서적 대화상자도 포함되어 있습니다.

능동적 오디오 사용하기

선제적 오디오를 사용하면 모델이 관련성이 있는 경우에만 응답할 수 있습니다. 사용 설정하면 모델이 텍스트 스크립트와 오디오 응답을 선제적으로 생성하지만 기기를 대상으로 하는 질문에 대해서 생성합니다. 기기 지향이 아닌 쿼리는 무시됩니다.

사전 오디오를 사용하려면 설정 메시지에서 proactivity 필드를 구성하고 proactive_audiotrue로 설정합니다.

Python

config = LiveConnectConfig(
    response_modalities=["AUDIO"],
    proactivity=ProactivityConfig(proactive_audio=True),
)
  

공감형 대화 사용

Affective Dialog를 사용하면 Live API 네이티브 오디오를 사용하는 모델이 사용자의 감정 표현을 더 잘 이해하고 적절하게 응답하여 더 미묘한 대화를 나눌 수 있습니다.

Affective Dialog를 사용 설정하려면 설정 메시지에서 enable_affective_dialogtrue로 설정하세요.

Python

config = LiveConnectConfig(
    response_modalities=["AUDIO"],
    enable_affective_dialog=True,
)
  

추가 정보

라이브 API 사용에 관한 자세한 내용은 다음을 참고하세요.