문서 메뉴
문서 홈
/
MongoDB 아틀라스
/ /

시맨틱 커널 Python 통합 시작하기

이 페이지의 내용

  • 배경
  • 전제 조건
  • 환경 설정
  • Atlas에 사용자 지정 데이터 저장
  • Atlas Vector Search 인덱스 만들기
  • Vector Search 쿼리 실행
  • 데이터에 대한 질문에 답변
  • 다음 단계

참고

이 튜토리얼에서는 시맨틱 커널 Python 라이브러리 를 사용합니다. . C# 라이브러리를 사용하는 튜토리얼은 시맨틱 커널 C# 통합 시작하기를 참조하세요.

Atlas Vector Search를 Microsoft 시맨틱 커널 과 통합할 수 있습니다. AI 애플리케이션을 구축하고 RAG(검색 강화 생성)를 구현합니다. 이 튜토리얼에서는 시맨틱 커널과 함께 Atlas Vector Search 를 사용하여 데이터에 대해 시맨틱 Atlas Search를 수행하고 RAG 구현을 빌드하는 방법을 보여 줍니다. 구체적으로 다음 조치를 수행합니다.

  1. 환경을 설정합니다.

  2. Atlas에 사용자 지정 데이터를 저장합니다.

  3. 데이터에 Atlas Vector Search 검색 인덱스를 만듭니다.

  4. 데이터에 대해 시맨틱 검색 쿼리를 실행합니다.

  5. Atlas Vector Search를 사용하여 RAG를 구현하여 데이터에 대한 질문에 답변하세요.

시맨틱 커널은 다양한 AI 서비스 및 플러그인을 애플리케이션과 결합할 수 있는 오픈 소스 SDK입니다. 시맨틱 커널은 RAG 를 포함한 다양한 AI 사용 사례에 사용할 수 있습니다.

Atlas Vector Search를 시맨틱 커널과 통합하면 Atlas를 벡터 데이터베이스로 사용하고 Atlas Vector Search를 사용하여 데이터에서 의미적으로 유사한 문서를 검색하여 RAG 를 구현할 수 있습니다. RAG 에 대해 자세히 알아보려면 Atlas Vector Search를 사용한 검색-증강 생성(RAG)을 참조하세요.

이 튜토리얼을 완료하려면 다음 조건을 충족해야 합니다.

  • MongoDB 버전 6 을(를) 실행하는 Atlas 클러스터입니다.0.11, 7.0.2 이상( RC 포함). 사용자의 IP 주소 가 Atlas 프로젝트의 액세스 목록에 포함되어 있는지 확인하세요.

  • OpenAI API 키입니다. API 요청에 사용할 수 있는 크레딧이 있는 유료 OpenAI 계정이 있어야 합니다.

  • Colab과같은 대화형 Python 노트북을 실행할 수 있는 환경입니다.

먼저 이 튜토리얼을 진행하려면 환경을 설정해야 합니다. 확장자가 .ipynb 인 파일을 저장하여 대화형 Python 노트북을 만든 후 노트북에서 다음 코드 스니펫을 실행합니다.

1
  1. 노트북에서 다음 명령을 실행하여 환경에 시맨틱 커널을 설치합니다.

    pip install --quiet --upgrade semantic-kernel openai motor
  2. 다음 코드를 실행하여 필요한 패키지를 가져옵니다.

    import getpass, openai
    import semantic_kernel as sk
    from semantic_kernel.connectors.ai.open_ai import (OpenAIChatCompletion, OpenAITextEmbedding)
    from semantic_kernel.connectors.memory.mongodb_atlas import MongoDBAtlasMemoryStore
    from semantic_kernel.core_plugins.text_memory_plugin import TextMemoryPlugin
    from semantic_kernel.memory.semantic_text_memory import SemanticTextMemory
    from semantic_kernel.prompt_template.input_variable import InputVariable
    from semantic_kernel.prompt_template.prompt_template_config import PromptTemplateConfig
    from pymongo import MongoClient
    from pymongo.operations import SearchIndexModel
2

다음 코드를 실행하고 메시지가 표시되면 다음을 제공합니다.

OPENAI_API_KEY = getpass.getpass("OpenAI API Key:")
ATLAS_CONNECTION_STRING = getpass.getpass("MongoDB Atlas SRV Connection String:")

참고

연결 문자열은 다음 형식을 사용해야 합니다.

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

이 섹션에서는 커널 을 초기화합니다. 애플리케이션의 서비스 및 플러그인을 관리하는 데 사용되는 기본 인터페이스입니다. 커널을 통해 AI 서비스를 구성하고, Atlas를 벡터 데이터베이스(메모리 저장소라고도 함)로 인스턴스화하고, 사용자 지정 데이터를 Atlas cluster에 로드합니다.

Atlas에 사용자 지정 데이터를 저장하려면 노트북에 다음 코드 스니펫을 붙여넣고 실행하세요.

1

다음 코드를 실행하여 커널을 초기화합니다.

kernel = sk.Kernel()
2

다음 코드를 실행하여 이 튜토리얼에 사용된 OpenAI 임베딩 모델 및 채팅 모델을 구성하고 이러한 서비스를 커널에 추가합니다. 이 코드는 다음을 지정합니다:

  • 텍스트를 벡터 임베딩으로 변환하는 데 사용되는 임베딩 모델인 OpenAI의 text-embedding-ada-002 .

  • 응답 생성에 사용되는 채팅 모델인 OpenAI의 gpt-3.5-turbo .

chat_service = OpenAIChatCompletion(
service_id="chat",
ai_model_id="gpt-3.5-turbo",
api_key=OPENAI_API_KEY
)
embedding_service = OpenAITextEmbedding(
ai_model_id="text-embedding-ada-002",
api_key=OPENAI_API_KEY
)
kernel.add_service(chat_service)
kernel.add_service(embedding_service)
3

다음 코드를 실행하여 Atlas를 메모리 저장소로 인스턴스화하고 커널에 추가합니다. 이 코드는 Atlas 클러스터에 대한 연결을 설정하고 다음을 지정합니다.

  • semantic_kernel_db 문서를 저장하는 데 사용되는 Atlas 데이터베이스입니다.

  • vector_index 시맨틱 Atlas Search 쿼리를 실행하는 데 사용되는 인덱스로 사용됩니다.

또한 플러그인 TextMemoryPlugin 가져옵니다. 라고 하며, 메모리에 텍스트를 저장하고 검색하는 데 도움이 되는 네이티브 함수 그룹을 제공합니다.

mongodb_atlas_memory_store = MongoDBAtlasMemoryStore(
connection_string=ATLAS_CONNECTION_STRING,
database_name="semantic_kernel_db",
index_name="vector_index"
)
memory = SemanticTextMemory(
storage=mongodb_atlas_memory_store,
embeddings_generator=embedding_service
)
kernel.add_plugin(TextMemoryPlugin(memory), "TextMemoryPlugin")
4

이 코드는 semantic_kernel_db.test 컬렉션을 몇 가지 샘플 문서로 채우는 함수를 정의하고 실행합니다. 이러한 문서에는 LLM 이 원래 액세스할 수 없었던 개인화된 데이터가 포함되어 있습니다.

async def populate_memory(kernel: sk.Kernel) -> None:
await memory.save_information(
collection="test", id="1", text="I am a developer"
)
await memory.save_information(
collection="test", id="2", text="I started using MongoDB two years ago"
)
await memory.save_information(
collection="test", id="3", text="I'm using MongoDB Vector Search with Semantic Kernel to implement RAG"
)
await memory.save_information(
collection="test", id="4", text="I like coffee"
)
print("Populating memory...")
await populate_memory(kernel)
print(kernel)
Populating memory...
plugins=KernelPluginCollection(plugins={'TextMemoryPlugin': KernelPlugin(name='TextMemoryPlugin', description=None, functions={'recall': KernelFunctionFromMethod(metadata=KernelFunctionMetadata(name='recall', plugin_name='TextMemoryPlugin', description='Recall a fact from the long term memory', parameters=[KernelParameterMetadata(name='ask', description='The information to retrieve', default_value=None, type_='str', is_required=True, type_object=<class 'str'>), KernelParameterMetadata(name='collection', description='The collection to search for information.', default_value='generic', type_='str', is_required=False, type_object=<class 'str'>), KernelParameterMetadata(name='relevance', description='The relevance score, from 0.0 to 1.0; 1.0 means perfect match', default_value=0.75, type_='float', is_required=False, type_object=<class 'float'>), KernelParameterMetadata(name='limit', description='The maximum number of relevant memories to recall.', default_value=1, type_='int', is_required=False, type_object=<class 'int'>)], is_prompt=False, is_asynchronous=True, return_parameter=KernelParameterMetadata(name='return', description='', default_value=None, type_='str', is_required=True, type_object=None)), method=<bound method TextMemoryPlugin.recall of TextMemoryPlugin(memory=SemanticTextMemory())>, stream_method=None), 'save': KernelFunctionFromMethod(metadata=KernelFunctionMetadata(name='save', plugin_name='TextMemoryPlugin', description='Save information to semantic memory', parameters=[KernelParameterMetadata(name='text', description='The information to save.', default_value=None, type_='str', is_required=True, type_object=<class 'str'>), KernelParameterMetadata(name='key', description='The unique key to associate with the information.', default_value=None, type_='str', is_required=True, type_object=<class 'str'>), KernelParameterMetadata(name='collection', description='The collection to save the information.', default_value='generic', type_='str', is_required=False, type_object=<class 'str'>)], is_prompt=False, is_asynchronous=True, return_parameter=KernelParameterMetadata(name='return', description='', default_value=None, type_='', is_required=True, type_object=None)), method=<bound method TextMemoryPlugin.save of TextMemoryPlugin(memory=SemanticTextMemory())>, stream_method=None)})}) services={'chat': OpenAIChatCompletion(ai_model_id='gpt-3.5-turbo', service_id='chat', client=<openai.AsyncOpenAI object at 0x7999971c8fa0>, ai_model_type=<OpenAIModelTypes.CHAT: 'chat'>, prompt_tokens=0, completion_tokens=0, total_tokens=0), 'text-embedding-ada-002': OpenAITextEmbedding(ai_model_id='text-embedding-ada-002', service_id='text-embedding-ada-002', client=<openai.AsyncOpenAI object at 0x7999971c8fd0>, ai_model_type=<OpenAIModelTypes.EMBEDDING: 'embedding'>, prompt_tokens=32, completion_tokens=0, total_tokens=32)} ai_service_selector=<semantic_kernel.services.ai_service_selector.AIServiceSelector object at 0x7999971cad70> retry_mechanism=PassThroughWithoutRetry() function_invoking_handlers={} function_invoked_handlers={}

샘플 코드를 실행한semantic_kernel_db.test cluster의 collection으로 이동 하여 Atlas UI에서 벡터 임베딩을 볼 수 있습니다.

참고

Atlas Vector Search 검색 인덱스를 만들려면 Atlas 프로젝트에 대한 Project Data Access Admin 이상의 액세스 권한이 있어야 합니다.

벡터 저장소에서 벡터 검색 쿼리를 활성화하려면 semantic_kernel_db.test 컬렉션에 Atlas Vector Search 인덱스를 생성하세요.

노트북에서 다음 코드를 실행하여 Atlas cluster에 연결하고 vectorSearch 유형의 인덱스를 생성합니다. 이 인덱스 정의는 다음 필드의 인덱싱을 지정합니다.

  • embedding 필드를 벡터 유형으로 지정합니다. embedding 필드에는 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536 벡터 차원을 지정하고 cosine 를 사용하여 유사성을 측정합니다.

# Connect to your Atlas cluster and specify the collection
client = MongoClient(ATLAS_CONNECTION_STRING)
collection = client["semantic_kernel_db"]["test"]
# Create your index model, then create the search index
search_index_model = SearchIndexModel(
definition={
"fields": [
{
"type": "vector",
"path": "embedding",
"numDimensions": 1536,
"similarity": "cosine"
}
]
},
name="vector_index",
type="vectorSearch"
)
collection.create_search_index(model=search_index_model)

인덱스를 빌드하는 데 약 1분 정도 걸립니다. 빌드되는 동안 인덱스는 초기 동기화 상태입니다. 빌드가 완료되면 컬렉션의 데이터 쿼리를 시작할 수 있습니다.

Atlas 가 인덱스를 빌드하면 데이터에 대해 벡터 Atlas Search 쿼리를 실행할 수 있습니다.

노트북에서 다음 코드를 실행하여 문자열 What is my job title? 에 대한 기본 시맨틱 검색을 수행합니다. 가장 관련성이 높은 문서와 0 ~ 1 사이의 관련성 점수 를 인쇄합니다.

result = await memory.search("test", "What is my job title?")
print(f"Retrieved document: {result[0].text}, {result[0].relevance}")
Retrieved document: I am a developer, 0.8991971015930176

이 섹션에서는 Atlas Vector Search 및 시맨틱 커널을 사용한 RAG 구현의 예를 보여줍니다. 이제 Atlas Vector Search를 사용하여 의미적으로 유사한 문서를 조회했으므로, 다음 코드 예제를 실행하여 LLM 이 해당 문서를 기반으로 질문에 답변하도록 프롬프트를 표시합니다.

다음 코드는 프롬프트 를 정의합니다.검색된 문서를 쿼리의 컨텍스트로 사용하도록 LLM 에 지시합니다. 이 예에서는 샘플 쿼리 When did I start using MongoDB? 을 사용하여 LLM 에 프롬프트를 표시합니다. 사용자 지정 데이터로 LLM 의 지식 기반을 보강했기 때문에 채팅 모델은 보다 정확하고 상황을 인식하는 응답을 생성할 수 있습니다.

service_id = "chat"
settings = kernel.get_service(service_id).instantiate_prompt_execution_settings(
service_id=service_id
)
prompt_template = """
Answer the following question based on the given context.
Question: {{$input}}
Context: {{$context}}
"""
chat_prompt_template_config = PromptTemplateConfig(
execution_settings=settings,
input_variables=[
InputVariable(name="input"),
InputVariable(name="context")
],
template=prompt_template
)
prompt = kernel.add_function(
function_name="RAG",
plugin_name="TextMemoryPlugin",
prompt_template_config=chat_prompt_template_config,
)
question = "When did I start using MongoDB?"
results = await memory.search("test", question)
retrieved_document = results[0].text
answer = await prompt.invoke(
kernel=kernel, input=question, context=retrieved_document
)
print(answer)
You started using MongoDB two years ago.

MongoDB는 다음과 같은 개발자 리소스도 제공합니다.

다음도 참조하세요.

돌아가기

시맨틱 커널 C#

다음

커다란 건초 더미