Skip to content

Commit 0eeeb91

Browse files
Merge pull request #2994 from milvus-io/update-tutorials
update docs
2 parents b7e084b + 79bd894 commit 0eeeb91

10 files changed

+1679
-204
lines changed

assets/hybrid_and_rerank.png

122 KB
Loading

site/en/integrations/build_RAG_with_milvus_and_crawl4ai.md

Lines changed: 388 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 343 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,343 @@
1+
---
2+
id: build_RAG_with_milvus_and_firecrawl.md
3+
summary: In this tutorial, we’ll show you how to build a Retrieval-Augmented Generation (RAG) pipeline using Milvus and Firecrawl. The pipeline integrates Firecrawl for web data scraping, Milvus for vector storage, and OpenAI for generating insightful, context-aware responses.
4+
title: Building RAG with Milvus and Firecrawl
5+
---
6+
7+
# Building RAG with Milvus and Firecrawl
8+
9+
<a href="https://colab.research.google.com/github/milvus-io/bootcamp/blob/master/bootcamp/tutorials/integration/build_RAG_with_milvus_and_firecrawl.ipynb" target="_parent">
10+
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
11+
</a>
12+
<a href="https://github.com/milvus-io/bootcamp/blob/master/bootcamp/tutorials/integration/build_RAG_with_milvus_and_firecrawl.ipynb" target="_blank">
13+
<img src="https://img.shields.io/badge/View%20on%20GitHub-555555?style=flat&logo=github&logoColor=white" alt="GitHub Repository"/>
14+
</a>
15+
16+
[Firecrawl](https://www.firecrawl.dev/) empowers developers to build AI applications with clean data scraped from any website. With advanced scraping, crawling, and data extraction capabilities, Firecrawl simplifies the process of converting website content into clean markdown or structured data for downstream AI workflows.
17+
18+
In this tutorial, we’ll show you how to build a Retrieval-Augmented Generation (RAG) pipeline using Milvus and Firecrawl. The pipeline integrates Firecrawl for web data scraping, Milvus for vector storage, and OpenAI for generating insightful, context-aware responses.
19+
20+
21+
## Preparation
22+
23+
### Dependencies and Environment
24+
25+
To start, install the required dependencies by running the following command:
26+
27+
28+
```shell
29+
$ pip install firecrawl-py pymilvus openai requests tqdm
30+
```
31+
32+
<div class="alert note">
33+
34+
If you are using Google Colab, to enable dependencies just installed, you may need to **restart the runtime** (click on the "Runtime" menu at the top of the screen, and select "Restart session" from the dropdown menu).
35+
36+
</div>
37+
38+
### Setting Up API Keys
39+
40+
To use Firecrawl to scrape data from the specified URL, you need to obtain a [FIRECRAWL_API_KEY](https://www.firecrawl.dev/) and set it as an environment variable. Also, we will use OpenAI as the LLM in this example. You should prepare the [OPENAI_API_KEY](https://platform.openai.com/docs/quickstart) as an environment variable as well.
41+
42+
43+
```python
44+
import os
45+
46+
os.environ["FIRECRAWL_API_KEY"] = "fc-***********"
47+
os.environ["OPENAI_API_KEY"] = "sk-***********"
48+
```
49+
50+
### Prepare the LLM and Embedding Model
51+
52+
We initialize the OpenAI client to prepare the embedding model.
53+
54+
55+
```python
56+
from openai import OpenAI
57+
58+
openai_client = OpenAI()
59+
```
60+
61+
Define a function to generate text embeddings using OpenAI client. We use the [text-embedding-3-small](https://platform.openai.com/docs/guides/embeddings) model as an example.
62+
63+
64+
```python
65+
def emb_text(text):
66+
return (
67+
openai_client.embeddings.create(input=text, model="text-embedding-3-small")
68+
.data[0]
69+
.embedding
70+
)
71+
```
72+
73+
Generate a test embedding and print its dimension and first few elements.
74+
75+
76+
```python
77+
test_embedding = emb_text("This is a test")
78+
embedding_dim = len(test_embedding)
79+
print(embedding_dim)
80+
print(test_embedding[:10])
81+
```
82+
83+
1536
84+
[0.009889289736747742, -0.005578675772994757, 0.00683477520942688, -0.03805781528353691, -0.01824733428657055, -0.04121600463986397, -0.007636285852640867, 0.03225184231996536, 0.018949154764413834, 9.352207416668534e-05]
85+
86+
87+
## Scrape Data Using Firecrawl
88+
89+
### Initialize the Firecrawl Application
90+
We will use the `firecrawl` library to scrape data from the specified URL in markdown format. Begin by initializing the Firecrawl application:
91+
92+
93+
```python
94+
from firecrawl import FirecrawlApp
95+
96+
app = FirecrawlApp(api_key=os.environ["FIRECRAWL_API_KEY"])
97+
```
98+
99+
### Scrape the Target Website
100+
Scrape the content from the target URL. The website [LLM-powered Autonomous Agents](https://lilianweng.github.io/posts/2023-06-23-agent/) provides an in-depth exploration of autonomous agent systems built using large language models (LLMs). We will use these content building a RAG system.
101+
102+
103+
104+
```python
105+
# Scrape a website:
106+
scrape_status = app.scrape_url(
107+
"https://lilianweng.github.io/posts/2023-06-23-agent/",
108+
params={"formats": ["markdown"]},
109+
)
110+
111+
markdown_content = scrape_status["markdown"]
112+
```
113+
114+
### Process the Scraped Content
115+
116+
To make the scraped content manageable for insertion into Milvus, we simply use "# " to separate the content, which can roughly separate the content of each main part of the scraped markdown file.
117+
118+
119+
```python
120+
def split_markdown_content(content):
121+
return [section.strip() for section in content.split("# ") if section.strip()]
122+
123+
124+
# Process the scraped markdown content
125+
sections = split_markdown_content(markdown_content)
126+
127+
# Print the first few sections to understand the structure
128+
for i, section in enumerate(sections[:3]):
129+
print(f"Section {i+1}:")
130+
print(section[:300] + "...")
131+
print("-" * 50)
132+
```
133+
134+
Section 1:
135+
Table of Contents
136+
137+
- [Agent System Overview](#agent-system-overview)
138+
- [Component One: Planning](#component-one-planning) - [Task Decomposition](#task-decomposition)
139+
- [Self-Reflection](#self-reflection)
140+
- [Component Two: Memory](#component-two-memory) - [Types of Memory](#types-of-memory)
141+
- [...
142+
--------------------------------------------------
143+
Section 2:
144+
Agent System Overview [\#](\#agent-system-overview)
145+
146+
In a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:
147+
148+
- **Planning**
149+
- Subgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling effi...
150+
--------------------------------------------------
151+
Section 3:
152+
Component One: Planning [\#](\#component-one-planning)
153+
154+
A complicated task usually involves many steps. An agent needs to know what they are and plan ahead.
155+
156+
#...
157+
--------------------------------------------------
158+
159+
160+
## Load Data into Milvus
161+
162+
### Create the collection
163+
164+
165+
```python
166+
from pymilvus import MilvusClient
167+
168+
milvus_client = MilvusClient(uri="./milvus_demo.db")
169+
collection_name = "my_rag_collection"
170+
```
171+
172+
<div class="alert note">
173+
174+
As for the argument of `MilvusClient`:
175+
- Setting the `uri` as a local file, e.g.`./milvus.db`, is the most convenient method, as it automatically utilizes [Milvus Lite](https://milvus.io/docs/milvus_lite.md) to store all data in this file.
176+
177+
- If you have large scale of data, you can set up a more performant Milvus server on [docker or kubernetes](https://milvus.io/docs/quickstart.md). In this setup, please use the server uri, e.g.`http://localhost:19530`, as your `uri`.
178+
179+
- If you want to use [Zilliz Cloud](https://zilliz.com/cloud), the fully managed cloud service for Milvus, adjust the `uri` and `token`, which correspond to the [Public Endpoint and Api key](https://docs.zilliz.com/docs/on-zilliz-cloud-console#free-cluster-details) in Zilliz Cloud.
180+
181+
</div>
182+
183+
Check if the collection already exists and drop it if it does.
184+
185+
186+
```python
187+
if milvus_client.has_collection(collection_name):
188+
milvus_client.drop_collection(collection_name)
189+
```
190+
191+
Create a new collection with specified parameters.
192+
193+
If we don’t specify any field information, Milvus will automatically create a default `id` field for primary key, and a `vector` field to store the vector data. A reserved JSON field is used to store non-schema-defined fields and their values.
194+
195+
196+
```python
197+
milvus_client.create_collection(
198+
collection_name=collection_name,
199+
dimension=embedding_dim,
200+
metric_type="IP", # Inner product distance
201+
consistency_level="Strong", # Strong consistency level
202+
)
203+
```
204+
205+
### Insert data
206+
207+
208+
```python
209+
from tqdm import tqdm
210+
211+
data = []
212+
213+
for i, section in enumerate(tqdm(sections, desc="Processing sections")):
214+
embedding = emb_text(section)
215+
data.append({"id": i, "vector": embedding, "text": section})
216+
217+
# Insert data into Milvus
218+
milvus_client.insert(collection_name=collection_name, data=data)
219+
```
220+
221+
Processing sections: 100%|██████████| 17/17 [00:08<00:00, 2.09it/s]
222+
223+
224+
225+
226+
227+
{'insert_count': 17, 'ids': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 'cost': 0}
228+
229+
230+
231+
## Build RAG
232+
233+
### Retrieve data for a query
234+
235+
Let’s specify a query question about the website we just scraped.
236+
237+
238+
239+
240+
```python
241+
question = "What are the main components of autonomous agents?"
242+
```
243+
244+
Search for the question in the collection and retrieve the semantic top-3 matches.
245+
246+
247+
```python
248+
search_res = milvus_client.search(
249+
collection_name=collection_name,
250+
data=[emb_text(question)],
251+
limit=3,
252+
search_params={"metric_type": "IP", "params": {}},
253+
output_fields=["text"],
254+
)
255+
```
256+
257+
Let’s take a look at the search results of the query
258+
259+
260+
261+
262+
```python
263+
import json
264+
265+
retrieved_lines_with_distances = [
266+
(res["entity"]["text"], res["distance"]) for res in search_res[0]
267+
]
268+
print(json.dumps(retrieved_lines_with_distances, indent=4))
269+
```
270+
271+
[
272+
[
273+
"Agent System Overview [\\#](\\#agent-system-overview)\n\nIn a LLM-powered autonomous agent system, LLM functions as the agent\u2019s brain, complemented by several key components:\n\n- **Planning**\n - Subgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\n - Reflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\n- **Memory**\n - Short-term memory: I would consider all the in-context learning (See [Prompt Engineering](https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/)) as utilizing short-term memory of the model to learn.\n - Long-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\n- **Tool use**\n - The agent learns to call external APIs for extra information that is missing from the model weights (often hard to change after pre-training), including current information, code execution capability, access to proprietary information sources and more.\n\n![](agent-overview.png)Fig. 1. Overview of a LLM-powered autonomous agent system.",
274+
0.6343474388122559
275+
],
276+
[
277+
"Table of Contents\n\n- [Agent System Overview](#agent-system-overview)\n- [Component One: Planning](#component-one-planning) - [Task Decomposition](#task-decomposition)\n - [Self-Reflection](#self-reflection)\n- [Component Two: Memory](#component-two-memory) - [Types of Memory](#types-of-memory)\n - [Maximum Inner Product Search (MIPS)](#maximum-inner-product-search-mips)\n- [Component Three: Tool Use](#component-three-tool-use)\n- [Case Studies](#case-studies) - [Scientific Discovery Agent](#scientific-discovery-agent)\n - [Generative Agents Simulation](#generative-agents-simulation)\n - [Proof-of-Concept Examples](#proof-of-concept-examples)\n- [Challenges](#challenges)\n- [Citation](#citation)\n- [References](#references)\n\nBuilding agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as [AutoGPT](https://github.com/Significant-Gravitas/Auto-GPT), [GPT-Engineer](https://github.com/AntonOsika/gpt-engineer) and [BabyAGI](https://github.com/yoheinakajima/babyagi), serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.",
278+
0.5715497732162476
279+
],
280+
[
281+
"Challenges [\\#](\\#challenges)\n\nAfter going through key ideas and demos of building LLM-centered agents, I start to see a couple common limitations:\n\n- **Finite context length**: The restricted context capacity limits the inclusion of historical information, detailed instructions, API call context, and responses. The design of the system has to work with this limited communication bandwidth, while mechanisms like self-reflection to learn from past mistakes would benefit a lot from long or infinite context windows. Although vector stores and retrieval can provide access to a larger knowledge pool, their representation power is not as powerful as full attention.\n\n- **Challenges in long-term planning and task decomposition**: Planning over a lengthy history and effectively exploring the solution space remain challenging. LLMs struggle to adjust plans when faced with unexpected errors, making them less robust compared to humans who learn from trial and error.\n\n- **Reliability of natural language interface**: Current agent system relies on natural language as an interface between LLMs and external components such as memory and tools. However, the reliability of model outputs is questionable, as LLMs may make formatting errors and occasionally exhibit rebellious behavior (e.g. refuse to follow an instruction). Consequently, much of the agent demo code focuses on parsing model output.",
282+
0.5009307265281677
283+
]
284+
]
285+
286+
287+
### Use LLM to get a RAG response
288+
289+
Convert the retrieved documents into a string format.
290+
291+
292+
293+
294+
```python
295+
context = "\n".join(
296+
[line_with_distance[0] for line_with_distance in retrieved_lines_with_distances]
297+
)
298+
```
299+
300+
Define system and user prompts for the Lanage Model. This prompt is assembled with the retrieved documents from Milvus.
301+
302+
303+
304+
305+
```python
306+
SYSTEM_PROMPT = """
307+
Human: You are an AI assistant. You are able to find answers to the questions from the contextual passage snippets provided.
308+
"""
309+
USER_PROMPT = f"""
310+
Use the following pieces of information enclosed in <context> tags to provide an answer to the question enclosed in <question> tags.
311+
<context>
312+
{context}
313+
</context>
314+
<question>
315+
{question}
316+
</question>
317+
"""
318+
```
319+
320+
Use OpenAI ChatGPT to generate a response based on the prompts.
321+
322+
323+
324+
325+
```python
326+
response = openai_client.chat.completions.create(
327+
model="gpt-4o",
328+
messages=[
329+
{"role": "system", "content": SYSTEM_PROMPT},
330+
{"role": "user", "content": USER_PROMPT},
331+
],
332+
)
333+
print(response.choices[0].message.content)
334+
```
335+
336+
The main components of a LLM-powered autonomous agent system are the Planning, Memory, and Tool use.
337+
338+
1. Planning: The agent breaks down large tasks into smaller, manageable subgoals, and can self-reflect and learn from past mistakes, refining its actions for future steps.
339+
340+
2. Memory: This includes short-term memory, which the model uses for in-context learning, and long-term memory, which allows the agent to retain and recall information over extended periods.
341+
342+
3. Tool use: This component allows the agent to call external APIs for additional information that is not available in the model weights, like current information, code execution capacity, and access to proprietary information sources.
343+

0 commit comments

Comments
 (0)