环境准备
# 1. 安装ollama
# 2. 执行:
ollama serve
# 3. 另开窗口执行
ollama pull qwen2.5:7b
git clone https://github.com/mingjiegao/llamaIndex_example
cd llamaIndex_example
python -m venv venv
pip install -r requirements.txt
LlamaIndex 入门示例 1: 最简单的 LLM 对话
python 01_simple_llm_chat.py
╔══════════════════════════════════════════════════════════════╗
║ LlamaIndex 入门示例 - LLM 基础对话 ║
╠══════════════════════════════════════════════════════════════╣
║ 确保已启动 Ollama 并下载模型: ║
║ ollama pull qwen2.5:7b ║
╚══════════════════════════════════════════════════════════════╝
============================================================
示例1: 简单单轮对话
============================================================
提问: 请用一句话解释什么是 Python
回答: Python 是一种高级编程语言,强调代码 readability 和简洁的语法(通常比Java或C++更简洁)。
============================================================
示例2: 使用消息列表(带系统提示词)
============================================================
系统设定: 你是一个幽默风趣的编程导师,擅长用生动的比喻解释技术概念。回答要简短有趣。
用户提问: 什么是变量?
AI回答: 变量啊,就像你的小钱包,你可以随时存点钱进去,也可以随时拿出去花。编程时,你给它赋值就是存钱,使用它的值就是取钱。只不过,这个钱包能装各种各样的"钱"------数字、文字甚至是一堆代码!
============================================================
示例3: 多轮对话(保持上下文)
============================================================
--- 第一轮 ---
用户: 我叫小明,我正在学习 Python
AI: 你好,小明!很高兴听到你在学习Python。如果你有任何关于Python的问题或需要帮助的地方,随时可以问我。加油!
--- 第二轮 ---
用户: 我叫什么名字?
AI: 你叫小明。
--- 完整消息历史 ---
[0] system: 你是一个友好的 AI 助手,请简洁地回答问题。...
[1] user: 我叫小明,我正在学习 Python...
[2] assistant: 你好,小明!很高兴听到你在学习Python。如果你有任何关于Python的问题或需要帮助的地方,随时...
[3] user: 我叫什么名字?...
============================================================
示例4: 流式输出(打字机效果)
============================================================
用户: 请用3个要点介绍 LlamaIndex 框架的核心功能
AI: LlamaIndex 是一个用于构建基于索引的知识库和进行复杂查询的强大框架。以下是其核心功能的三个要点:
1. **灵活的数据结构支持**:
- LlamaIndex 支持多种数据结构,包括但不限于文本、代码、数据库记录等。它通过将原始数据转换为索引节点,并将这些节点组织成多级链接的图结构来处理不同类型的数据。
- 这种灵活性使得用户可以根据具体需求选择或自定义合适的结构化方式。
2. **高效的查询与检索机制**:
- LlamaIndex 采用先进的算法和优化策略,能够高效地执行复杂查询。它支持全文搜索、部分匹配等操作,并且可以进行多条件组合查询。
- 同时还提供了丰富的查询语言和API接口,便于用户通过自然语言或编程方式构建复杂的查询请求。
3. **易于扩展与定制的架构设计**:
- LlamaIndex 提供了高度模块化的设计思路,允许开发者轻松添加新的数据源接入点、节点处理器等组件。
- 它还支持通过配置文件来调整框架的行为和性能参数,使得用户可以根据实际应用场景进行灵活
调整。
============================================================
所有示例运行完成!
============================================================
LlamaIndex 入门示例 2: RAG(检索增强生成)
python 02_simple_rag.py
╔══════════════════════════════════════════════════════════════╗
║ LlamaIndex 入门示例 - RAG 检索增强生成 ║
╠══════════════════════════════════════════════════════════════╣
║ 确保已启动 Ollama 并下载模型: ║
║ ollama pull qwen2.5:7b ║
║ ║
║ 首次运行会下载 embedding 模型(约 100MB) ║
╚══════════════════════════════════════════════════════════════╝
============================================================
步骤1: 配置模型
============================================================
modules.json: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 349/349 [00:00<00:00, 217kB/s]
config_sentence_transformers.json: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 124/124 [00:00<00:00, 260kB/s]
README.md: 27.7kB [00:00, 11.5MB/s]
sentence_bert_config.json: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 52.0/52.0 [00:00<00:00, 135kB/s]
config.json: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 776/776 [00:00<00:00, 2.07MB/s]
model.safetensors: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 95.8M/95.8M [00:25<00:00, 3.74MB/s]
Loading weights: 100%|████████████████████████████████████████████████████████████████████████████████████████| 71/71 [00:00<00:00, 5280.72it/s, Materializing param=pooler.dense.weight]
BertModel LOAD REPORT from: BAAI/bge-small-zh-v1.5
Key | Status | |
------------------------+------------+--+-
embeddings.position_ids | UNEXPECTED | |
Notes:
- UNEXPECTED :can be ignored when loading from different task/architecture; not ok if you expect identical arch.
tokenizer_config.json: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 367/367 [00:00<00:00, 660kB/s]
vocab.txt: 110kB [00:00, 3.35MB/s]
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
tokenizer.json: 439kB [00:00, 4.11MB/s]
special_tokens_map.json: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 125/125 [00:00<00:00, 229kB/s]
config.json: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 190/190 [00:00<00:00, 406kB/s]
✓ LLM 配置完成: qwen2.5:7b (Ollama)
✓ Embedding 配置完成: bge-small-zh-v1.5
============================================================
步骤2: 准备文档数据
============================================================
✓ 创建了 3 个文档
[1] python_intro: 209 字符
[2] llamaindex_intro: 281 字符
[3] django_intro: 255 字符
============================================================
步骤3: 构建向量索引
============================================================
正在构建索引(首次可能需要下载 embedding 模型)...
Parsing nodes: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 4177.59it/s]
Generating embeddings: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 21.34it/s]
✓ 索引构建完成
============================================================
步骤4: 查询测试
============================================================
--- 查询 1 ---
问题: Python 是什么?有什么特点?
回答: Python 是一种高级编程语言。它的设计哲学注重代码的可读性和简洁性,并支持面向对象、函数式和过程式等多种编程范式。
相关来源:
- python_intro (相似度: 0.6708)
- django_intro (相似度: 0.5498)
--- 查询 2 ---
问题: LlamaIndex 可以做什么?
回答: LlamaIndex 可以用于构建数据驱动的应用程序,其核心功能包括数据连接、创建索引、查询处理以及使用 Agent 进行交互。它支持多种数据源类型,如 PDF、Word 文档、网页内容、数据库和 API 等,并且能够与不同类型的语言模型(例如 OpenAI、Ollama 和 HuggingFace)配合工作。此外,通过 LlamaIndex 可以快速搭建 RAG(检索增强生成)系统。
相关来源:
- llamaindex_intro (相似度: 0.6476)
- django_intro (相似度: 0.3527)
--- 查询 3 ---
问题: Django 和 DRF 是什么关系?
回答: Django 是一个 Web 框架,提供了丰富的功能如 ORM、Admin 后台等。而 Django REST Framework (DRF) 是基于 Django 的一个专门用于构建 RESTful API 的框架。因此,DRF 可以视为 Django 下的一个子框架或扩展模块,专注于提供更便捷的 RESTful API 开发能力。
相关来源:
- django_intro (相似度: 0.6082)
- llamaindex_intro (相似度: 0.3803)
============================================================
额外示例: Chat Engine(多轮对话)
============================================================
--- 对话 1 ---
用户: LlamaIndex 有哪些核心功能?
Querying with: LlamaIndex 有哪些核心功能?
AI: LlamaIndex 的核心功能包括数据连接、数据索引、查询引擎以及 Agent。
--- 对话 2 ---
用户: 这些功能中,哪个最常用?
Querying with: 在 LlamaIndex 的核心功能中,哪一个是最常用的?
AI: 在 LlamaIndex 的核心功能中,并未明确指出哪个是最常用的。不过,在实际应用中,查询引擎通常是一个非常常用的功能,因为它直接支持用户通过自然语言进行信息检索和问题查询。
============================================================
RAG 示例运行完成!
============================================================
LlamaIndex 入门示例 3: Agent(智能代理)
python 03_simple_agent.py
╔══════════════════════════════════════════════════════════════╗
║ LlamaIndex 入门示例 - Agent 智能代理 ║
╠══════════════════════════════════════════════════════════════╣
║ 确保已启动 Ollama 并下载模型: ║
║ ollama pull qwen2.5:7b ║
║ ║
║ Agent 会调用工具来完成任务,观察 verbose 输出 ║
║ 可以看到 LLM 的推理过程 ║
╚══════════════════════════════════════════════════════════════╝
============================================================
Agent 工作流程说明
============================================================
ReAct Agent 的工作流程:
┌─────────────────────────────────────────────────────────┐
│ 用户提问: "北京今天天气怎么样?" │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ Thought (思考): │
│ "用户想知道北京的天气,我需要调用 get_weather 工具" │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ Action (行动): │
│ 调用工具: get_weather(city="北京") │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ Observation (观察): │
│ 工具返回: "北京天气: 晴, 温度 15°C, 湿度 45%" │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ Thought (思考): │
│ "我已经获得了天气信息,可以回答用户了" │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ Final Answer (最终回答): │
│ "北京今天天气晴朗,气温 15°C,湿度 45%,适合出行。" │
└─────────────────────────────────────────────────────────┘
============================================================
步骤1: 创建工具
============================================================
✓ 创建了 4 个工具:
- get_current_time: 获取当前时间,返回格式为 YYYY-MM-DD HH:MM:SS...
- calculate: 计算数学表达式,支持加减乘除和括号。参数 expression: 数学表达式字符串...
- get_weather: 获取城市天气信息。参数 city: 城市名称,如'北京'...
- search_knowledge: 在知识库中搜索信息。参数 query: 搜索关键词...
============================================================
步骤2: 创建 Agent
============================================================
/Users/gaomingjie/root/Projects/py/znyw/test/llamaindex/llamaIndex_example/venv/lib/python3.12/site-packages/llama_index/core/agent/react/base.py:154: DeprecationWarning: Call to deprecated class ReActAgent. (ReActAgent has been rewritten and replaced by llama_index.core.agent.workflow.ReActAgent.
This implementation will be removed in a v0.13.0 and the new implementation will be promoted to the `from llama_index.core.agent import ReActAgent` path.
See the docs for more information: https://docs.llamaindex.ai/en/stable/understanding/agent/)
return cls(
/Users/gaomingjie/root/Projects/py/znyw/test/llamaindex/llamaIndex_example/venv/lib/python3.12/site-packages/deprecated/classic.py:184: DeprecationWarning: Call to deprecated class AgentRunner. (AgentRunner has been deprecated and is not maintained.
This implementation will be removed in a v0.13.0.
See the docs for more information on updated agent usage: https://docs.llamaindex.ai/en/stable/understanding/agent/)
return old_new1(cls, *args, **kwargs)
✓ ReActAgent 创建完成
============================================================
步骤3: 测试 Agent
============================================================
============================================================
测试 1: 现在几点了?
============================================================
> Running step 0937e0eb-8b05-4c9c-801b-48952f1bb9e4. Step input: 现在几点了?
Thought: The current language of the user is: Chinese. I need to use a tool to get the current time to answer the question.
Action: get_current_time
Action Input: {}
Observation: 2026-01-30 21:46:59
> Running step 646bf934-cf70-438f-9a24-52f9e6aa286c. Step input: None
Thought: I can answer without using any more tools. I'll use the user's language to answer
Answer: 现在的时间是21:46:59。
最终回答: 现在的时间是21:46:59。
============================================================
测试 2: 请帮我计算 (15 + 25) * 3 - 10
============================================================
> Running step 2220793f-f9ce-4248-9ff9-c349ccc40d0c. Step input: 请帮我计算 (15 + 25) * 3 - 10
Thought: 我需要使用calculate工具来帮助我解答这个问题。
Action: calculate
Action Input: {'expression': '(15 + 25) * 3 - 10'}
Observation: 计算结果: (15 + 25) * 3 - 10 = 110
> Running step 76395dba-c448-4372-94d5-3c4c8699d941. Step input: None
Thought: 我可以回答这个问题了。
Answer: 计算结果是110。
最终回答: 计算结果是110。
============================================================
测试 3: 北京今天天气怎么样?
============================================================
> Running step b618ceb1-e4f8-4d4a-b5b8-3ea28c728c65. Step input: 北京今天天气怎么样?
Thought: 我需要使用get_weather工具来获取北京市的天气信息。
Action: get_weather
Action Input: {'city': '北京'}
Observation: 北京天气: 晴, 温度 15°C, 湿度 45%
> Running step 5bffc82a-4a0f-4806-961f-7e4026be3095. Step input: None
Thought: 我已经得到了北京今天的天气情况,可以回答问题了。
Answer: 北京今天是晴天,温度是15°C,湿度为45%。
最终回答: 北京今天是晴天,温度是15°C,湿度为45%。
============================================================
测试 4: 什么是 LlamaIndex?
============================================================
> Running step 5dd7156c-69a2-402d-9940-7a8385f33d3d. Step input: 什么是 LlamaIndex?
Thought: 我需要搜索一下LlamaIndex的相关信息。
Action: search_knowledge
Action Input: {'query': 'LlamaIndex'}
Observation: 找到相关信息: LlamaIndex 是一个 LLM 应用框架,主要用于构建 RAG 和 Agent 应用。
> Running step 1d882dbf-609e-4ed7-9c03-9fb8b35bd257. Step input: None
Thought: 我可以回答这个问题了。
Answer: LlamaIndex是一个LLM应用框架,主要用于构建RAG和Agent应用。
最终回答: LlamaIndex是一个LLM应用框架,主要用于构建RAG和Agent应用。
============================================================
测试 5: 现在是什么时间?北京天气如何?
============================================================
> Running step 06580f3a-85a1-4532-bbfd-34d56ac7ef3f. Step input: 现在是什么时间?北京天气如何?
Thought: 我需要获取当前时间和北京的天气信息。
Action: get_current_time
Action Input: {}
Observation: 2026-01-30 21:48:22
> Running step bdaa02ff-9665-4bf8-8bac-c39dab2a5f21. Step input: None
Thought: 我已经获得了当前时间。接下来我需要查询北京的天气情况。
Action: get_weather
Action Input: {'city': '北京'}
Observation: 北京天气: 晴, 温度 15°C, 湿度 45%
> Running step 498b2834-519a-4529-a719-a8dd49eec0ac. Step input: None
Thought: 我已经获得了当前时间和北京的天气信息。现在可以回答用户的问题了。
Answer: 现在的时间是2026-01-30 21:48:22,北京今天的天气是晴天,温度为15°C,湿度为45%。
最终回答: 现在的时间是2026-01-30 21:48:22,北京今天的天气是晴天,温度为15°C,湿度为45%。
============================================================
Agent 示例运行完成!
============================================================