Gemini API를 사용하면 파일 검색 도구를 통해 검색 증강 생성 ('RAG')을 사용할 수 있습니다. 파일 검색은 사용자의 프롬프트를 기반으로 관련 정보를 빠르게 검색할 수 있도록 데이터를 가져오고, 청크로 나누고, 색인을 생성합니다. 이 정보는 모델에 컨텍스트로 제공되어 모델이 더 정확하고 관련성 있는 답변을 제공할 수 있습니다.
uploadToFileSearchStore API를 사용하여 기존 파일을 파일 검색 스토어에 직접 업로드하거나, 파일을 동시에 만들려면 파일을 별도로 업로드한 후 가져올 수 있습니다.
파일 검색 스토어에 직접 업로드
다음 예에서는 파일 스토어에 파일을 직접 업로드하는 방법을 보여줍니다.
Python
from google import genai
from google.genai import types
import time
client = genai.Client()
# Create the file search store with an optional display name that shows in the grounding metadata
file_search_store = client.file_search_stores.create(config={'display_name': 'your-fileSearchStore-name'})
# Upload and import a file into the file search store, supply a unique file name which will be visible in citations
operation = client.file_search_stores.upload_to_file_search_store(
file='path/to/your/file.txt',
file_search_store_name='unique_file_name'
)
# Wait until import is complete
while not operation.done:
time.sleep(5)
operation = client.operations.get(operation)
# Ask a question about the file
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""Can you tell me about Robert Graves""",
config=types.GenerateContentConfig(
tools=[
file_search=(
file_search_store_names=[file_search_store.name]
)
]
)
)
print(response.text)
파일 가져오기
또는 기존 파일을 업로드하여 파일 저장소로 가져올 수 있습니다.
Python
from google import genai
from google.genai import types
import time
client = genai.Client()
# Upload the file using the Files API, supply a unique file name which will be visible in citations
sample_file = client.files.upload(file='sample.txt', config={'name': 'unique_file_name'})
# Create the file search store with an optional display name that shows in the grounding metadata
file_search_store = client.file_search_stores.create(config={'display_name': 'your-fileSearchStore-name'})
# Import the file into the file search store
operation = client.file_search_stores.import_file(
file_search_store_name=file_search_store.name,
file_name=sample_file.name
)
# Wait until import is complete
while not operation.done:
time.sleep(5)
operation = client.operations.get(operation)
# Ask a question about the file
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""Can you tell me about Robert Graves""",
config=types.GenerateContentConfig(
tools=[
file_search=(
file_search_store_names=[file_search_store.name]
)
]
)
)
print(response.text)
청크 구성
파일을 파일 검색 스토어로 가져오면 자동으로 청크로 분할되고, 삽입되고, 색인이 생성되고, 파일 검색 스토어로 업로드됩니다. 청크 전략을 더 세부적으로 제어해야 하는 경우 chunking_config 설정을 지정하여 청크당 최대 토큰 수와 중복되는 최대 토큰 수를 설정할 수 있습니다.
# Upload and import and upload the file into the file search store with a custom chunking configuration
operation = client.file_search_stores.upload_to_file_search_store(
file_search_store_name=file_search_store.name,
file_name=sample_file.name,
config={
'chunking_config': {
'white_space_config': {
'max_tokens_per_chunk': 200,
'max_overlap_tokens': 20
}
}
}
)
파일 검색 저장소를 사용하려면 업로드 및 가져오기 예와 같이 generateContent 메서드에 도구로 전달하세요.
작동 방식
파일 검색은 시맨틱 검색이라는 기법을 사용하여 사용자 프롬프트와 관련된 정보를 찾습니다. 기존의 키워드 기반 검색과 달리 시맨틱 검색은 질문의 의미와 컨텍스트를 이해합니다.
파일을 가져오면 텍스트의 시맨틱 의미를 포착하는 임베딩이라는 숫자 표현으로 변환됩니다. 이러한 임베딩은 특수 파일 검색 데이터베이스에 저장됩니다. 쿼리를 입력하면 쿼리도 임베딩으로 변환됩니다. 그런 다음 시스템은 파일 검색 저장소에서 가장 유사하고 관련성 높은 문서 청크를 찾기 위해 파일 검색을 실행합니다.
파일 검색 uploadToFileSearchStore API를 사용하는 과정은 다음과 같습니다.
파일 검색 스토어 만들기: 파일 검색 스토어에는 파일에서 처리된 데이터가 포함됩니다. 시맨틱 검색이 작동하는 임베딩의 영구 컨테이너입니다.
파일을 업로드하고 파일 검색 스토어로 가져오기: 파일을 업로드하고 결과를 파일 검색 스토어로 동시에 가져옵니다. 이렇게 하면 원시 문서를 참조하는 임시
File객체가 생성됩니다. 그런 다음 데이터가 청크로 분할되고, 파일 검색 임베딩으로 변환되고, 색인이 생성됩니다.File객체는 48시간 후에 삭제되지만 파일 검색 스토어로 가져온 데이터는 삭제할 때까지 무기한 저장됩니다.파일 검색으로 쿼리: 마지막으로
generateContent호출에서FileSearch도구를 사용합니다. 도구 구성에서 검색할FileSearchStore를 가리키는FileSearchRetrievalResource를 지정합니다. 이렇게 하면 모델이 해당 특정 파일 검색 스토어에서 시맨틱 검색을 실행하여 대답의 근거가 될 관련 정보를 찾습니다.
이 다이어그램에서 문서에서 임베딩 모델(gemini-embedding-001 사용)로 연결되는 점선은 uploadToFileSearchStore API (파일 스토리지 우회)를 나타냅니다.
그렇지 않으면 Files API를 사용하여 파일을 별도로 만든 후 가져오면 색인 생성 프로세스가 Documents에서 File storage로 이동한 후 Embedding model로 이동합니다.
파일 검색 스토어
파일 검색 스토어는 문서 임베딩의 컨테이너입니다. File API를 통해 업로드된 원시 파일은 48시간 후에 삭제되지만 파일 검색 스토어에 가져온 데이터는 수동으로 삭제할 때까지 무기한 저장됩니다. 문서를 정리하기 위해 여러 파일 검색 저장소를 만들 수 있습니다. FileSearchStore API를 사용하면 파일 검색 저장소를 생성, 나열, 가져오기, 삭제하여 관리할 수 있습니다. 파일 검색 저장소 이름은 전역 범위입니다.
파일 검색 저장소를 관리하는 방법의 몇 가지 예는 다음과 같습니다.
# Create a file search store (including optional display_name for easier reference)
file_search_store = client.file_search_stores.create(config={'display_name': 'my-file_search-store-123'})
# List all your file search stores
for file_search_store in client.file_search_stores.list():
print(file_search_store)
# Get a specific file search store by name
my_file_search_store = client.file_search_stores.get(name='fileSearchStores/my-file_search-store-123')
# Delete a file search store
client.file_search_stores.delete(name='fileSearchStores/my-file_search-store-123', config={'force': True})
파일 메타데이터
파일을 필터링하거나 추가 컨텍스트를 제공하는 데 도움이 되도록 파일에 맞춤 메타데이터를 추가할 수 있습니다. 메타데이터는 키-값 쌍의 집합입니다.
# Import the file into the file search store with custom metadata
op = client.file_search_stores.import_file(
file_search_store_name=file_search_store.name,
file_name=sample_file.name,
custom_metadata=[
{"key": "author", "string_value": "Robert Graves"},
{"key": "year", "numeric_value": 1934}
]
)
이는 파일 검색 저장소에 여러 문서가 있고 그중 일부만 검색하려는 경우에 유용합니다.
# Use the metadata filter to search within a subset of documents
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""Tell me about the book 'I, Claudius'""",
config=types.GenerateContentConfig(
tools=[
types.Tool(
file_search=types.FileSearch(
file_search_store_names=[file_search_store.name],
metadata_filter = 'author=Robet Graves',
)
)
]
)
)
print(response.text)
metadata_filter의 목록 필터 문법 구현에 관한 안내는 google.aip.dev/160에서 확인할 수 있습니다.
인용
파일 검색을 사용하면 모델의 대답에 업로드된 문서의 어떤 부분이 대답을 생성하는 데 사용되었는지 명시하는 인용이 포함될 수 있습니다. 이렇게 하면 사실 확인 및 검증에 도움이 됩니다.
응답의 grounding_metadata 속성을 통해 인용 정보에 액세스할 수 있습니다.
print(response.candidates[0].grounding_metadata)
지원되는 모델
다음 모델은 파일 검색을 지원합니다.
지원되는 파일 형식
파일 검색은 다음 섹션에 나열된 다양한 파일 형식을 지원합니다.
애플리케이션 파일 형식
application/dartapplication/ecmascriptapplication/jsonapplication/ms-javaapplication/mswordapplication/pdfapplication/sqlapplication/typescriptapplication/vnd.curlapplication/vnd.dartapplication/vnd.ibm.secure-containerapplication/vnd.jupyterapplication/vnd.ms-excelapplication/vnd.oasis.opendocument.textapplication/vnd.openxmlformats-officedocument.presentationml.presentationapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheetapplication/vnd.openxmlformats-officedocument.wordprocessingml.documentapplication/vnd.openxmlformats-officedocument.wordprocessingml.templateapplication/x-cshapplication/x-hwpapplication/x-hwp-v5application/x-latexapplication/x-phpapplication/x-powershellapplication/x-shapplication/x-shellscriptapplication/x-texapplication/x-zshapplication/xmlapplication/zip
텍스트 파일 형식
text/1d-interleaved-parityfectext/REDtext/SGMLtext/cache-manifesttext/calendartext/cqltext/cql-extensiontext/cql-identifiertext/csstext/csvtext/csv-schematext/dnstext/encaprtptext/enrichedtext/exampletext/fhirpathtext/flexfectext/fwdredtext/gff3text/grammar-ref-listtext/hl7v2text/htmltext/javascripttext/jcr-cndtext/jsxtext/markdowntext/mizartext/n3text/parameterstext/parityfectext/phptext/plaintext/provenance-notationtext/prs.fallenstein.rsttext/prs.lines.tagtext/prs.prop.logictext/raptorfectext/rfc822-headerstext/rtftext/rtp-enc-aescm128text/rtploopbacktext/rtxtext/sgmltext/shaclctext/shextext/spdxtext/stringstext/t140text/tab-separated-valuestext/texmacstext/trofftext/tsvtext/tsxtext/turtletext/ulpfectext/uri-listtext/vcardtext/vnd.DMClientScripttext/vnd.IPTC.NITFtext/vnd.IPTC.NewsMLtext/vnd.atext/vnd.abctext/vnd.ascii-arttext/vnd.curltext/vnd.debian.copyrighttext/vnd.dvb.subtitletext/vnd.esmertec.theme-descriptortext/vnd.exchangeabletext/vnd.familysearch.gedcomtext/vnd.ficlab.flttext/vnd.flytext/vnd.fmi.flexstortext/vnd.gmltext/vnd.graphviztext/vnd.hanstext/vnd.hgltext/vnd.in3d.3dmltext/vnd.in3d.spottext/vnd.latex-ztext/vnd.motorola.reflextext/vnd.ms-mediapackagetext/vnd.net2phone.commcenter.commandtext/vnd.radisys.msml-basic-layouttext/vnd.senx.warpscripttext/vnd.sositext/vnd.sun.j2me.app-descriptortext/vnd.trolltech.linguisttext/vnd.wap.sitext/vnd.wap.sltext/vnd.wap.wmltext/vnd.wap.wmlscripttext/vtttext/wgsltext/x-asmtext/x-bibtextext/x-bootext/x-ctext/x-c++hdrtext/x-c++srctext/x-cassandratext/x-chdrtext/x-coffeescripttext/x-componenttext/x-cshtext/x-csharptext/x-csrctext/x-cudatext/x-dtext/x-difftext/x-dsrctext/x-emacs-lisptext/x-erlangtext/x-gff3text/x-gotext/x-haskelltext/x-javatext/x-java-propertiestext/x-java-sourcetext/x-kotlintext/x-lilypondtext/x-lisptext/x-literate-haskelltext/x-luatext/x-moctext/x-objcsrctext/x-pascaltext/x-pcs-gcdtext/x-perltext/x-perl-scripttext/x-pythontext/x-python-scripttext/x-r-markdowntext/x-rsrctext/x-rsttext/x-ruby-scripttext/x-rusttext/x-sasstext/x-scalatext/x-schemetext/x-script.pythontext/x-scsstext/x-setexttext/x-sfvtext/x-shtext/x-siestatext/x-sostext/x-sqltext/x-swifttext/x-tcltext/x-textext/x-vbasictext/x-vcalendartext/xmltext/xml-dtdtext/xml-external-parsed-entitytext/yaml
비율 제한
File Search API에는 서비스 안정성을 위해 다음과 같은 한도가 적용됩니다.
- 최대 파일 크기 / 문서당 한도: 100MB
- 프로젝트별 파일 검색 저장소: 10
- 프로젝트 파일 검색 저장소의 총 크기 (사용자 등급 기준):
- 무료: 1GB
- Tier 1: 10 GB
- Tier 2: 100 GB
- Tier 3: 1 TB
- 권장사항: 최적의 검색 지연 시간을 보장하려면 각 파일 검색 저장소의 크기를 20GB 미만으로 제한하세요.