Gemini File Search

LiteLLM으로 Latency Augmented Generation(RAG)을 위한 Google Gemini의 File Search를 사용해요. Gemini File Search는 데이터를 가져오고, 청킹하고, 인덱싱해 사용자 프롬프트에 기반한 관련 정보를 빠르게 검색할 수 있게 해요. 이 정보는 더 정확하고 관련성 높은 답변을 위해 모델에 컨텍스트로 제공돼요.

출처: 문서

본문

기능 (Features)

기능 지원 비고
비용 추적 비용 계산 아직 미구현
로깅 전체 요청/응답 로깅
RAG Ingest API 업로드 → 청킹 → 임베딩 → 저장
벡터 스토어 검색 메타데이터 필터로 검색
사용자 지정 청킹 청크 크기와 오버랩 설정
메타데이터 필터링 사용자 지정 메타데이터로 필터
Citations grounding 메타데이터에서 추출

빠른 시작 (Quick Start)

설정 (Setup)

Gemini API 키를 설정해요:

export GEMINI_API_KEY="your-api-key"
# or
export GOOGLE_API_KEY="your-api-key"

기본 RAG Ingest

Python SDK:

import litellm

# Ingest a document
response = await litellm.aingest(
    ingest_options={
        "name": "my-document-store",
        "vector_store": {
            "custom_llm_provider": "gemini"
        }
    },
    file_data=("document.txt", b"Your document content", "text/plain")
)

print(f"Vector Store ID: {response['vector_store_id']}")
print(f"File ID: {response['file_id']}")

LiteLLM Proxy:

curl -X POST "http://localhost:4000/v1/rag/ingest" \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "file": {
      "filename": "document.txt",
      "content": "'"$(base64 -i document.txt)"'",
      "content_type": "text/plain"
    },
    "ingest_options": {
      "name": "my-document-store",
      "vector_store": {
        "custom_llm_provider": "gemini"
      }
    }
  }'

벡터 스토어 검색

Python SDK:

import litellm

# Search the vector store
response = await litellm.vector_stores.asearch(
    vector_store_id="fileSearchStores/your-store-id",
    query="What is the main topic?",
    custom_llm_provider="gemini",
    max_num_results=5
)

for result in response["data"]:
    print(f"Score: {result.get('score')}")
    print(f"Content: {result['content'][0]['text']}")

LiteLLM Proxy:

curl -X POST "http://localhost:4000/v1/vector_stores/fileSearchStores/your-store-id/search" \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What is the main topic?",
    "custom_llm_provider": "gemini",
    "max_num_results": 5
  }'

고급 기능 (Advanced Features)

사용자 지정 청킹 구성

문서를 청크로 분할하는 방법을 제어해요.

import litellm

response = await litellm.aingest(
    ingest_options={
        "name": "custom-chunking-store",
        "vector_store": {
            "custom_llm_provider": "gemini"
        },
        "chunking_strategy": {
            "white_space_config": {
                "max_tokens_per_chunk": 200,
                "max_overlap_tokens": 20
            }
        }
    },
    file_data=("document.txt", document_content, "text/plain")
)

청킹 파라미터:

  • max_tokens_per_chunk: 청크당 최대 토큰 수 (기본: 800, 최소: 100, 최대: 4096)
  • max_overlap_tokens: 청크 간 오버랩 (기본: 400)

메타데이터 필터링

파일에 사용자 지정 메타데이터를 붙이고 검색을 필터링해요.

Ingest 중 메타데이터 첨부:

import litellm

response = await litellm.aingest(
    ingest_options={
        "name": "metadata-store",
        "vector_store": {
            "custom_llm_provider": "gemini",
            "custom_metadata": [
                {"key": "author", "string_value": "John Doe"},
                {"key": "year", "numeric_value": 2024},
                {"key": "category", "string_value": "documentation"}
            ]
        }
    },
    file_data=("document.txt", document_content, "text/plain")
)

메타데이터 필터로 검색:

import litellm

response = await litellm.vector_stores.asearch(
    vector_store_id="fileSearchStores/your-store-id",
    query="What is LiteLLM?",
    custom_llm_provider="gemini",
    filters={"author": "John Doe", "category": "documentation"}
)

필터 구문:

  • 단순 동등: {"key": "value"}
  • Gemini 변환: key="value"
  • 여러 필터는 AND로 결합

기존 벡터 스토어 사용

기존 File Search 스토어에 ingest하고 싶을 때:

import litellm

# First, create a store
create_response = await litellm.vector_stores.acreate(
    name="My Persistent Store",
    custom_llm_provider="gemini"
)
store_id = create_response["id"]

# Then ingest multiple documents into it
for doc in documents:
    await litellm.aingest(
        ingest_options={
            "vector_store": {
                "custom_llm_provider": "gemini",
                "vector_store_id": store_id  # Reuse existing store
            }
        },
        file_data=(doc["name"], doc["content"], doc["type"])
    )

Citation 추출

Gemini는 citations와 함께 grounding metadata를 제공해요.

import litellm

response = await litellm.vector_stores.asearch(
    vector_store_id="fileSearchStores/your-store-id",
    query="Explain the concept",
    custom_llm_provider="gemini"
)

for result in response["data"]:
    # Access citation information
    if "attributes" in result:
        print(f"URI: {result['attributes'].get('uri')}")
        print(f"Title: {result['attributes'].get('title')}")
    # Content with relevance score
    print(f"Score: {result.get('score')}")
    print(f"Text: {result['content'][0]['text']}")

완전한 예시 (Complete Example)

end-to-end 워크플로:

import litellm

# 1. Create a File Search store
store_response = await litellm.vector_stores.acreate(
    name="Knowledge Base",
    custom_llm_provider="gemini"
)
store_id = store_response["id"]
print(f"Created store: {store_id}")

# 2. Ingest documents with custom chunking and metadata
documents = [
    {
        "name": "intro.txt",
        "content": b"Introduction to LiteLLM...",
        "metadata": [
            {"key": "section", "string_value": "intro"},
            {"key": "priority", "numeric_value": 1}
        ]
    },
    {
        "name": "advanced.txt",
        "content": b"Advanced features...",
        "metadata": [
            {"key": "section", "string_value": "advanced"},
            {"key": "priority", "numeric_value": 2}
        ]
    }
]

for doc in documents:
    ingest_response = await litellm.aingest(
        ingest_options={
            "name": f"ingest-{doc['name']}",
            "vector_store": {
                "custom_llm_provider": "gemini",
                "vector_store_id": store_id,
                "custom_metadata": doc["metadata"]
            },
            "chunking_strategy": {
                "white_space_config": {
                    "max_tokens_per_chunk": 300,
                    "max_overlap_tokens": 50
                }
            }
        },
        file_data=(doc["name"], doc["content"], "text/plain")
    )
    print(f"Ingested: {doc['name']}")

# 3. Search with filters
search_response = await litellm.vector_stores.asearch(
    vector_store_id=store_id,
    query="How do I get started?",
    custom_llm_provider="gemini",
    filters={"section": "intro"},
    max_num_results=3
)

# 4. Process results
for i, result in enumerate(search_response["data"]):
    print(f"\nResult {i+1}:")
    print(f"  Score: {result.get('score')}")
    print(f"  File: {result.get('filename')}")
    print(f"  Content: {result['content'][0]['text'][:100]}...")

지원 파일 유형 (Supported File Types)

문서

  • PDF (application/pdf)
  • Microsoft Word (.docx, .doc)
  • Microsoft Excel (.xlsx, .xls)
  • Microsoft PowerPoint (.pptx)
  • OpenDocument 형식 (.odt, .ods, .odp)

텍스트 파일

  • 일반 텍스트 (text/plain)
  • Markdown (text/markdown)
  • HTML (text/html)
  • CSV (text/csv)
  • JSON (application/json)
  • XML (application/xml)

코드 파일

  • Python, JavaScript, TypeScript, Java, C/C++, Go, Rust 등
  • 대부분의 일반적인 프로그래밍 언어 지원

Gemini의 전체 지원 파일 유형 목록을 참고하세요.

가격 (Pricing)

  • 인덱싱: 백만 토큰당 $0.15 (임베딩 가격)
  • 저장: 무료
  • 쿼리 임베딩: 무료
  • 검색된 토큰: 일반 컨텍스트 토큰으로 청구

지원 모델 (Supported Models)

File Search는 다음과 함께 동작해요:

  • gemini-3.1-pro-preview
  • gemini-3.8-flash (및 preview 버전)

문제 해결 (Troubleshooting)

인증 에러

# Ensure API key is set
import os
os.environ["GEMINI_API_KEY"] = "your-api-key"

# Or pass explicitly
response = await litellm.aingest(
    ingest_options={
        "vector_store": {
            "custom_llm_provider": "gemini",
            "api_key": "your-api-key"
        }
    },
    file_data=(...)
)

스토어를 찾을 수 없음

전체 스토어 이름 형식을 사용하세요:

  • fileSearchStores/abc123
  • abc123

대용량 파일

100MB보다 큰 파일은 ingest 전에 더 작은 청크로 분할하세요.

느린 인덱싱

ingest 후 Gemini가 문서를 인덱싱하는 데 시간이 걸릴 수 있어요. 검색 전에 몇 초 기다리세요.

import time

# After ingest
await litellm.aingest(...)

# Wait for indexing
time.sleep(5)

# Then search
await litellm.vector_stores.asearch(...)

더 알아보기 (Learn more)