services.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from qcloud_cos import CosConfig
  2. from qcloud_cos import CosS3Client
  3. import tcvectordb
  4. from tcvectordb.model.ai_database import AIDatabase
  5. from tcvectordb.model.collection_view import CollectionView, Embedding, SplitterProcess, ParsingProcess
  6. from tcvectordb.model.index import Index
  7. from tcvectordb.exceptions import ServerInternalError
  8. from rich.console import Console
  9. from settings import settings
  10. console = Console()
  11. cos = CosS3Client(
  12. CosConfig(
  13. Region=settings.tencent_cloud.region,
  14. SecretId=settings.tencent_cloud.secret_id,
  15. SecretKey=settings.tencent_cloud.secret_key,
  16. ),
  17. )
  18. vdb = tcvectordb.RPCVectorDBClient(
  19. url=str(settings.VDB.url),
  20. username=settings.VDB.username,
  21. key=settings.VDB.key,
  22. )
  23. def create_ai_database_if_not_exists(database_name: str) -> AIDatabase:
  24. if vdb.exists_db(database_name):
  25. console.log(f'[green]Database "{database_name}" already exists.[/green]')
  26. return vdb.database(database_name)
  27. else:
  28. console.log(f'[green]Creating database "{database_name}"...[/green]')
  29. return vdb.create_ai_database(database_name)
  30. def create_collection_view_if_not_exists(database: AIDatabase, collection_name: str) -> CollectionView:
  31. try:
  32. console.log(f'[green]Checking if collection view "{collection_name}" exists...[/green]')
  33. return database.describe_collection_view(collection_name)
  34. except ServerInternalError as e:
  35. if not e.message.startswith(f'CollectionView not exist: {collection_name}'):
  36. raise e
  37. console.log(f'[green]Creating collection view "{collection_name}"...[/green]')
  38. return database.create_collection_view(
  39. collection_name,
  40. embedding=Embedding(
  41. language='multi',
  42. enable_words_embedding=True,
  43. ),
  44. splitter_process=SplitterProcess(
  45. append_title_to_chunk=False,
  46. append_keywords_to_chunk=True,
  47. chunk_splitter=None,
  48. ),
  49. parsing_process=ParsingProcess('VisionModelParsing'),
  50. index=Index(),
  51. )
  52. def create_db_collection_view_if_not_exists(database: str, collection: str) -> CollectionView:
  53. db = create_ai_database_if_not_exists(database)
  54. return db, create_collection_view_if_not_exists(db, collection)
  55. database, collection_view = create_db_collection_view_if_not_exists(
  56. settings.VDB.database,
  57. settings.VDB.collection,
  58. )
  59. console.log(f'[green]Collection view "{settings.VDB.collection}" is ready.[/green]')