MongoDB의 샘플 문서와 채팅하기

MongoDB의 샘플 문서와 채팅하기 (BETA)

세 개의 가상 정책 문서를 만들고 MongoDB Atlas에 인덱싱한 뒤, LiteLLM Admin UI에서 시맨틱 검색을 테스트하고 결과를 채팅 completion에 사용해 봐요. 아래 예시 텍스트는 이 튜토리얼을 위해 작성된 것으로, 실제 회사 정책을 설명하지 않습니다.

BETA

MongoDB 벡터 스토어는 LiteLLM의 BETA 기능이에요. 이 통합은 기존 MongoDB 인덱스를 검색합니다. 이 튜토리얼은 MongoDB Python 드라이버로 문서를 준비한 뒤 LiteLLM에 인덱스를 등록합니다. 일반 설정과 제한 사항은 통합 가이드를 참고하세요.

시작하기 전에

다음이 필요합니다:

  • Vector Search와 추가 검색 인덱스 용량이 있는 Atlas 클러스터, 데모 컬렉션을 만들고 읽을 수 있는 데이터베이스 사용자, 인덱스 생성 권한.
  • 설정 스크립트와 MongoDB sidecar 양쪽에서 클러스터로의 연결 문자열과 네트워크 접근.
  • litellm[proxy]가 설치된 실행 중인 LiteLLM proxy, 저장된 등록을 위한 구성된 데이터베이스, Admin UI 접근.
  • 이 예시에서 사용하는 embedding/chat 모델용 OpenAI API 키. 다른 제공자도 문서와 쿼리 임베딩이 같은 모델과 차원을 사용한다면 사용할 수 있어요.

LiteLLM에 모델 추가

LiteLLM Admin UI의 Models 아래에서 OpenAI API 키로 다음 배포를 추가하거나, proxy에 이미 있는 동등한 배포를 재사용하세요:

| Purpose | Provider | Provider model | Name on the proxy | | Embed documents and search queries | OpenAI | text-embedding-3-small | text-embedding-3-small | | Generate chat answers | OpenAI | gpt-4o-mini | gpt-4o-mini |

설정 파일에서 LiteLLM 모델 식별자는 openai/text-embedding-3-smallopenai/gpt-4o-mini예요. embedding 배포에 model_info.mode: embedding을 설정해 UI가 embedding 모델로 식별하게 하세요. 이 예시에서는 embedding 모델의 기본 1536 dimensions를 사용합니다.

샘플 문서 준비

별도 설정 환경에 의존성을 설치하세요. PyMongo는 샘플 데이터를 준비하는 데 사용되며, LiteLLM proxy나 SDK의 의존성이 아니에요:

python -m venv .venv-mongodb-setupsource .venv-mongodb-setup/bin/activatepip install openai pymongo

MONGODB_CONNECTION_STRING을 클러스터의 전체 URI로, LITELLM_API_KEY를 embedding 모델 접근이 가능한 LiteLLM 키로 설정하세요. proxy가 다른 주소를 사용하면 LITELLM_BASE_URL을 설정하세요:

export MONGODB_CONNECTION_STRING='mongodb+srv://<user>:<pass>@<cluster>/?...'export LITELLM_API_KEY='<key>'export LITELLM_BASE_URL='http://localhost:4000/v1'

Atlas 웹사이트 로그인과는 별개인 데이터베이스 사용자의 자격 증명을 사용하세요. 사용자 이름과 비밀번호의 특수 문자는 percent-encode 하세요.

이것을 prepare_documents.py로 저장하고 python prepare_documents.py로 실행하세요. 이 스크립트는 proxy의 embeddings API를 통해 원본 샘플 텍스트를 임베딩하고 PyMongo를 사용해 문서를 삽입합니다. 데모 컬렉션이 이미 존재하면 중단되므로 기존 데이터를 덮어쓰지 않아요.

prepare_documents.py

import osfrom openai import OpenAIfrom pymongo import MongoClientsamples = [
    {
        "_id": "projector-booking",
        "text": "For this fictional demo, projectors may be reserved for 45 minutes. Include reservation code DEMO-7321 with every projector booking.",
    },
    {
        "_id": "desk-reservation",
        "text": "For this fictional demo, standing desks can be reserved for two hours. Cancel a desk reservation at least 15 minutes before it starts.",
    },
    {
        "_id": "visitor-badges",
        "text": "For this fictional demo, visitors collect badges at the welcome desk. Return each badge before leaving the building.",
    },
]with MongoClient(os.environ["MONGODB_CONNECTION_STRING"]) as mongo:    database = mongo["litellm_docs_demo"]
    if "policies" in database.list_collection_names():
        raise RuntimeError("Demo collection already exists. Use a fresh database for this tutorial.")
    with OpenAI(
        base_url=os.environ.get("LITELLM_BASE_URL", "http://localhost:4000/v1"),
        api_key=os.environ["LITELLM_API_KEY"],
    ) as client:
        embeddings = client.embeddings.create(
            model="text-embedding-3-small",
            input=[document["text"] for document in samples],
        )
    for item in embeddings.data:
        samples[item.index]["embedding"] = item.embedding
    collection = database.create_collection("policies")
    collection.insert_many(samples)
    print("Inserted three sample documents into litellm_docs_demo.policies.")

문서 삽입은 LiteLLM의 벡터 스토어 API 밖에서 설정 스크립트가 수행합니다. LiteLLM의 MongoDB 통합은 /rag/ingest나 벡터 스토어 파일 업로드를 지원하지 않아요.

Atlas 인덱스 준비

Atlas에서 litellm_docs_demo.policiesVector Search 인덱스를 만들고 litellm_demo_policy_idx로 이름 지으세요. 다음 정의를 사용합니다:

Vector Search index definition

{
  "fields": [
    {
      "type": "vector",
      "path": "embedding",
      "numDimensions": 1536,
      "similarity": "cosine"
    }
  ]
}

READY 상태가 되고 쿼리 가능해질 때까지 기다리세요. 데이터베이스, 컬렉션, 인덱스 이름을 바꾸면 나머지 단계에서 그 값들을 사용하세요.

MongoDB sidecar 배포

Docker, Compose, Kubernetes용 sidecar 배포 가이드를 따르세요. sidecar의 MONGODB_CONNECTION_STRING을 설정 스크립트가 사용하는 URI로, MONGODB_SIDECAR_API_KEY를 LiteLLM과 공유하는 강력한 비밀로 설정하세요. URI와 MongoDB TLS 파일은 sidecar에 유지됩니다.

Docker 호스트에서 실행되는 proxy의 경우 Sidecar URL로 http://127.0.0.1:8080을 사용하세요. Compose 예시는 LiteLLM의 네트워크 네임스페이스를 공유하며 같은 loopback URL을 사용합니다. 원격 sidecar는 HTTPS가 필요해요. 인덱스를 등록하기 전에 sidecar의 /health/readiness 엔드포인트가 HTTP 200을 반환하는지 확인하세요.

Admin UI에서 인덱스 등록

Tools > Vector Stores > Manage Vector Stores > + Add Vector Store를 연 뒤 다음을 입력하세요:

| UI field | Value | | Provider | MongoDB (BETA) | | Vector Store Name | MongoDB Demo Policies | | Vector Store ID | litellm_demo_policy_idx | | Sidecar URL | The sidecar address reachable from your LiteLLM proxy. | | Sidecar API Key | The sidecar's MONGODB_SIDECAR_API_KEY value. | | Database | litellm_docs_demo | | Collection | policies | | Embedding Model | text-embedding-3-small | | Vector Field Name | embedding | | Text Field | text | | Candidates Considered | Leave blank. |

Create를 클릭하세요. 이 인덱스가 proxy에 이미 등록됐다면 다음 단계에서 기존 등록을 선택하세요. 쿼리 embedding 모델은 설정 스크립트에서 사용한 모델과 동일하게 유지하세요. 채팅 모델은 독립적으로 변경할 수 있어요.

검색 테스트

Test Vector Store에서 MongoDB Demo Policies를 선택하고 다음을 실행하세요:

How long can I book a projector, and which reservation code should I use?

ID가 projector-booking인 문서를 찾으세요. 그 텍스트에는 45 minutesDEMO-7321이 포함되어야 해요. 결과를 펼쳐 검색된 텍스트를 확인하세요. 유사도 점수는 달라질 수 있어요.

API를 통해서도 같은 검색을 실행할 수 있어요. 이 스토어 접근이 가능한 LiteLLM 키를 사용하고, proxy가 다른 주소를 쓰면 http://localhost:4000을 바꾸세요:

curl -X POST 'http://localhost:4000/v1/vector_stores/litellm_demo_policy_idx/search' \
  -H "Authorization: Bearer ***" \
  -H 'Content-Type: application/json' \
  -d '{
    "query": "How long can I book a projector, and which reservation code should I use?",
    "max_num_results": 3
  }'

이것은 연결, 쿼리 임베딩, 인덱스, 반환 텍스트를 함께 확인합니다. 샘플 문서에 관한 질문으로 관련성(relevance)을 평가해 보세요.

채팅 completion에서 문서 사용

실행 중인 proxy에 등록된 첫 벡터 스토어라면, 채팅 테스트 전에 proxy의 데이터베이스 동기화를 기다리거나 재시작하세요. 첫 등록 관련 참고를 보세요.

스토어와 채팅 모델 모두에 접근할 수 있는 LiteLLM 키를 사용하세요:

curl -X POST 'http://localhost:4000/v1/chat/completions' \
  -H "Authorization: Bearer ***" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [
      {
        "role": "system",
        "content": "Use the provided demo policies to answer the question. If there is no relevant context, say you do not know."
      },
      {
        "role": "user",
        "content": "How long can I book a projector, and which reservation code should I use?"
      }
    ],
    "tools": [
      {
        "type": "file_search",
        "vector_store_ids": ["litellm_demo_policy_idx"]
      }
    ]
  }'

응답의 두 부분을 검증하세요:

  • choices[0].message.content45 minutesDEMO-7321로 답하는지.
  • choices[0].message.provider_specific_fields.search_resultsprojector-booking 문서와 그 텍스트를 포함하는지.

채팅 응답이 성공했다고 해서 검색(retrieval)이 동작했다는 뜻은 아니에요. 소스 결과를 확인해 MongoDB가 컨텍스트를 제공했는지 확인하세요. 일반 채팅 가이드에는 이 결과를 출력하는 Python 예시가 있어요.

자체 컬렉션에 대해서는 MongoDB 통합 가이드를 사용해 데이터베이스, 컬렉션, 인덱스, 필드 이름, embedding 모델을 바꾸세요.

더 알아보기 (Learn more)