J.P. Pérez Tejada commited on
Commit
2471c16
·
1 Parent(s): 371a7b1

Implement lazy initialization for embedding function and add API key setter in ChromaDB class.

Browse files
gnosis/chroma_client.py CHANGED
@@ -11,13 +11,29 @@ class ChromaDB:
11
  """Initialize the client."""
12
  self.client = chromadb.PersistentClient(path=path)
13
  self.api_key = api_key
14
- self.embedding_function = OpenAIEmbeddingFunction(
15
- api_key=self.api_key, model_name="text-embedding-3-small"
16
- )
17
  self.client.heartbeat()
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def get_collection(self, name):
20
  """Get a Chroma collection."""
 
 
21
  try:
22
  collection = self.client.get_collection(
23
  name=name,
@@ -29,6 +45,8 @@ class ChromaDB:
29
 
30
  def create_collection(self, name):
31
  """Create a Chroma collection."""
 
 
32
  try:
33
  collection = self.client.get_or_create_collection(
34
  name=name,
 
11
  """Initialize the client."""
12
  self.client = chromadb.PersistentClient(path=path)
13
  self.api_key = api_key
14
+ self._embedding_function = None # ← lazy, not created yet
 
 
15
  self.client.heartbeat()
16
 
17
+ @property
18
+ def embedding_function(self):
19
+ """Create embedding function only when API key is available."""
20
+ if not self.api_key:
21
+ return None
22
+ if self._embedding_function is None:
23
+ self._embedding_function = OpenAIEmbeddingFunction(
24
+ api_key=self.api_key, model_name="text-embedding-3-small"
25
+ )
26
+ return self._embedding_function
27
+
28
+ def set_api_key(self, api_key):
29
+ """Update the API key and reset the embedding function."""
30
+ self.api_key = api_key
31
+ self._embedding_function = None # force recreation with new key
32
+
33
  def get_collection(self, name):
34
  """Get a Chroma collection."""
35
+ if not self.embedding_function:
36
+ return st.error("Add your OpenAI API key first.")
37
  try:
38
  collection = self.client.get_collection(
39
  name=name,
 
45
 
46
  def create_collection(self, name):
47
  """Create a Chroma collection."""
48
+ if not self.embedding_function:
49
+ return st.error("Add your OpenAI API key first.")
50
  try:
51
  collection = self.client.get_or_create_collection(
52
  name=name,
gnosis/components/handlers.py CHANGED
@@ -8,6 +8,8 @@ def set_api_key():
8
  """Set the OpenAI API key."""
9
  openai.api_key = st.session_state.api_key
10
  st.session_state.api_message = gm.api_message(openai.api_key)
 
 
11
 
12
 
13
  def click_wk_button():
 
8
  """Set the OpenAI API key."""
9
  openai.api_key = st.session_state.api_key
10
  st.session_state.api_message = gm.api_message(openai.api_key)
11
+ if "chroma_db" in st.session_state:
12
+ st.session_state.chroma_db.set_api_key(openai.api_key)
13
 
14
 
15
  def click_wk_button():