This page provides practical code examples for implementing knowledge base operations. For broader documentation and concepts, see the Knowledge Base Documentation.
# Configure ingestion settingscontent=kb_service.upload_content(path_to_content=str(file_path),content_name=Path(file_path).name,mime_type="text/plain",scope_id=scope_id,skip_ingestion=False,# Process the content for searchmetadata={"department":"legal","classification":"confidential"})
uploaded_content=kb_service.upload_content(path_to_content=str(output_filepath),content_name=output_filepath.name,mime_type=str(mimetypes.guess_type(output_filepath)[0]),chat_id=payload.chat_id,skip_ingestion=skip_ingestion,# Usually True for generated files)reference=ContentReference(id=content.id,sequence_number=1,message_id=message_id,name=filename,source=payload.name,source_id=chat_id,url=f"unique://content/{uploaded_content.id}",# Special URL format for content)self.chat_service.modify_assistant_message(content="Please find the translated document below in the references.",references=[reference],set_completed_at=True,)
# %%frompathlibimportPathfromdotenvimportdotenv_valuesfromunique_toolkitimport(KnowledgeBaseService,)kb_service=KnowledgeBaseService.from_settings()demo_env_vars=dotenv_values(Path(__file__).parent/"demo.env")scope_id=demo_env_vars.get("UNIQUE_SCOPE_ID")or"unknown"file_path=Path(__file__).parent/"test.txt"# Configure ingestion settingscontent=kb_service.upload_content(path_to_content=str(file_path),content_name=Path(file_path).name,mime_type="text/plain",scope_id=scope_id,skip_ingestion=False,# Process the content for searchmetadata={"department":"legal","classification":"confidential"},)
# Download content as bytescontent_bytes=kb_service.download_content_to_bytes(content_id=content_idor"unknown",)# Process in memorytext=""withio.BytesIO(content_bytes)asfile_like:text=file_like.read().decode("utf-8")print(text)
# Download to secure temporary filefilename="my_testfile.txt"temp_file_path=kb_service.download_content_to_file(content_id=content_id,output_filename=filename,output_dir_path=Path(tempfile.mkdtemp())# Use secure temp directory)try:# Process the filewithopen(temp_file_path,'rb')asfile:text=file.read().decode("utf-8")print(text)finally:# Always clean up temporary filesiftemp_file_path.exists():temp_file_path.unlink()# Clean up the temporary directorytemp_file_path.parent.rmdir()
# %%importiofrompathlibimportPathfromdotenvimportdotenv_valuesfromunique_toolkitimport(KnowledgeBaseService,)kb_service=KnowledgeBaseService.from_settings()demo_env_vars=dotenv_values(Path(__file__).parent/"demo.env")content_id=demo_env_vars.get("UNIQUE_CONTENT_ID")or"unknown"# Download content as bytescontent_bytes=kb_service.download_content_to_bytes(content_id=content_idor"unknown",)# Process in memorytext=""withio.BytesIO(content_bytes)asfile_like:text=file_like.read().decode("utf-8")print(text)
# %%importtempfilefrompathlibimportPathfromdotenvimportdotenv_valuesfromunique_toolkitimport(KnowledgeBaseService,)kb_service=KnowledgeBaseService.from_settings()demo_env_vars=dotenv_values(Path(__file__).parent/"demo.env")content_id=demo_env_vars.get("UNIQUE_CONTENT_ID")or"unknown"# Download to secure temporary filefilename="my_testfile.txt"temp_file_path=kb_service.download_content_to_file(content_id=content_id,output_filename=filename,output_dir_path=Path(tempfile.mkdtemp()),# Use secure temp directory)try:# Process the filewithopen(temp_file_path,"rb")asfile:text=file.read().decode("utf-8")print(text)finally:# Always clean up temporary filesiftemp_file_path.exists():temp_file_path.unlink()# Clean up the temporary directorytemp_file_path.parent.rmdir()
# Search for content using vector similaritycontent_chunks=kb_service.search_content_chunks(search_string="Harry Potter",search_type=ContentSearchType.VECTOR,limit=10,score_threshold=0.7,# Only return results with high similarityscope_ids=[scope_id])print(f"Found {len(content_chunks)} relevant chunks")fori,chunkinenumerate(content_chunks[:3]):print(f" {i+1}. {chunk.text[:100]}...")
# Combined semantic and keyword search for best resultscontent_chunks=kb_service.search_content_chunks(search_string="Harry Potter",search_type=ContentSearchType.COMBINED,limit=15,search_language="english",scope_ids=[scope_id],# Limit to specific scopes if configured)print(f"Combined search found {len(content_chunks)} chunks")
# %%frompathlibimportPathfromdotenvimportdotenv_valuesfromunique_toolkitimport(KnowledgeBaseService,)fromunique_toolkit.content.schemasimport(ContentSearchType,)kb_service=KnowledgeBaseService.from_settings()demo_env_vars=dotenv_values(Path(__file__).parent/"demo.env")scope_id=demo_env_vars.get("UNIQUE_SCOPE_ID")or"unknown"# Search for content using vector similaritycontent_chunks=kb_service.search_content_chunks(search_string="Harry Potter",search_type=ContentSearchType.VECTOR,limit=10,score_threshold=0.7,# Only return results with high similarityscope_ids=[scope_id],)print(f"Found {len(content_chunks)} relevant chunks")fori,chunkinenumerate(content_chunks[:3]):print(f" {i+1}. {chunk.text[:100]}...")
# %%frompathlibimportPathfromdotenvimportdotenv_valuesfromunique_toolkitimport(KnowledgeBaseService,)fromunique_toolkit.content.schemasimport(ContentSearchType,)kb_service=KnowledgeBaseService.from_settings()demo_env_vars=dotenv_values(Path(__file__).parent/"demo.env")scope_id=demo_env_vars.get("UNIQUE_SCOPE_ID")or"unknown"# Combined semantic and keyword search for best resultscontent_chunks=kb_service.search_content_chunks(search_string="Harry Potter",search_type=ContentSearchType.COMBINED,limit=15,search_language="english",scope_ids=[scope_id],# Limit to specific scopes if configured)print(f"Combined search found {len(content_chunks)} chunks")
# %%frompathlibimportPathfromdotenvimportdotenv_valuesfromunique_toolkitimport(KnowledgeBaseService,)kb_service=KnowledgeBaseService.from_settings()demo_env_vars=dotenv_values(Path(__file__).parent/"demo.env")scope_id=demo_env_vars.get("UNIQUE_SCOPE_ID")or"unknown"# Search for specific content filescontents=kb_service.search_contents(where={"title":{"contains":"manual"}},)