Elffuss BraidHub

kikocis/lancedb public

main · 20.3 KiBRenderedRawPermalink
1**phidata** is a framework for building **AI Assistants** with long-term memory, contextual knowledge, and the ability to take actions using function calling. It helps turn general-purpose LLMs into specialized assistants tailored to your use case by extending its capabilities using **memory**, **knowledge**, and **tools**.
2
3- **Memory**: Stores chat history in a **database** and enables LLMs to have long-term conversations.
4- **Knowledge**: Stores information in a **vector database** and provides LLMs with business context. (Here we will use LanceDB)
5- **Tools**: Enable LLMs to take actions like pulling data from an **API**, **sending emails** or **querying a database**, etc.
6
7![example](https://raw.githubusercontent.com/lancedb/assets/refs/heads/main/docs/assets/integration/phidata_assistant.png)
8
9Memory & knowledge make LLMs smarter while tools make them autonomous.
10
11LanceDB is a vector database and its integration into phidata makes it easy for us to provide a **knowledge base** to LLMs. It enables us to store information as [embeddings](../embeddings/understanding_embeddings.md) and search for the **results** similar to ours using **query**.
12
13??? Question "What is Knowledge Base?"
14 Knowledge Base is a database of information that the Assistant can search to improve its responses. This information is stored in a vector database and provides LLMs with business context, which makes them respond in a context-aware manner.
15
16 While any type of storage can act as a knowledge base, vector databases offer the best solution for retrieving relevant results from dense information quickly.
17
18Let's see how using LanceDB inside phidata helps in making LLM more useful:
19
20## Prerequisites: install and import necessary dependencies
21
22**Create a virtual environment**
23
241. install virtualenv package
25 ```python
26 pip install virtualenv
27 ```
282. Create a directory for your project and go to the directory and create a virtual environment inside it.
29 ```python
30 mkdir phi
31 ```
32 ```python
33 cd phi
34 ```
35 ```python
36 python -m venv phidata_
37 ```
38
39**Activating virtual environment**
40
411. from inside the project directory, run the following command to activate the virtual environment.
42 ```python
43 phidata_/Scripts/activate
44 ```
45
46**Install the following packages in the virtual environment**
47```python
48pip install lancedb phidata youtube_transcript_api openai ollama pandas numpy
49```
50
51**Create python files and import necessary libraries**
52
53You need to create two files - `transcript.py` and `ollama_assistant.py` or `openai_assistant.py`
54
55=== "openai_assistant.py"
56
57 ```python
58 import os, openai
59 from rich.prompt import Prompt
60 from phi.assistant import Assistant
61 from phi.knowledge.text import TextKnowledgeBase
62 from phi.vectordb.lancedb import LanceDb
63 from phi.llm.openai import OpenAIChat
64 from phi.embedder.openai import OpenAIEmbedder
65 from transcript import extract_transcript
66
67 if "OPENAI_API_KEY" not in os.environ:
68 # OR set the key here as a variable
69 openai.api_key = "sk-..."
70
71 # The code below creates a file "transcript.txt" in the directory, the txt file will be used below
72 youtube_url = "https://www.youtube.com/watch?v=Xs33-Gzl8Mo"
73 segment_duration = 20
74 transcript_text,dict_transcript = extract_transcript(youtube_url,segment_duration)
75 ```
76
77=== "ollama_assistant.py"
78
79 ```python
80 from rich.prompt import Prompt
81 from phi.assistant import Assistant
82 from phi.knowledge.text import TextKnowledgeBase
83 from phi.vectordb.lancedb import LanceDb
84 from phi.llm.ollama import Ollama
85 from phi.embedder.ollama import OllamaEmbedder
86 from transcript import extract_transcript
87
88 # The code below creates a file "transcript.txt" in the directory, the txt file will be used below
89 youtube_url = "https://www.youtube.com/watch?v=Xs33-Gzl8Mo"
90 segment_duration = 20
91 transcript_text,dict_transcript = extract_transcript(youtube_url,segment_duration)
92 ```
93
94=== "transcript.py"
95
96 ``` python
97 from youtube_transcript_api import YouTubeTranscriptApi
98 import re
99
100 def smodify(seconds):
101 hours, remainder = divmod(seconds, 3600)
102 minutes, seconds = divmod(remainder, 60)
103 return f"{int(hours):02}:{int(minutes):02}:{int(seconds):02}"
104
105 def extract_transcript(youtube_url,segment_duration):
106 # Extract video ID from the URL
107 video_id = re.search(r'(?<=v=)[\w-]+', youtube_url)
108 if not video_id:
109 video_id = re.search(r'(?<=be/)[\w-]+', youtube_url)
110 if not video_id:
111 return None
112
113 video_id = video_id.group(0)
114
115 # Attempt to fetch the transcript
116 try:
117 # Try to get the official transcript
118 transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en'])
119 except Exception:
120 # If no official transcript is found, try to get auto-generated transcript
121 try:
122 transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
123 for transcript in transcript_list:
124 transcript = transcript.translate('en').fetch()
125 except Exception:
126 return None
127
128 # Format the transcript into 120s chunks
129 transcript_text,dict_transcript = format_transcript(transcript,segment_duration)
130 # Open the file in write mode, which creates it if it doesn't exist
131 with open("transcript.txt", "w",encoding="utf-8") as file:
132 file.write(transcript_text)
133 return transcript_text,dict_transcript
134
135 def format_transcript(transcript,segment_duration):
136 chunked_transcript = []
137 chunk_dict = []
138 current_chunk = []
139 current_time = 0
140 # 2 minutes in seconds
141 start_time_chunk = 0 # To track the start time of the current chunk
142
143 for segment in transcript:
144 start_time = segment['start']
145 end_time_x = start_time + segment['duration']
146 text = segment['text']
147
148 # Add text to the current chunk
149 current_chunk.append(text)
150
151 # Update the current time with the duration of the current segment
152 # The duration of the current segment is given by segment['start'] - start_time_chunk
153 if current_chunk:
154 current_time = start_time - start_time_chunk
155
156 # If current chunk duration reaches or exceeds 2 minutes, save the chunk
157 if current_time >= segment_duration:
158 # Use the start time of the first segment in the current chunk as the timestamp
159 chunked_transcript.append(f"[{smodify(start_time_chunk)} to {smodify(end_time_x)}] " + " ".join(current_chunk))
160 current_chunk = re.sub(r'[\xa0\n]', lambda x: '' if x.group() == '\xa0' else ' ', "\n".join(current_chunk))
161 chunk_dict.append({"timestamp":f"[{smodify(start_time_chunk)} to {smodify(end_time_x)}]", "text": "".join(current_chunk)})
162 current_chunk = [] # Reset the chunk
163 start_time_chunk = start_time + segment['duration'] # Update the start time for the next chunk
164 current_time = 0 # Reset current time
165
166 # Add any remaining text in the last chunk
167 if current_chunk:
168 chunked_transcript.append(f"[{smodify(start_time_chunk)} to {smodify(end_time_x)}] " + " ".join(current_chunk))
169 current_chunk = re.sub(r'[\xa0\n]', lambda x: '' if x.group() == '\xa0' else ' ', "\n".join(current_chunk))
170 chunk_dict.append({"timestamp":f"[{smodify(start_time_chunk)} to {smodify(end_time_x)}]", "text": "".join(current_chunk)})
171
172 return "\n\n".join(chunked_transcript), chunk_dict
173 ```
174
175!!! warning
176 If creating Ollama assistant, download and install Ollama [from here](https://ollama.com/) and then run the Ollama instance in the background. Also, download the required models using `ollama pull <model-name>`. Check out the models [here](https://ollama.com/library)
177
178
179**Run the following command to deactivate the virtual environment if needed**
180```python
181deactivate
182```
183
184## **Step 1** - Create a Knowledge Base for AI Assistant using LanceDB
185
186=== "openai_assistant.py"
187
188 ```python
189 # Create knowledge Base with OpenAIEmbedder in LanceDB
190 knowledge_base = TextKnowledgeBase(
191 path="transcript.txt",
192 vector_db=LanceDb(
193 embedder=OpenAIEmbedder(api_key = openai.api_key),
194 table_name="transcript_documents",
195 uri="./t3mp/.lancedb",
196 ),
197 num_documents = 10
198 )
199 ```
200
201=== "ollama_assistant.py"
202
203 ```python
204 # Create knowledge Base with OllamaEmbedder in LanceDB
205 knowledge_base = TextKnowledgeBase(
206 path="transcript.txt",
207 vector_db=LanceDb(
208 embedder=OllamaEmbedder(model="nomic-embed-text",dimensions=768),
209 table_name="transcript_documents",
210 uri="./t2mp/.lancedb",
211 ),
212 num_documents = 10
213 )
214 ```
215Check out the list of **embedders** supported by **phidata** and their usage [here](https://docs.phidata.com/embedder/introduction).
216
217Here we have used `TextKnowledgeBase`, which loads text/docx files to the knowledge base.
218
219Let's see all the parameters that `TextKnowledgeBase` takes -
220
221| Name| Type | Purpose | Default |
222|:----|:-----|:--------|:--------|
223|`path`|`Union[str, Path]`| Path to text file(s). It can point to a single text file or a directory of text files.| provided by user |
224|`formats`|`List[str]`| File formats accepted by this knowledge base. |`[".txt"]`|
225|`vector_db`|`VectorDb`| Vector Database for the Knowledge Base. phidata provides a wrapper around many vector DBs, you can import it like this - `from phi.vectordb.lancedb import LanceDb` | provided by user |
226|`num_documents`|`int`| Number of results (documents/vectors) that vector search should return. |`5`|
227|`reader`|`TextReader`| phidata provides many types of reader objects which read data, clean it and create chunks of data, encapsulate each chunk inside an object of the `Document` class, and return **`List[Document]`**. | `TextReader()` |
228|`optimize_on`|`int`| It is used to specify the number of documents on which to optimize the vector database. Supposed to create an index. |`1000`|
229
230??? Tip "Wonder! What is `Document` class?"
231 We know that, before storing the data in vectorDB, we need to split the data into smaller chunks upon which embeddings will be created and these embeddings along with the chunks will be stored in vectorDB. When the user queries over the vectorDB, some of these embeddings will be returned as the result based on the semantic similarity with the query.
232
233 When the user queries over vectorDB, the queries are converted into embeddings, and a nearest neighbor search is performed over these query embeddings which returns the embeddings that correspond to most semantically similar chunks(parts of our data) present in vectorDB.
234
235 Here, a “Document” is a class in phidata. Since there is an option to let phidata create and manage embeddings, it splits our data into smaller chunks(as expected). It does not directly create embeddings on it. Instead, it takes each chunk and encapsulates it inside the object of the `Document` class along with various other metadata related to the chunk. Then embeddings are created on these `Document` objects and stored in vectorDB.
236
237 ```python
238 class Document(BaseModel):
239 """Model for managing a document"""
240
241 content: str # <--- here data of chunk is stored
242 id: Optional[str] = None
243 name: Optional[str] = None
244 meta_data: Dict[str, Any] = {}
245 embedder: Optional[Embedder] = None
246 embedding: Optional[List[float]] = None
247 usage: Optional[Dict[str, Any]] = None
248 ```
249
250However, using phidata you can load many other types of data in the knowledge base(other than text). Check out [phidata Knowledge Base](https://docs.phidata.com/knowledge/introduction) for more information.
251
252Let's dig deeper into the `vector_db` parameter and see what parameters `LanceDb` takes -
253
254| Name| Type | Purpose | Default |
255|:----|:-----|:--------|:--------|
256|`embedder`|`Embedder`| phidata provides many Embedders that abstract the interaction with embedding APIs and utilize it to generate embeddings. Check out other embedders [here](https://docs.phidata.com/embedder/introduction) | `OpenAIEmbedder` |
257|`distance`|`List[str]`| The choice of distance metric used to calculate the similarity between vectors, which directly impacts search results and performance in vector databases. |`Distance.cosine`|
258|`connection`|`lancedb.db.LanceTable`| LanceTable can be accessed through `.connection`. You can connect to an existing table of LanceDB, created outside of phidata, and utilize it. If not provided, it creates a new table using `table_name` parameter and adds it to `connection`. |`None`|
259|`uri`|`str`| It specifies the directory location of **LanceDB database** and establishes a connection that can be used to interact with the database. | `"/tmp/lancedb"` |
260|`table_name`|`str`| If `connection` is not provided, it initializes and connects to a new **LanceDB table** with a specified(or default) name in the database present at `uri`. |`"phi"`|
261|`nprobes`|`int`| It refers to the number of partitions that the search algorithm examines to find the nearest neighbors of a given query vector. Higher values will yield better recall (more likely to find vectors if they exist) at the expense of latency. |`20`|
262
263
264!!! note
265 Since we just initialized the KnowledgeBase. The VectorDB table that corresponds to this Knowledge Base is not yet populated with our data. It will be populated in **Step 3**, once we perform the `load` operation.
266
267 You can check the state of the LanceDB table using - `knowledge_base.vector_db.connection.to_pandas()`
268
269Now that the Knowledge Base is initialized, , we can go to **step 2**.
270
271## **Step 2** - Create an assistant with our choice of LLM and reference to the knowledge base.
272
273
274=== "openai_assistant.py"
275
276 ```python
277 # define an assistant with gpt-4o-mini llm and reference to the knowledge base created above
278 assistant = Assistant(
279 llm=OpenAIChat(model="gpt-4o-mini", max_tokens=1000, temperature=0.3,api_key = openai.api_key),
280 description="""You are an Expert in explaining youtube video transcripts. You are a bot that takes transcript of a video and answer the question based on it.
281
282 This is transcript for the above timestamp: {relevant_document}
283 The user input is: {user_input}
284 generate highlights only when asked.
285 When asked to generate highlights from the video, understand the context for each timestamp and create key highlight points, answer in following way -
286 [timestamp] - highlight 1
287 [timestamp] - highlight 2
288 ... so on
289
290 Your task is to understand the user question, and provide an answer using the provided contexts. Your answers are correct, high-quality, and written by an domain expert. If the provided context does not contain the answer, simply state,'The provided context does not have the answer.'""",
291 knowledge_base=knowledge_base,
292 add_references_to_prompt=True,
293 )
294 ```
295
296=== "ollama_assistant.py"
297
298 ```python
299 # define an assistant with llama3.1 llm and reference to the knowledge base created above
300 assistant = Assistant(
301 llm=Ollama(model="llama3.1"),
302 description="""You are an Expert in explaining youtube video transcripts. You are a bot that takes transcript of a video and answer the question based on it.
303
304 This is transcript for the above timestamp: {relevant_document}
305 The user input is: {user_input}
306 generate highlights only when asked.
307 When asked to generate highlights from the video, understand the context for each timestamp and create key highlight points, answer in following way -
308 [timestamp] - highlight 1
309 [timestamp] - highlight 2
310 ... so on
311
312 Your task is to understand the user question, and provide an answer using the provided contexts. Your answers are correct, high-quality, and written by an domain expert. If the provided context does not contain the answer, simply state,'The provided context does not have the answer.'""",
313 knowledge_base=knowledge_base,
314 add_references_to_prompt=True,
315 )
316 ```
317
318Assistants add **memory**, **knowledge**, and **tools** to LLMs. Here we will add only **knowledge** in this example.
319
320Whenever we will give a query to LLM, the assistant will retrieve relevant information from our **Knowledge Base**(table in LanceDB) and pass it to LLM along with the user query in a structured way.
321
322- The `add_references_to_prompt=True` always adds information from the knowledge base to the prompt, regardless of whether it is relevant to the question.
323
324To know more about an creating assistant in phidata, check out [phidata docs](https://docs.phidata.com/assistants/introduction) here.
325
326## **Step 3** - Load data to Knowledge Base.
327
328```python
329# load out data into the knowledge_base (populating the LanceTable)
330assistant.knowledge_base.load(recreate=False)
331```
332The above code loads the data to the Knowledge Base(LanceDB Table) and now it is ready to be used by the assistant.
333
334| Name| Type | Purpose | Default |
335|:----|:-----|:--------|:--------|
336|`recreate`|`bool`| If True, it drops the existing table and recreates the table in the vectorDB. |`False`|
337|`upsert`|`bool`| If True and the vectorDB supports upsert, it will upsert documents to the vector db. | `False` |
338|`skip_existing`|`bool`| If True, skips documents that already exist in the vectorDB when inserting. |`True`|
339
340??? tip "What is upsert?"
341 Upsert is a database operation that combines "update" and "insert". It updates existing records if a document with the same identifier does exist, or inserts new records if no matching record exists. This is useful for maintaining the most current information without manually checking for existence.
342
343During the Load operation, phidata directly interacts with the LanceDB library and performs the loading of the table with our data in the following steps -
344
3451. **Creates** and **initializes** the table if it does not exist.
346
3472. Then it **splits** our data into smaller **chunks**.
348
349 ??? question "How do they create chunks?"
350 **phidata** provides many types of **Knowledge Bases** based on the type of data. Most of them :material-information-outline:{ title="except LlamaIndexKnowledgeBase and LangChainKnowledgeBase"} has a property method called `document_lists` of type `Iterator[List[Document]]`. During the load operation, this property method is invoked. It traverses on the data provided by us (in this case, a text file(s)) using `reader`. Then it **reads**, **creates chunks**, and **encapsulates** each chunk inside a `Document` object and yields **lists of `Document` objects** that contain our data.
351
3523. Then **embeddings** are created on these chunks are **inserted** into the LanceDB Table
353
354 ??? question "How do they insert your data as different rows in LanceDB Table?"
355 The chunks of your data are in the form - **lists of `Document` objects**. It was yielded in the step above.
356
357 for each `Document` in `List[Document]`, it does the following operations:
358
359 - Creates embedding on `Document`.
360 - Cleans the **content attribute**(chunks of our data is here) of `Document`.
361 - Prepares data by creating `id` and loading `payload` with the metadata related to this chunk. (1)
362 { .annotate }
363
364 1. Three columns will be added to the table - `"id"`, `"vector"`, and `"payload"` (payload contains various metadata including **`content`**)
365
366 - Then add this data to LanceTable.
367
3684. Now the internal state of `knowledge_base` is changed (embeddings are created and loaded in the table ) and it **ready to be used by assistant**.
369
370## **Step 4** - Start a cli chatbot with access to the Knowledge base
371
372```python
373# start cli chatbot with knowledge base
374assistant.print_response("Ask me about something from the knowledge base")
375while True:
376 message = Prompt.ask(f"[bold] :sunglasses: User [/bold]")
377 if message in ("exit", "bye"):
378 break
379 assistant.print_response(message, markdown=True)
380```
381
382
383For more information and amazing cookbooks of phidata, read the [phidata documentation](https://docs.phidata.com/introduction) and also visit [LanceDB x phidata docmentation](https://docs.phidata.com/vectordb/lancedb).